import requests,time
from bs4 import BeautifulSoup
import p_mysql,json
class jxy_all():
    def xunhuan(self,gol_cookies):
        wrong = 0
        first_run = 0
        jishu = 0
        toufayu = False
        multiple = [1, 3, 7, 15, 31, 63, 127, 34, 55, 89, 144, 1, 1]
        maxwrong = 6
        global moni
        firstflag_vote = ''
        current_period = ''
        vote_retime = 0
        endf = 1
        wrongflag = False
        vote_list = []
        self.header = {"Accept": "text/html, application/xhtml+xml, */*",
                       "Accept-Encoding": "gzip, deflate",
                       "Accept-Language": "zh-CN",
                       "Connection": "Keep-Alive",
                       "Host": "www.juxiangyou.com",
                       "Referer": "http://www.juxiangyou.com/",
                       "User-Agent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64;Trident/5.0)"}
        post_head = {"Accept": "application/json, text/javascript, */*; q=0.01",
                     "Accept-Encoding": "gzip, deflate",
                     "Accept-Language": "zh-cn",
                     "Cache-Control": "no-cache",
                     "Connection": "Keep-Alive",
                     "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
                     "Host": "www.juxiangyou.com",
                     "Referer": "http://www.juxiangyou.com/fun/play/crazy28/index",
                     "User-Agent": "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)",
                     "X-Requested-With": "XMLHttpRequest"}
        self.url = 'http://www.juxiangyou.com/fun/play/crazy28/index'
        yinshu = 1
        list_v = []
        czlst = []
        c_time = time.strftime('%m-%d %H:%M', time.localtime(time.time()))
        try:
            req = requests.get(self.url, cookies=gol_cookies, headers=self.header)
            soup = BeautifulSoup(req.text, 'lxml')
            # 查询当前投注信息
            vote_info = soup.find('p', attrs={'class': 'time-static1'})
            # 第一步 找到当前期 这里必然找出当前期，目的是为了投注。
            if vote_info != None:
                if (vote_info.text).find('正在开奖') > 0:
                    print('正在开奖，等待5秒')
                    time.sleep(5)
                else:
                    # 如果没有开奖，则查询当前投注期
                    try:
                        vote_current = vote_info.find_all('span')
                        # 结束标识，查询
                        end_flag = (vote_info.text).find('截止投注')
                        if end_flag > 0:
                            # 即使投注了，当前期也需要展示出来，为投注判断
                            print(vote_current[0].string + '期已经截止投注')
                            current_period = vote_current[0].string
                        else:
                            print('当前期' + vote_current[0].string + '剩余' + vote_current[1].string + '秒投注')
                            vote_retime = int(vote_current[1].string)
                            current_period = vote_current[0].string
                    except Exception as e:
                        print('搜索资料出错，列表错误')
                        print('traceback.format_exc():%s' % traceback.format_exc())
            if current_period != '':
                # 添加保存第一次金币部分
                try:
                    current_jinbi = (soup.find('span', attrs={'class': 'J_udou'}).string).replace(',', '')
                except Exception as e:
                    print(repr(e))
                if firstflag_vote == '':
                    firstflag_vote = current_period
                    firstflag_jinbi = current_jinbi
                    config = configparser.ConfigParser()
                    config.read("Config_jxyfk28.ini")
                    config_title = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
                    try:
                        config.add_section(config_title)
                        config.set(config_title, "starttime：", config_title)
                        config.set(config_title, "firstvote：", firstflag_vote)
                        config.set(config_title, "firstjinbi", firstflag_jinbi)
                        config.write(open("Config_jxyfk28.ini", "w"))
                        tempa = config.sections()
                        newa = []
                        findtime = time.strftime('%Y-%m-%d', time.localtime(time.time()))
                        # print(findtime)
                        for x in tempa:
                            # print(x.find(findtime))
                            if x.find(findtime) >= 0:
                                newa.append(x)
                        todayfirstjinbi = int(config.get(newa[0], 'firstjinbi'))
                    except configparser.DuplicateSectionError:
                        print("Section already exists")
                # 循环采集部分
                mydb = p_mysql.MySQL()
                # 查询数据库最后一期，然后显示出来
                sql_text = "select period from jx_fk28 ORDER BY period DESC limit 1"
                sql_re = mydb.query(sql_text)
                if len(sql_re) <= 0:
                    endf = 44
                else:
                    endf = int((int(current_period) - int(sql_re[0][0])) / 25) + 1
                    if endf >= 44:
                        endf = 44
                self.up_dt_info.emit("需采集" + str(endf) + "页数")
                w = 1
                while w <= endf:
                    self.up_dt_info.emit("开始采集，第" + str(w) + "页---")
                    try:
                        base_time = int(time.time()) * 1000
                        x_sign = baseN(base_time, 36)
                        # 为header字典添加一个X-sign标识，毫秒级时间戳36进制
                        post_head['X-Sign'] = x_sign
                        # 服务器接受str格式，把字典格式json格式转化
                        a = json.dumps(
                            {"c": "quiz", "fun": "getEachList", "items": "crazy28", "pageSize": 23, "pageIndex": w})
                        b = json.dumps({"items": "crazy28"})
                        # 毫秒级时间戳，同时作为postdatspeed16a数据发现服务器
                        pst_data = {'jxy_parameter': a, 'timestamp': base_time, 'params': b,
                                    'xtpl': 'fun/private/jc-index-tbl'}
                        url = 'http://www.juxiangyou.com/fun/play/interaction'
                        # Post数据服务器，cookies使用登录页面与验证码 合并cookies提交
                        req_one = requests.post(url, data=pst_data, cookies=gol_cookies, headers=post_head,
                                                allow_redirects=False)
                        vote_data = json.loads(req_one.text)
                        if vote_data['code'] == 10000:
                            for x in vote_data['itemList']:
                                period = x['num']
                                vote_time = x['date']
                                jcjg = x['jcjg2']
                                state = x['state']
                                if state == 1:
                                    sql = "insert into jx_fk28 values ('" + period + "','" + vote_time + "','" + str(
                                        jcjg) + "')"
                                    mydb.query(sql)
                        w = w + 1
                    except Exception as e:
                        self.up_dt_info.emit("采集过程中，页面信息问题，重新采集该页")
                        print("错误:%s" % traceback.format_exc())
                        w = w - 1
                        if w <= 0:
                            w = 1
                self.up_dt_info.emit("采集完成")
                self.up_table_info.emit(req.text)
                # if moni == 1 and first_run == 0:
                #     wrong = firstwrong
                #     print('当我更新wrong时，我的值还是',firstwrong)
                if first_run == 0:
                    self.up_dt_info.emit('先搜索最近的一次错6')
                    remax = self.remaxwrong()
                    if int(current_period) - int(remax) <= 30:
                        moni = 0
                    first_run = 1
                    self.up_statusinfo.emit(
                        '第一次查询错六为: ' + str(remax) + " ,间隔期 : " + str(int(current_period) - int(remax)))
                    self.up_dt_info.emit('搜索结束')

                # 每一次，必须采集完成后，才开始从数据库中拿数据判断
                if vote_list:  # 如果不为空，说明上一次投注了，判断是否正确。
                    try:
                        vote_period = str(vote_list[-1]).strip()
                        sql = "select * from jx_fk28 where period='" + vote_period + "' limit 1"
                        redata = mydb.query(sql)
                        last_vote = redata[0][2]
                        # print('返回列表', vote_list, '查找返回投注期的结果', last_vote[0])
                        self.up_dt_info.emit('上期投注列表' + str(vote_list))
                        if int(last_vote) in vote_list:
                            print('投注正确,倍率清空')
                            self.up_lastinfo.emit((vote_period, '', '', last_vote, '正确', ''))
                            wrong = 0
                            if wrongflag == True and moni == 1:
                                wrongflag = False
                                toufayu = True
                                jishu = 0
                                moni = 0
                        else:
                            self.up_lastinfo.emit((vote_period, '', '', last_vote, '错误', ''))
                            if int(last_vote) > 0:
                                # print('投注错误,次数加 1 ,错误次数：', wrong)
                                wrong = wrong + 1
                                if wrong >= maxwrong:
                                    wrongflag = True
                                    moni = 1
                    except Exception as e:
                        self.up_dt_info.emit("查询已投注的结果错误:%s" % traceback.format_exc())
                        # ---------------------------------------------------
                s1 = int(current_period) - 1
                s2 = str(int(current_period) - 2)
                s3 = str(int(current_period) - 3)
                s4 = str(int(current_period) - 4)
                # sql = "select * from jx_fk28 where period='" + s1 + "' or period='" + s2 + "' or period='" + s3 + "' or period='" + s4 + "' order by period DESC"
                sql = "select * from jx_fk28 where period <= %s order by period DESC LIMIT 20" % (s1)
                # print(sql)
                redata_1 = mydb.query(sql)
                # print(redata_1)
                last_1 = redata_1[0][2]
                last_2 = redata_1[1][2]
                last_3 = redata_1[2][2]
                last_4 = redata_1[3][2]
                print(last_1, last_2, last_3, last_4)
                for x in redata_1:
                    czlst.append(int(x[2]))
                print(czlst)
                if vote_retime > 9:
                    if moni == 0:
                        if jishu >= 6 and wrong == 0:
                            toufayu = False
                        if toufayu == True:
                            yinshu = 20
                        jishu = jishu + 1
                        if jishu >= 250 and wrong <= 2:
                            moni = 1
                            jishu = 0
                    # print('lezhuan,最大错:', maxwrong, '当前错误', wrong, "金币：", '倍数', yinshu, '模拟', moni, '投注次数', jishu,
                    #       '错标', wrongflag, '偷发育', toufayu)
                    # list_v = daxiao_1(last_1, last_2, last_3, last_4, multiple[wrong], yinshu)
                    list_v = daxiao_2(last_1, last_2, last_3, last_4, multiple[wrong], yinshu, czlst)
                if list_v:
                    vote_list = vote_thing(current_period, list_v)
                    if int(vote_list[0]) < 10:
                        dd = '小'
                    else:
                        dd = '大'
                    self.up_curinfo.emit((current_period, multiple[wrong] * yinshu * 500, jishu, wrong,
                                          int(current_jinbi) - todayfirstjinbi, moni, dd))
                else:
                    vote_list = []
                    self.up_curinfo.emit((current_period, '', '', '', '', moni, ''))
                del mydb
                dealy_time = vote_retime + 28
                self.up_dt_info.emit('延时%s刷新' % dealy_time)
                for m in range(dealy_time, -1, -1):
                    self.up_lcd_num.emit(m)
                    time.sleep(1)
            else:
                self.up_dt_info.emit("当前期都没找到，继续延时30秒查找")
                time.sleep(5)
        except Exception as e:
            print('traceback.format_exc():%s' % traceback.format_exc())
            self.up_dt_info.emit("访问网站出错，等待10秒，重新访问" + repr(e))
            time.sleep(5)


import os
import numpy as np
import matplotlib.pyplot as plt
import cv2

# Import PyWavelets library
import pywt
import pywt.data

# Load an example image
path = os.path.dirname(__file__)
image_path = "image.jpg"
original_image = cv2.imread(os.path.join(path, image_path), cv2.IMREAD_GRAYSCALE)

# Perform 2D wavelet transform (MRA) on the original image
''' The output is a tuple with 4 elements: LL, (LH, HL, HH)
LL = Approximation, LH = Horizontal detail, HL = Vertical detail, HH = Diagonal detail
"haar" is the name of the wavelet used '''
coeffs2 = pywt.dwt2(original_image, 'haar')
LL, (LH, HL, HH) = coeffs2

# Define meta information (for example, a watermark)
'''Random meta-information is generated using NumPy's
np.random.randint function. The meta_info variable
contains random integer values between 0 and 127.
The goal is to embed this meta-information into the
approximation component (LL) of the wavelet-transformed image.'''
meta_info = np.random.randint(0, 128, size=LL.shape)  # Ensure meta_info has the same dimensions as LL

# Resize meta_info to match the shape of LL
meta_info_resized = cv2.resize(meta_info, (LL.shape[1], LL.shape[0]))

# Exchange the LL (approximation) coefficients with meta information
LL_with_meta_info = LL + meta_info_resized

# Reconstruct the image using the modified coefficients
'''The modified coefficients, including LL_with_meta_info,
LH, HL, and HH, are used to reconstruct the modified image
using the inverse wavelet transform with the 'haar' wavelet.
The reconstructed image is stored in the modified_image variable.'''
modified_image = pywt.idwt2((LL_with_meta_info, (LH, HL, HH)), 'haar')

# Plot the original and modified images
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(original_image, cmap='gray')
plt.title('Original Image')
plt.axis('off')

plt.subplot(1, 2, 2)
plt.imshow(modified_image, cmap='gray')
plt.title('Modified Image with Meta Information')
plt.axis('off')

plt.tight_layout()
plt.show()


from itertools import islice
from collections import defaultdict

def distance(point):
    return abs(point[0]) + abs(point[1])

def neighbours(point):
    x, y = point
    return ((x+1, y), (x-1, y), (x, y+1), (x, y-1),
            (x+1, y+1), (x-1, y-1), (x+1, y-1), (x-1, y+1))

def spiral_seq():
    yield 0, 0
    x, y = 1, 0
    inc_x, inc_y = 0, 1
    while True:
        yield x, y
        if abs(x) == abs(y):
            if x <= 0 and y <= 0:
                inc_x, inc_y = 1, 0
            elif x > 0 and y <= 0:
                x += 1
                y -= 1
                inc_x, inc_y = 0, 1
            elif x <= 0 and y > 0:
                inc_x, inc_y = 0, -1
            else:
                inc_x, inc_y = -1, 0
        x += inc_x
        y += inc_y

def sequential_spiral(nth):
    return next(islice(spiral_seq(), nth - 1, nth))

def neighbour_spiral(limit):
    matrix = defaultdict(int)
    matrix[(0, 0)] = 1
    for point in islice(spiral_seq(), 1, None):
        value = sum(matrix[neighbour] for neighbour in neighbours(point))
        if value > limit:
            return value
        else:
            matrix[point] = value

print(distance(sequential_spiral(368078)))
print(neighbour_spiral(368078))


# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from kouzi_crawler.items import KouziCrawlerItem

class QzkeySpider(CrawlSpider):
    name = 'qzkey'
    allowed_domains = ['qzkey.com']
    start_urls = ['http://mimi1688.aly611.qzkey.com/']

    rules = (
        Rule(LinkExtractor(allow=r'Product.aspx\?typeid=\d+'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        app_list = response.xpath('//dl[@class="cpDl2"]/dd/ul//li')
        kouzi_name = '有鱼汇'
        kouzi_link = response.url
        kouzi_type = 'web'
        for item in app_list:
            app_item = KouziCrawlerItem()
            app_item['app_name'] = item.xpath('./a//dd//h3/text()').extract_first().strip()
            app_item['app_link'] = item.xpath('./a/@href').extract_first()
            app_item['kouzi_type'] = kouzi_type
            app_item['kouzi_name'] = kouzi_name
            app_item['kouzi_link'] = kouzi_link
            yield app_item


import torch
import numpy as np
from six import string_types
from torch import optim
import inspect
import torch.nn as nn
import torch.nn.parallel
from torch.autograd import Variable
import torch.nn.functional as F

from tqdm import tqdm
import copy

def get_function_args( fn ):
    """returns a list of all argumnts, dict of all the defualts , and list of all non default arguments

    Args:
        fn (function): [description]

    Returns:
        [type]: [description]
    """
    args = inspect.getargspec( fn  ).args

    if inspect.getargspec( fn  ).defaults  is None:
        n_defaults = 0
        def_args = []
    else:
        n_defaults = len(inspect.getargspec( fn  ).defaults  )
        def_args = list(inspect.getargspec( fn  ).defaults )

    if n_defaults > 0:
        default_args = args[ -1*n_defaults : ]
    else:
        default_args = []

    defaults = { a[0]:a[1] for a in zip(default_args , def_args  ) }
    non_defaults = args[: len( args) - n_defaults ]

    return args , defaults , non_defaults

# given a dictionary kwargs .. this will return which all of those can be sent to the function fn_name
def filter_functions_kwargs(fn_name , kwargs ):
    fn_args = inspect.getargspec( fn_name  ).args
    ret = {}
    for k in kwargs:
        if k in fn_args:
            ret[ k ] = kwargs[k]
    return ret

def str_to_auto_type(var):
    #first test bools
    if var == 'True' or var=='true':
            return True
    elif var == 'False' or var=='false':
            return False
    else:
            #int
            try:
                    return int(var)
            except ValueError:
                    pass
            #float
            try:
                    return float(var)
            except ValueError:
                    pass

            # homogenus list
            # todo

            #string
            try:
                    return str(var)
            except ValueError:
                    raise NameError('Something Messed Up Autocasting var %s (%s)'
                                      % (var, type(var)))

# returns a dictionarly of named args from cli!!
def get_cli_opts(argv):
    opts = {}  # Empty dictionary to store key-value pairs.

    argv= copy.deepcopy(argv)

    while argv:  # While there are arguments left to parse...
        if argv[0][0] == '-' and  argv[0][1] == '-':  # Found a "--name value" pair.

            argv[0] = argv[0][2:] # remove '--'

            assert argv[0] != '' , "There is some issue with the cli args becasue a key cannot be empty"
            assert not argv[0] in opts , "Repeated argument: "+argv[0]
            opts[argv[0]] = str_to_auto_type( argv[1] )   # Add key and value to the dictionary.
        argv = argv[1:]  # Reduce the argument list by copying it starting from index 1.

    return opts

def get_vars( data , cuda=False  , numpy=False ):

#     list( map( lambda x :Variable(torch.FloatTensor(x.float() )).cuda() , imgs   ))

    if type( data ) is tuple:
        return tuple([ get_vars(d , cuda=cuda , numpy=numpy) for d in data  ])
    elif type( data ) is list:
        return list([ get_vars(d , cuda=cuda , numpy=numpy) for d in data  ])
    elif type( data ) is dict:
        return { k:get_vars(data[k] , cuda=cuda , numpy=numpy) for k in data }
    else:
        if numpy:
            data = torch.from_numpy(data)
        r =  Variable( data )
        if cuda:
            r = r.cuda()
        return r

def get_np_arrs( data ):
    if type( data ) is tuple:
        return tuple([ get_np_arrs(d  ) for d in data  ])
    elif type( data ) is list:
        return list([ get_np_arrs(d  ) for d in data  ])
    elif type( data ) is dict:
        return { k:get_np_arrs(data[k]  ) for k in data }
    else:
        return data.cpu().detach().numpy()

class ProgressBar(tqdm):
    def __init__( self , iterator ):
        super(ProgressBar, self).__init__(iterator)
        self.vals_history_dict = {}

    def add( self , vals_dict ):
        for k in vals_dict:
            if not k in self.vals_history_dict:
                self.vals_history_dict[k] = []
            self.vals_history_dict[k].append( vals_dict[k])

        self.bar_str = ""
        for k in self.vals_history_dict:
            self.bar_str += k+":"+ "%.3f"%(np.mean(self.vals_history_dict[k])) + " "

        self.set_description(self.bar_str )


import os
import sys
import threading
import asyncio

sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))
import discord

client = None
channel = None
ready = False

def init():
    global client
    global channel

    intents = discord.Intents.default()
    intents.message_content = True
    client = discord.Client(intents=intents)

    # discord.utils.get(channels.guild.channels, name="")

    @client.event
    async def on_ready():
        global ready

        ready = True
        print(f"We have logged in as {client.user}")

    @client.event
    async def on_message(message):
        if message.author == client.user:
            return

        if message.content.startswith('$hello'):
            await message.channel.send('Hello!')

def start(token):
    threading.Thread(target=client.run, args=(token,)).start()

def send_message(channel_id, text, files=[]):
    channel = client.get_channel(channel_id)
    if channel == None:
        print("no such channel")
        return
    client.loop.create_task(channel.send(text, files=[discord.File(p) for p in files]))

def stop():
    client.loop.create_task(client.close())


from enum import Enum

import ffmpeg
import numpy as np
import pandas as pd
import torch

from data_processing.custom_segmentation import CustomSegmentationStrategy
from data_processing.simple_segmentation import SimpleSegmentation
from data_processing.voice_activity_detection import VADSilero

class Method(Enum):
    CUSTOM = "CUSTOM"
    SILERO = "SILERO"
    SIMPLE = "SIMPLE"

class AudioConvert:

    def __init__(self, method: Method = Method.CUSTOM, use_gpu: bool = False):
        self.method = method
        if method == method.SILERO:
            self.custom_speaker_activity_detection = VADSilero(use_gpu=use_gpu)
            self.custom_segmentation = None
            self.simple_segmentation = None
        elif method == method.CUSTOM:
            self.custom_segmentation = CustomSegmentationStrategy()
            self.custom_speaker_activity_detection = None
            self.simple_segmentation = None
        elif method == method.SIMPLE:
            self.custom_segmentation = None
            self.custom_speaker_activity_detection = None
            self.simple_segmentation = SimpleSegmentation()

    @staticmethod
    def read_file_to_np(audiofile_path: str):
        out, err = (
            ffmpeg
                .input(audiofile_path)
                .output('pipe:', format="wav", acodec="pcm_s16le", ar=16000, ac=1)
                .run(capture_stdout=True)
        )
        numpy_array = np.frombuffer(out, dtype=np.int16)
        return numpy_array

    def convert_file_to_segments(self, audiofile_path: str):
        audio = self.read_file_to_np(audiofile_path)
        audio_tensor = torch.Tensor(audio)

        if self.method == Method.CUSTOM:
            vad_matrix = self.custom_speaker_activity_detection.get_VAD_matrix(audio_tensor)
            self.custom_segmentation.plot_VAD(vad_matrix)
            segments = self.custom_segmentation.segment(vad_matrix.numpy())
            audio_segments = self.custom_speaker_activity_detection.audio_to_segments_from_stamps(audio, segments)
        elif self.method == Method.SILERO:
            timestamps = self.custom_speaker_activity_detection._get_speech_ts_adaptive(audio_tensor)
            audio_segments = self.custom_speaker_activity_detection.audio_to_segments(audio, timestamps)
        elif self.method == Method.SIMPLE:
            audio_segments = self.simple_segmentation.segment(audio_tensor)
        else:
            raise RuntimeError()

        return audio_segments

if __name__ == '__main__':
    method = Method.SILERO
    converter = AudioConvert(method=method, use_gpu=False)
    audio_files = [
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/foelg_pengende/Foelg-pengene--Hvem-sk_5e5eee8c464747fdaab37a30a626df9b_192.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/24_spørgsmål_til_professoren/Historier_fra_de_varme_lande.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/danske_statsministre/Bang_Andr_f_rdigproduceret_med_intro_og_outro_online-audio-converter_com_.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/den_agile_podcast/Podcast#3 - Agile kontra vandfald.mp3",
        #"/media/rafje/danspeech/data_mining/unlabeled/podcasts/supertanker/Supertanker--USA-paa-r_2c271306def14480840af87150e5d636_192.mp3",
        "/home/rafje/Downloads/Foelg-pengene--Apple--_823566a09c664d17aad77862d288473a_192.mp3"
    ]

    audio_lenghts = []
    for audio_file in audio_files:
        lengths = map(lambda x: len(x[2]) / 16000, converter.convert_file_to_segments(audio_file))
        audio_lenghts.append(lengths)

    import matplotlib.pyplot as plt

    all_lengths = []

    lower_seconds = 4
    upper_seconds = 15

    under_seconds = []
    between = []
    over_seconds = []

    for i in range(len(audio_lenghts)):
        current_lengths = list(audio_lenghts[i])
        all_lengths += current_lengths
        df = pd.DataFrame(current_lengths, columns=['one'])
        ax = df.plot.hist(bins=20, alpha=0.5)
        plt.show()

        for audio_length in current_lengths:
            if audio_length < lower_seconds:
                under_seconds.append(audio_length)
            if audio_length > upper_seconds:
                over_seconds.append(audio_length)
            else:
                between.append(audio_length)

    df = pd.DataFrame(all_lengths, columns=['Audio lengths'])
    ax = df.plot.hist(bins=20, alpha=0.5)
    plt.show()

    print(f"Length under: {len(under_seconds)}")
    print(f"Length over: {len(over_seconds)}")
    print(f"Length between: {len(between)}")
    print(f"total length: {len(under_seconds) + len(over_seconds) + len(between)}")

    print(f"Length under seconds: {sum(under_seconds)}")
    print(f"Length over seconds: {sum(over_seconds)}")
    print(f"Length between seconds: {sum(between)}")

    print(f"total length seconds: {sum(under_seconds) + sum(over_seconds) + sum(between)}")


from django import forms

from bankapp.models import Person, City

GENDER_CHOICES = [
 ('Male', 'Male'),
 ('Female', 'Female')
]
MATERIALS_PROVIDE_CHOICE = [
 ('Debit Card', 'Debit Card'),
 ('Credit Card', 'Credit Card'),
 ('Check Book', 'Check Book'),
]
class PersonCreationForm(forms.ModelForm):
    gender = forms.ChoiceField(choices=GENDER_CHOICES, widget=forms.RadioSelect)
    materials = forms.MultipleChoiceField(label='Materials Provide', choices=MATERIALS_PROVIDE_CHOICE,
                                         widget=forms.CheckboxSelectMultiple)
    class Meta:
        model = Person
        fields = '__all__'
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Name'}),
            'email': forms.EmailInput(attrs={'class': 'form-control','placeholder':'Enter Your Email-ID'}),
            'address': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Address'}),
            'age': forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Age'}),
            'dob': forms.DateInput(attrs={'class': 'form-control','type':'date'}),
            'account': forms.Select(attrs={'class': 'form-control'}),
            'district': forms.Select(attrs={'class': 'form-control'}),
            'city': forms.Select(attrs={'class': 'form-control'}),
            'mob': forms.NumberInput(attrs={'class': 'form-control','placeholder':'Enter Your Mobile Number'}),

        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['city'].queryset = City.objects.none()

        if 'district' in self.data:
            try:
                district_id = int(self.data.get('district'))
                self.fields['city'].queryset = City.objects.filter(district_id=district_id).order_by('name')
            except (ValueError, TypeError):
                pass  # invalid input from the client; ignore and fallback to empty City queryset
        elif self.instance.pk:
            self.fields['city'].queryset = self.instance.district.city_set.order_by('name')


import sys
import pathlib
import generator_func
import generator_logging
from datetime import datetime

from PyQt6.QtCore import QRunnable, QThreadPool, QDateTime, QSettings
from PyQt6.QtWidgets import (QApplication,
                             QDateTimeEdit,
                             QLabel,
                             QMainWindow,
                             QPushButton,
                             QWidget,
                             QFileDialog,
                             QGridLayout,
                             QLineEdit,
                             QComboBox,
                             QProgressBar,
                             QStatusBar,
                             QSpinBox,
                             QTableWidget,
                             QTableWidgetItem,
                             QMessageBox)
from PyQt6.QtGui import QIcon

MAXIMUM_IK_QUANTITY = 9999

class Worker(QRunnable):  # класс для мультипоточности???
    def run(self):  # мой код
        date_1 = win.date_1
        ed_date = date_1.toString('yyyy-MM-dd')
        req_date_time = date_1.toString('yyyy-MM-ddThh:mm:ssZ')
        path_for_ik = win.directory_path.currentText()  # в качестве пути для ИК берётся значение, указанное в ComboBox
        win.progressbar.setMaximum(win.ik_quantity.value())
        win.btn_create_IK.setEnabled(False)
        start = datetime.now()
        # aaa = generator_func.check_dir_emptiness(path_for_ik) # проверка каталога сохранения ИК на наличие файлов
        for i in range(win.ik_quantity.value()):
            generator_func.create_ik(path_for_ik, ed_date, req_date_time)
            win.progressbar.setValue(i + 1)
            win.status_bar.showMessage(f'Создано конвертов: {i + 1}')
        end = datetime.now()
        win.status_bar.showMessage(f'Создано конвертов: {win.ik_quantity.value()}. Затраченное время: {end - start}')
        generator_logging.log_event(f'Создано конвертов: {win.ik_quantity.value()}. Каталог: {path_for_ik}. '
                                    f'Затраченное время: {end - start}')
        win.btn_create_IK.setEnabled(True)

class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        # Добавляем файл с настройками
        self.settings = QSettings('settings.ini', QSettings.Format.IniFormat)
        self.path_history = set()
        self.date_1 = ''
        self.setWindowTitle("Генератор ИК")  # заголовок главного окна
        self.setMinimumSize(500, 150)  # минимальные размеры главного окна
        self.get_directory_path = QPushButton('Выбрать каталог', self)
        self.get_directory_path.setFixedWidth(150)  # установка ширины кнопки
        # Определяем элементы интерфейса
        self.btn_create_IK = QPushButton('Создать конверты', self)
        self.ik_quantity_label = QLabel()
        self.calendar_label = QLabel()
        self.line_edit_for_combo = QLineEdit()
        self.directory_path = QComboBox()
        self.directory_path.setLineEdit(self.line_edit_for_combo)
        self.ik_quantity = QSpinBox()
        self.calendar = QDateTimeEdit()
        self.progressbar = QProgressBar()
        self.status_bar = QStatusBar()
        self.start_date = QDateTime.currentDateTime()
        self.calendar.setDisplayFormat('dd.MM.yyyy')
        self.ik_quantity.setMaximum(MAXIMUM_IK_QUANTITY)
        self.setMaximumWidth(1800)
        self.get_directory_path.clicked.connect(self.get_directory)
        self.btn_create_IK.clicked.connect(self.create_ik_func)
        self.ik_quantity.textChanged.connect(self.ik_quantity_signal)
        self.calendar.dateTimeChanged.connect(self.calendar_changed)
        self.calendar.setCalendarPopup(True)
        self.calendar.setDateTime(self.start_date)
        self.date_1 = self.calendar.dateTime()
        self.table = QTableWidget()
        self.table_widget_item = QTableWidgetItem()
        # размещение элементов
        grid_layout = QGridLayout()
        grid_layout.addWidget(self.get_directory_path, 0, 0)
        grid_layout.addWidget(self.directory_path, 0, 1)
        grid_layout.addWidget(self.ik_quantity_label, 1, 0)
        grid_layout.addWidget(self.ik_quantity, 1, 1)
        grid_layout.addWidget(self.calendar_label, 2, 0)
        grid_layout.addWidget(self.calendar, 2, 1)
        grid_layout.addWidget(self.btn_create_IK, 3, 0, 1, 2)
        # grid_layout.addWidget(self.progressbar, 5, 0, 1, 2)
        grid_layout.addWidget(self.status_bar, 4, 0, 1, 2)
        widget = QWidget()
        widget.setLayout(grid_layout)
        self.setCentralWidget(widget)
        self.ik_quantity_label.setText('Количество конвертов')
        self.calendar_label.setText('Дата ИК')
        self.btn_create_IK.setEnabled(False)
        # создание всплывающих подсказок для элементов интерфейса
        self.get_directory_path.setToolTip('Выберите каталог для сохранения ИК')
        self.directory_path.setToolTip('Можно вставить путь или выбрать с помощью кнопки')
        self.ik_quantity.setToolTip('Количество создаваемых конвертов')
        self.btn_create_IK.setToolTip('Введите количество создаваемых конвертов')
        self.calendar.setToolTip('Дата интеграционного конверта, дата заявки, дата выдачи кредита')
        self.status_bar.showMessage('')
        # self.table.cellClicked(0,0)
        # Что-то про многопоточность
        self.threadpool = QThreadPool()
        self.ik_quantity_label = ''
        self.iteration_count = ''
        # определение переменных для пути к каталогам и файлам
        self.start_path = pathlib.Path.cwd()
        self.envelope_path = self.start_path.joinpath('sample/envelope.xml')
        self.routeinfo_path = self.start_path.joinpath('sample/RouteInfo.xml')
        self.ed421_path = self.start_path.joinpath('sample/ED421.xml')
        self.line_edit_for_combo.setText(str(self.start_path))
        self.path_for_ik = self.start_path
        self.path_for_ik_str = str(self.path_for_ik)
        # подгонка ширины под длину пути к каталогу
        self.setMinimumWidth(int(len(str(self.start_path)) * 8.5))
        # импорт сохраненных настроек
        if self.settings.value('OD'):
            self.calendar.setDateTime(self.settings.value('OD'))
        else:
            self.date_1 = self.calendar.date()
        if self.settings.value('Path'):
            self.directory_path.addItems(self.settings.value('Path'))
            self.path_history = self.settings.value('Path')
        else:
            self.path_history = set()

    def get_directory(self):
        """
        Вызов диалогового окна для выбора каталога сохранения создаваемых конвертов
        :return:
        """
        self.path_for_ik = QFileDialog.getExistingDirectory(self, caption='Выбрать каталог сохранения',
                                                            directory=str(pathlib.Path.cwd()))
        self.path_for_ik_str = str(self.path_for_ik)
        self.line_edit_for_combo.setText(self.path_for_ik_str)
        self.setMinimumWidth(len(self.path_for_ik_str * 10))

    def create_ik_func(self):
        """
        Создание конвертов
        :return:
        """
        worker = Worker()  # делаем переменную на созданный класс FirstThread
        self.threadpool.start(worker)  # обращаемся к созданному классу FirstThread
        # добавление пути для ИК в выпадающий список
        if self.path_for_ik_str in self.path_history:
            pass
        elif self.path_for_ik_str not in self.path_history:
            self.path_history.add(self.path_for_ik_str)
            self.directory_path.addItem(self.path_for_ik_str)

    def ik_quantity_signal(self, value):
        """
        Определяет заполнено поле с количеством конвертов или нет и блокирует кнопку создания ИК
        :param value:
        :return:
        """
        if self.ik_quantity.value() == 0:
            self.btn_create_IK.setEnabled(False)
            self.btn_create_IK.setToolTip('Введите количество создаваемых конвертов')
        else:
            self.btn_create_IK.setEnabled(True)
            self.btn_create_IK.setToolTip('Создать конверты')

    def calendar_changed(self):
        self.date_1 = self.calendar.dateTime()

    def closeEvent(self, event):  # переопределение события закрытия окна
        self.settings.setValue('Path', self.path_history)  # Сохранить переменную с историей в файле с настройками
        self.settings.setValue('OD', self.date_1)  # Сохранить переменную с датой в файле с настройками

if __name__ == '__main__':
    app = QApplication(sys.argv)
    style = """
            QMainWindow {
                /*background-color: #fff;*/
            }
            QProgressBar {
                border: 1px solid grey;
                border-radius: 5px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #05B8CC;
                width: 10px;
                /*margin: 0.5px;*/
            }
            """
    app.setStyleSheet(style)
    win = Window()
    app.setWindowIcon(QIcon(str(win.start_path.joinpath('other/hedgehog_deep_red.png'))))
    win.show()
    sys.exit(app.exec())


"""Basic status commands to check the health of the bot."""
import datetime

import discord
from discord.ext import commands

from metricity.config import BotConfig

DESCRIPTIONS = (
    "Command processing time",
    "Last event received",
    "Discord API latency",
)
ROUND_LATENCY = 3
INTRO_MESSAGE = "Hello, I'm {name}. I insert all your data into a GDPR-compliant database."

class Status(commands.Cog):
    """Get the latency between the bot and Discord."""

    def __init__(self, bot: commands.Bot) -> None:
        self.bot = bot

    @commands.Cog.listener()
    async def on_socket_event_type(self, _: str) -> None:
        """Store the last event received as an int."""
        self.last_event_received = int(datetime.datetime.now(datetime.UTC).timestamp())

    @commands.command()
    @commands.has_any_role(BotConfig.staff_role_id)
    @commands.guild_only()
    async def status(self, ctx: commands.Context) -> None:
        """Respond with an embed with useful status info for debugging."""
        if ctx.guild.id != BotConfig.guild_id:
            return

        bot_ping = (datetime.datetime.now(datetime.UTC) - ctx.message.created_at).total_seconds() * 1000
        if bot_ping <= 0:
            bot_ping = "Your clock is out of sync, could not calculate ping."
        else:
            bot_ping = f"{bot_ping:.{ROUND_LATENCY}f} ms"

        discord_ping = f"{self.bot.latency * 1000:.{ROUND_LATENCY}f} ms"

        last_event = f"<t:{self.last_event_received}>"

        embed = discord.Embed(
            title="Status",
            description=INTRO_MESSAGE.format(name=ctx.guild.me.display_name),
        )

        for desc, latency in zip(DESCRIPTIONS, (bot_ping, last_event, discord_ping), strict=True):
            embed.add_field(name=desc, value=latency, inline=False)

        await ctx.send(embed=embed)

async def setup(bot: commands.Bot) -> None:
    """Load the status extension."""
    await bot.add_cog(Status(bot))


from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time
import pickle
import os

#put url here
#example_url= "https://archive.thehated3.workers.dev/0:/Station%20X%20-%20The%20Complete%20Cyber%20Security%20Course!/"
durl= "https://archive.thehated3.workers.dev/0:/Station%20X%20-%20The%20Complete%20Cyber%20Security%20Course!/"

#put local path to download here, leave '.' to download in current directory
#example_path="./Station_X_The_Complete_Cyber_Security_Course"
dpath="."

count=0
rcount=0
failed_links=[]
failed_paths=[]

def download(url,path):
    global count, failed_links, failed_paths
    fireFoxOptions = webdriver.FirefoxOptions()
    fireFoxOptions.add_argument("--headless")
    # brower = webdriver.Firefox(firefox_options=fireFoxOptions)

    driver = webdriver.Firefox(executable_path="./geckodriver.exe",options=fireFoxOptions)
    driver.get(url)

    time.sleep(3)
    previous_height=driver.execute_script('return document.body.scrollHeight')
    while True:
        driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
        time.sleep(3)
        new_height=driver.execute_script('return document.body.scrollHeight')

        if new_height==previous_height:
            break
        previous_height=new_height

    try:
        element = WebDriverWait(driver,100).until(EC.presence_of_element_located((By.CLASS_NAME, "list-group-item")))
    except:
        count+=1
        print(f"FILE NOT DOWNLOADED:\npath: {path}\n count:{count}")
        print("TIMEOUT not LOADING ELEMENTS BY CLASS NAME list-grout-items EXCEPTION")
        return

    tuna=driver.find_elements_by_class_name("list-group-item")
    dlinks=[]

    for i in tuna:

        folder=i.get_attribute('href')
        if folder==None:
            target_urls=i.find_elements_by_css_selector('a')
            furl=target_urls[1].get_attribute('href')
            dlinks.append(furl)
        else:
            fname=i.text
            formated_folder_name=fname.replace(" ","-")
            new_path=path+"/"+formated_folder_name
            download(folder,new_path)

    for x in dlinks:
        # print(x)
        # cmd=f'wget -c -P '+'"'+f'{path}'+'" '+'"'+ f'{x}'+'"'
        print(f"****DOWNLOADING IN PATH****: {path}\nfiles_skipped_till_now={count} \n\n")
        failure=os.system(f"""wget -c -P "{path}" "{x}" """)
        if failure != 0:
            count+=1
            failed_links.append(x)
            failed_paths.append(path)
            print(f"FILE NOT DOWNLOADED:\npath: {path}\nfile: {x}\n count:{count}")

    driver.close()

def direct_download(dd_url,dd_path):
    rfc=os.system(f"""wget -c -P "{dd_path}" "{dd_url}" """)
    return rfc

def retry():
    global rcount
    new_links=[]
    new_paths=[]
    rcount=0
    try:
        failed_file_open=open("failed_links_info.pickle","rb")
    except:
        print('failed_links_info NOT Available, ABORTING...')
        return

    get_failed=pickle.load(failed_file_open)
    fetch_links=get_failed[0]
    fetch_paths=get_failed[1]
    failed_file_open.close()

    link_size=len(fetch_links)

    for k in range(link_size):
        l=fetch_links[k]
        p=fetch_paths[k]
        status=direct_download(l,p)
        if status!=0:
            rcount+=1
            new_links.append(l)
            new_paths.append(p)
            print(f"FILE NOT DOWNLOADED:\npath: {p}\nfile: {l}\n count:{rcount}")

    print(f"Number of files not downloaded: {rcount}")
    nf=len(new_paths)
    o_again=open("failed_links_info.pickle","wb")
    m_list=[new_links,new_paths]
    pickle.dump(m_list,o_again)
    o_again.close()

    for e in range(nf):
        ww=new_paths[e]
        tt=new_links[e]
        print(f"{ww}\n{tt}\n\n")

if __name__=='__main__':

    ui=input("Choose:\n1.Retry failed downloads\n2.Download from new link provided\nChoose either '1' or ('2') :")
    if ui==1 or ui=='1':
        retry()
    else:
        download(durl,dpath)
        print(f"Number of files not downloaded: {count}")
        number_failed=len(failed_paths)
        fo=open("failed_links_info.pickle","wb")
        combined_list=[failed_links,failed_paths]
        pickle.dump(combined_list,fo)
        fo.close()

        for i in range(number_failed):
            a=failed_paths[i]
            b=failed_links[i]
            print(f"{a}\n{b}\n\n")

        user_input=input("Do you want to retry {count} failed downloads? (Y)/N : ")
        if user_input.lower()=='n':
            pass
        else:
            retry()

    # print(turl)


from QLearning import Game
from collections import Counter
import pandas as pd
import matplotlib.pyplot as plt

gamma = 0.1

def Menu():
    usr_op = None
    while usr_op != 0:
        print('//-//-//-// Card-Jitsu Menu //-//-//-//')
        print('\nSelect an option to continue: ')
        print('1. Play game vs AI.')
        print('2. Get Strategy Metrics.')
        print('3. Get Random Metrics.')
        print('4. Train Ai Manual.')
        print('5. Train Ai Random.')
        print('0. Exit.')

        usr_op = int(input('\n Option selected: '))
        if usr_op == 1:
            Game(gamma)
        elif usr_op == 2:
            get_metrics(is_random = False, train = False, show_game = True)
        elif usr_op == 3:
            get_metrics(is_random = True, train = False, show_game = False)
        elif usr_op == 4:
            get_metrics(is_random = False, train = True, show_game = True)
        elif usr_op == 5:
            get_metrics(is_random = True, train = True, show_game = False, show_metrics = False)

        print('\n\n')

def get_metrics(is_random, train, show_game, show_metrics = True):

    history = {
        'Game': [],
        'Round': [],
        'AI': [],
        'Player': [],
        'Winner': [],
        'Game Winner': []
    }

    game = 0
    g = int(input('Numero de juegos a realizar: '))

    while game < g:
        winrecord , winner = Game(gamma, is_random, train, show_game)

        for round in range(len(winrecord)):
            history['Game'].append(game)
            history['Game Winner'].append(winner)
            history['Round'].append(round)
            history['AI'].append(winrecord[round]['AI'])
            history['Player'].append(winrecord[round]['Player'])
            history['Winner'].append(winrecord[round]['Winner'])

        game += 1

    if not show_metrics: return 0

    history = pd.DataFrame.from_dict(history)

    # Histograma de Rondas y juegos
    game_winrate = Counter(list(history['Game Winner']))
    game_winrate = pd.DataFrame.from_dict(game_winrate, orient='index', columns=['Games Won'])
    game_winrate.plot(kind='pie', y='Games Won', autopct='%1.0f%%', explode=(0.01, 0.01), startangle=20)
    plt.title('Frecuency of Games Won')
    plt.ylabel('')
    plt.show()

    # Diagrama de Pie de rondas ganadas

    round_winrate = Counter(list(history['Winner']))
    round_winrate = pd.DataFrame.from_dict(round_winrate, orient='index', columns=['Rounds Won'])
    round_winrate.plot(kind='pie', y='Rounds Won', autopct='%1.0f%%', explode=(0.01, 0.01, 0.01), startangle=60)

    plt.title('Frecuency of Rounds Won and Tied')
    plt.ylabel('')
    plt.show()

    # Histograma de cartas
    ai_cardrate = Counter(list(history['AI']))
    ai_cardrate = pd.DataFrame.from_dict(ai_cardrate, orient='index', columns=['AI Cards'])

    player_cardrate = Counter(list(history['Player']))
    player_cardrate = pd.DataFrame.from_dict(player_cardrate, orient='index', columns=['Player Cards'])

    hist_cardrate = ai_cardrate.merge(player_cardrate, how='outer', left_index=True, right_index=True).fillna(0)
    hist_cardrate.plot(kind = 'bar')

    plt.title('Frecuency of Cards Used')
    plt.show()

Menu()


import serial
import datetime as dt
import sys

class gps:
    def __init__(self, port = "/dev/serial0"):
        # Initializes serial connection for gps communication
        try:
            self.__ser = serial.Serial(port)
        except Exception as e:
                        sys.exit("Can not connect with GPS using uart: " + str(e))

    def get_record(self):
        # For 50 times tries to read GPRMC record from gps in form of strings
        got_record = False
        for _ in range(50):
            gps_record = self.__ser.readline().decode('UTF-8')
            if gps_record[0:6] == "$GPRMC":
                got_record = True
                break

        if got_record == True:
            data = gps_record.split(",")
            if data[2] == 'A':
                self._status = "Correct"

                # GMT time
                if is_number(data[1][0:2]) and is_number(data[1][2:4]) and is_number(data[1][4:6]):
                    self._time = data[1][0:2] + ":" + data[1][2:4] + ":" + data[1][4:6]
                else:
                    self._time = dt.datetime.now().strftime('[%H:%M:%S]')
                    self._status = "Corrupted data"

                # Latitude
                if (is_number(data[3])):
                    self._latitude = data[3]
                else:
                    self._status = "Corrupted data"

                # Latitude direction N/S
                self._hemisphere_NS = data[4]

                # Longitude
                if (is_number(data[5])):
                    self._longitude = data[5]
                else:
                    self._status = "Corrupted data"

                # Longitude direction W/E
                self._hemisphere_WE = data[6]

                # Velocity in knots
                if (is_number(data[7])):
                    self._velocity = data[7]
                else:
                    self._status = "Corrupted data"

                # True course
                if (is_number(data[8])):
                    self._course = data[8]
                elif data[8] == '':
                    self._course = 0;
                else:
                    self._status = "Corrupted data"

                # Date
                if is_number(data[9][4:6]) and is_number(data[9][2:4]) and is_number(data[9][0:2]):
                    self._date = data[9][4:6] + "-" + data[9][2:4] + "-" + data[9][0:2]
                else:
                    self._status = "Corrupted data"

                if self._status == "Correct":
                    return 0
                else:
                    return 1
            else:
                self._status = "Signal lost"
                self._time = dt.datetime.now().strftime('%H:%M:%S')
                self._date = dt.datetime.now().strftime('%Y-%m-%d')

                return 1
        else:
            self._status = "Connection error"
            self._time = dt.datetime.now().strftime('%H:%M:%S')
            self._date = dt.datetime.now().strftime('%Y-%m-%d')

            return 1

    def _decode(self, coord):
        #Converts DDDMM.MMMMM to DD deg MM.MMMMM min
        tmp = coord.split(".")
        deg = tmp[0][0:-2]
        mins = tmp[0][-2:]
        return deg + " deg " + mins + "." + tmp[1] + " min"

    def get_gps_time(self):
        # Returns date and time or 1 if fails to obtain them
        if (self.get_record()):
            return 1
        else:
            return self._date + " " + self._time

    def get_decimal_degrees_record(self):
        # Read from GPS and get current location parameters dictionary in decimal_degrees
        if (self.get_record() == 0):
            hemi_NE_sign = "+" if self._hemisphere_NS == "N" else "-"
            hemi_WE_sign = "+" if self._hemisphere_WE == "E" else "-"

            pos = self._latitude.find('.')
            lat_deg = self._latitude[:pos-2]
            lat_mins = self._latitude[pos-2:pos] + self._latitude[pos+1:]
            lat_mins = str(round(float(lat_mins) / 60.0))

            pos = self._longitude.find('.')
            lng_deg = self._longitude[:pos-2]
            lng_mins = self._longitude[pos-2:pos] + self._longitude[pos+1:]
            lng_mins = str(round(float(lng_mins) / 60.0))

            return {
                'timestamp' : self.get_gps_time(),
                'status' : self._status,
                'latitude' : float(hemi_NE_sign + lat_deg + "." + lat_mins),
                'longitude' : float(hemi_WE_sign + lng_deg + "." + lng_mins),
                'velocity' : float(self._velocity),
                'course' : float(self._course) }
        else:
            return {
                'timestamp' : self._date + " " + self._time,
                'status' : self._status,
                'latitude' : 0,
                'longitude' : 0,
                'velocity' : 0,
                'course' : 0 }

    def get_location_message(self):
        # Read from GPS and get current location in a easily readible string
        self.get_record()
        time_stamp = dt.datetime.now().strftime('[%Y-%m-%d %H:%M:%S]')

        return "%s latitude: %s(%s), longitude: %s(%s), velocity: %s, True Course: %s" %  (
            time_stamp,
            self._decode(self._latitude),
            self._hemisphere_NS,
            self._decode(self._longitude),
            self._hemisphere_NS,
            self._velocity,
            self._course)

def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False


#!/usr/bin/env python

__author__ = 'j5wagner@ucsd.edu'

import commands
from d3r.celppade.custom_protein_prep import ProteinPrep

class chimera_dockprep(ProteinPrep):
    """Abstract class defining methods for a custom docking solution
    for CELPP
    """

    ProteinPrep.OUTPUT_PROTEIN_SUFFIX = '.mol2'

    def receptor_scientific_prep(self,
                                 protein_file,
                                 prepared_protein_file,
                                 targ_info_dict={}):
        """
        Protein 'scientific preparation' is the process of generating
        a dockable representation of the candidate protein from a
        single-chain PDB file.
        :param protein_file: PDB file containing candidate protein.
        :param prepared_protein_file: The result of preparation should have this file name.
        :param targ_info_dict: A dictionary of information about this target and the candidates chosen for docking.
        :returns: True if preparation was successful. False otherwise.
        """

        #####################################################################
        ### $ python  clean_receptor.py  receptor.pdb  clean_receptor.pdb ###
        #####################################################################

        # Implements the logic that was formerly in clean_receptor.py
        orig_pdb = open(protein_file).readlines()
        with open('clean_receptor.pdb','wb') as of:
            for line in orig_pdb:
                if len(line) > 4:
                    if line[:4] == 'ATOM':
                        of.write(line)

        #####################################################################
        ### $ chimera  --nogui  --script  "chimeraPrep.py  clean_receptor.pdb  prepared_receptor.mol2"
        #####################################################################

        # Write the chimera-interpreted code to a script file
        chimera_prep_text = '''import chimera
import sys
opened = chimera.openModels.open(sys.argv[1])
mol = opened[0]

import DockPrep

DockPrep.prep([mol])
from WriteMol2 import writeMol2
with open(sys.argv[2],'wb') as of:
    writeMol2([mol], of)
'''
        with open('chimera_prep.py','wb') as of:
            of.write(chimera_prep_text)

        # Run chimera with the script as an input
        prep_cmd = 'chimera  --nogui  --script  "chimera_prep.py  clean_receptor.pdb ' + prepared_protein_file + ' " 1> prep.stdout 2> prep.stderr'
        commands.getoutput(prep_cmd)

        return True

if ("__main__") == (__name__):
    import logging
    import os
    import shutil
    from argparse import ArgumentParser
    parser = ArgumentParser()
    parser.add_argument("-p", "--pdbdb", metavar = "PATH", help = "PDB DATABANK which we will dock into")
    parser.add_argument("-c", "--challengedata", metavar="PATH", help = "PATH to the unpacked challenge data package")
    parser.add_argument("-o", "--prepdir", metavar = "PATH", help = "PATH to the output directory")
    logger = logging.getLogger()
    logging.basicConfig( format  = '%(asctime)s: %(message)s', datefmt = '%m/%d/%y %I:%M:%S', filename = 'final.log', filemode = 'w', level = logging.INFO )
    opt = parser.parse_args()
    pdb_location = opt.pdbdb
    challenge_data_path = opt.challengedata
    prep_result_path = opt.prepdir

    #running under this dir
    abs_running_dir = os.getcwd()
    log_file_path = os.path.join(abs_running_dir, 'final.log')
    log_file_dest = os.path.join(os.path.abspath(prep_result_path), 'final.log')

    prot_prepper = chimera_dockprep()
    prot_prepper.run_scientific_protein_prep(challenge_data_path, pdb_location, prep_result_path)

    #move the final log file to the result dir
    shutil.move(log_file_path, log_file_dest)


import os

import wx
from wx.lib.colourchooser.canvas import Canvas

class ImageCanvas(wx.Panel):
    """
    Image Panel

    """
    def __init__(self, parent, image_path=None, *args, **kwargs):
        """
        Constructor

        :param parent:
        """
        wx.Panel.__init__(self, parent=parent, *args, **kwargs)

        self.image_path = image_path
        if self.image_path:
            bmp = wx.Bitmap(self.image_path)

            padding = 10
            self.SetMinClientSize((bmp.GetWidth() + padding,
                                   bmp.GetHeight() + padding))

        self.glyphs = []

        # self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
        self.frame = parent

        # img = wx.EmptyImage(240, 240)

        self.main_sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.main_sizer.Add((1, 1), 0, wx.EXPAND, 75)
        # self.main_sizer.Add(img, 0, wx.EXPAND)
        self.main_sizer.Add((1,1), 0, wx.ALL, 75)

        self.SetSizer(self.main_sizer)

        self.Bind(wx.EVT_ERASE_BACKGROUND, self.on_erase_background)
        self.Bind(wx.EVT_SIZE, self.on_size)

    def set_sizer(self):
        """

        :param sizer:
        :return:
        """
        sizer = wx.BoxSizer(wx.VERTICAL)
        hSizer = wx.BoxSizer(wx.HORIZONTAL)

        for num in range(4):
            label = "Button %s" % num
            btn = wx.Button(self, label=label)
            sizer.Add(btn, 0, wx.ALL, 5)

        hSizer.Add((1,1), 1, wx.EXPAND)
        hSizer.Add(sizer, 0, wx.TOP, 100)
        hSizer.Add((1,1), 0, wx.ALL, 75)

        self.SetSizer(hSizer)

    def on_size(self, event):
        """

        :param event:
        """

        event.Skip()
        self.Refresh()

    def scale_image(self, image, max_width=None, max_height=None):
        """

        :param image:
        :param max_width:
        :param max_height:
        :return:
        """
        width = image.GetWidth()
        height = image.GetHeight()
        ratio = min(max_width / width, max_height / height)
        image = image.Scale(ratio * width, ratio * height, wx.IMAGE_QUALITY_HIGH)
        result = wx.BitmapFromImage(image)

        return result

    def on_erase_background(self, event):
        """
        Add a picture to the background

        :param event:
        """

        # self.Freeze()

        dc = event.GetDC()
        w, h = self.GetClientSize()

        if not dc:
            dc = wx.ClientDC(self)
            rect = self.GetUpdateRegion().GetBox()
            dc.SetClippingRect(rect)
        dc.Clear()

        if self.image_path:
            bmp = wx.Bitmap(self.image_path)
            # bmp = self.scale_image(bmp, 100, 200)
            size = bmp.GetSize()

            x = int(w/2.0 - size.x/2.0)
            y = int(h/2.0 - size.y/2.0)

            dc.DrawBitmap(bmp, x, y)

        self.draw_model(dc)

        # self.Thaw()

    def draw_model(self, dc):
        """
        Draw glyps

        :param dc:
        :return:
        """
        for glyph in self.glyphs:
            glyph.draw(dc)

class Glyph(object):
    def __init__(self, *args, **kwargs):
        self.pen_color = kwargs.get('pen_color', wx.BLACK)
        self.pen_width = kwargs.get('pen_width', 5)

        self.coordinates = kwargs.get('coordinates', [])

    def set_pen(self, dc):
        dc.SetPen(self.pen_color, self.pen_width)

    def pre_draw(self, dc):
        self.set_pen()

    def post_draw(self, dc):
        pass

    def _draw_(self, dc):
        pass

    def draw(self, dc):
        self.pre_draw(dc)
        self._draw_(dc)
        self.post_draw(dc)

class Arc(Glyph):
    """

    """
    def _draw_(self, dc):
        pass

class Line(Glyph):
    """

    """
    def _draw_(self, dc):
        xy1 = self.coordinates[0]
        xy2 = self.coordinates[1]

        dc.DrawLine(xy1[0], xy1[1], xy2[0], xy2[1])

class Circle(Glyph):
    """

    """
    def _draw_(self, dc):
        xy = self.coordinates[0]

        dc.DrawCircle(xy[0], xy[1], 100)

class Rectangle(Glyph):
    """

    """
    def _draw_(self, dc):
        pass


from setuptools import setup
import sys

VERSION = '1.2.1263'

plist = dict(
    CFBundleName='VisTrails',
    CFBundleShortVersionString=VERSION,
    CFBundleGetInfoString=' '.join(['VisTrails', VERSION]),
    CFBundleExecutable='vistrails',
    CFBundleIdentifier='edu.utah.sci.vistrails',
)

sys.path.append('../..')
APP = ['../../vistrails/run.py']
#comma-separated list of additional data files and
#folders to include (not for code!)
#DATA_FILES = ['/usr/local/graphviz-2.12/bin/dot',]
OPTIONS = {'argv_emulation': True,
           'iconfile': 'vistrails/resources/vistrails_icon.icns',
           'includes': 'sip,pylab,xml,netCDF3,netCDF4_utils,netcdftime,\
            libxml2,libxslt, Cookie, BaseHTTPServer, multifile, shelve,itk, itkBase, itkConfig, itkLazy, itkTypes, itkExtras',
           'packages': 'PyQt4,vtk,MySQLdb,matplotlib,vistrails,numpy,ZSI,api',
           'plist': plist,
           }

setup(
    app=APP,
 #   data_files=DATA_FILES,
    options={'py2app': OPTIONS},
    setup_requires=['py2app'],
)


from functools import wraps
from typing import Callable

from util.threading import Thread, TimeoutException
from util.typing import P

from .AbstractHandler import PAYLOAD_TYPE, RESPONSE_TYPE, CONTEXT_TYPE, AbstractHandler

class AbstractTimeoutHandler(AbstractHandler[PAYLOAD_TYPE, RESPONSE_TYPE, CONTEXT_TYPE]):
    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        cls.handle_request = cls._wrap_timeout(cls.handle_request)

    def __init__(self, timeout: float = None, default: PAYLOAD_TYPE = None, **kwargs):
        super().__init__(**kwargs)
        self.timeout = timeout
        self.default = default

    @staticmethod
    def _wrap_timeout(
        handle_request: Callable[P, RESPONSE_TYPE]
    ) -> Callable[P, RESPONSE_TYPE]:

        if (
            hasattr(handle_request, "_AbstractTimeoutHandler_wrapped")
            and handle_request._AbstractTimeoutHandler_wrapped == True
        ):
            return handle_request

        @wraps(handle_request)
        def execute_with_timeout(self: "AbstractTimeoutHandler") -> RESPONSE_TYPE:
            result = None
            completed = False

            def run_execute_and_store_result():
                nonlocal result
                nonlocal completed
                try:
                    result = handle_request()
                    completed = True
                except TimeoutException:
                    pass

            thread = Thread(target=run_execute_and_store_result, daemon=True)
            thread.start()
            thread.join(self.timeout)

            if not completed:
                result = self.default

            return result  # type: ignore

        execute_with_timeout._AbstractTimeoutHandler_wrapped = True

        return execute_with_timeout


from django.urls import path

from widgets.views import HomePageView, UserProfilePageView, SharedWidgetsPageView, \
    PrivateWidgetsPageView, MemoryWidgetsView

urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
    path('home/shared-widgets/', SharedWidgetsPageView.as_view(), name='shared-widgets'),
    path('user-profile/<slug:slug>/', UserProfilePageView.as_view(), name='user-profile'),
    path('user-profile/<slug:slug>/widgets/', PrivateWidgetsPageView.as_view(), name='private-widgets'),
    path('memory-widgets/<int:pk>', MemoryWidgetsView.as_view(), name='memory-widgets'),
]


from typing import Any, Dict

def play_game() -> None:
    print('playing game')

def update_state(current_state: Dict) -> Dict:
    print('here we change things')

    possible_actions = {
        'mod status': lambda : print('modifting status'),
        'remove status': lambda : print('removing status'),
        'go back': lambda : print('saving updates')
    }
    show_commands('update status menu', possible_actions)
    return current_state

def quit():
    print('good bye m8')

def show_commands(title: str, commands: Dict) -> Any:

    print(title.upper())
    idxs = {}
    for idx, op in enumerate(commands):
        print(f'{op} -> press [{idx}]')
        idxs[str(idx)] = commands[op]

    while True:
        user_op =  input('select an option > ')
        if user_op in idxs:
            return idxs[user_op]()

def main():
    state = {
        'user_name': 'santi'
    }

    commands = {
        'play': play_game,
        'quit': quit,
        'update_satus': lambda : update_state(state)
    }

    show_commands('main menu', commands=commands)

main()


import pandas as pd
import numpy as np
import tensorflow as tf
import sklearn.model_selection as sk
import helper as hp
import preprocessing as pre
import machine_learning as ml
import json
import os

from flask import Flask, redirect, url_for, request, jsonify
from tensorflow.keras import layers
from tensorflow.keras.models import load_model

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

ML_model       = None
ML_history     = None
graph          = None
titles         = None
classes        = None
targets        = None
categories     = None
training_type  = 0

app = Flask(__name__)

@app.route('/')
def initialize():
   return 'Use /Train or /Predict'

@app.route('/Train', methods = ['POST'])
def Train():
    global ML_model
    global ML_history
    global classes
    global titles
    global targets
    global categories
    global graph

    # Getting the POST Request Body Data
    Data = request.data
    # Converting Text/Plain to JSON Structure
    JsonData = json.loads(Data)
    # Extracting product titles and product classes
    titles = JsonData["products"]
    targets = JsonData["classes"]
    training_type = JsonData["training_type"]
    # 1 is Very Small (80  vec size, Hidden Layers (1024,512))
    # 2 is Small      (200 vec size, Hidden Layers (2048,1024))
    # 3 is Large      (200 vec size, Hidden Layers (2048,1024,1024))
    if(len(titles) == len(targets)):
    # Preprocessing of data
        # Converts target to multi classes array where [1,0,0,0,0,0,....] corresponds to class 1 and [0,1,0,0,0,0,....] corresponds to class 2
        labels, classes, categories = hp.Get_Targets_Arrays(targets)
        print(categories)
        # Converts products titles to vectors
        pre.Doc2Vectors(titles, training_type)
        # Creating Vectors List for all products -> Dataset
        Vectors_List = hp.Get_Product_Vectors(len(titles),training_type)
        # Splitting Data to Train, Validate and Test sets
        train_data, train_labels, val_data, val_labels, test_data, test_labels = pre.Data_Split(Vectors_List,labels)
        # Training
        if(training_type == 1):
            ML_model, ML_history = ml.Train_1(train_data, train_labels, val_data, val_labels, len(labels[0]))
        else:
            if(training_type ==2):
                ML_model, ML_history = ml.Train_2(train_data, train_labels, val_data, val_labels, len(labels[0]))
            else:
                ML_model, ML_history = ml.Train_3(train_data, train_labels, val_data, val_labels, len(labels[0]))

        graph = tf.get_default_graph()
        # Evaluating the trained model
        results = ML_model.evaluate(test_data, test_labels)

        response = "Training Completed with testing scores of " + str(results[1]) + " accuracy and " + str(results[0]) + " Loss"
        return response

    else:
        return "Products and Classes don't have the same length"

@app.route('/Predict',methods = ['POST'])
def Predict():
    global ML_model
    global classes
    global categories
    global training_type

    # Getting the POST Request Body Data
    Data = request.data
    # Converting Text/Plain to JSON Structure
    JsonData = json.loads(Data)
    # Extracting product titles and product classes
    titles = JsonData["products"]

    # Get the product title for prediction from the GET Request
    #title = request.args.get('product')
    # Convert the title to vector based on the titles vector model done in the training process
    #v = hp.Get_Products_Title_Vector(titles)

    # Load model weights for predictins
    ML_model = load_model("weights")
    ML_model._make_predict_function()

    predicted_classes = []

    for title in titles:
        v = hp.Get_Product_Title_Vector(title)
        # Predictions
        pred = ML_model.predict(v)
        max_index = np.argmax(pred)
        predicted_class = categories[max_index]
        predicted_classes.append(predicted_class)
    response = {
    "predictions":predicted_classes,
    }
    return jsonify(response)

if __name__ == '__main__':
   app.run(host='0.0.0.0', port=5010)


import datetime
import json
import os
import re
import shutil

class Fileop():
    def isDirectory(self, fDir):
        return os.path.isdir(fDir)

    def countDir(self, dPath):
        dirListing = next(os.walk(dPath))[2]
        return len(dirListing)

    def CjsonLoad(self, jfile):
        fdir = os.path.join(Fileop.dwnDir(''), "conf")
        condir = Fileop.isDirectory('', fdir)
        if condir:
            confile = os.path.join(fdir, jfile)
            with open(confile, "r") as j:
                return json.load(j)

    def SjsonLoad(self, jfile):
        fdir = Fileop.dwnDir('')
        condir = Fileop.isDirectory('', fdir)
        if condir:
            confile = os.path.join(fdir, jfile)
            with open(confile, "r") as j:
                return json.load(j)

    def curWorkDir(self):
        return os.path.dirname(os.path.realpath(__file__))

    def makDir(self, Folder):
        try:
            os.makedirs(Folder)
        except OSError as e:
            print("Warning making {0} : MSG - {1}".format(Folder, e))

    def dwnDir(self):
        return os.path.normpath(os.getcwd() + os.sep + os.pardir)

    def newDirec(self, nDirName):
        return os.mkdir(nDirName)

    def RecFileDir(self, dirName):
        new_Folder = os.path.join(Fileop.dwnDir(''), dirName)
        dFlag = Fileop.isDirectory('', new_Folder)
        if not dFlag:
            # make directory
            try:
                Fileop.newDirec('', new_Folder)
            except OSError:
                print("Creation of the directory %s failed. \n" % new_Folder)
            else:
                print("Successfully created the directory %s.\n " % new_Folder)
        else:
            print("Directory ( %s ) already exists.\n" % new_Folder)
        return new_Folder

    def newest(self, path):
        files = os.listdir(path)
        lenfile = len(files)
        if lenfile != 0:
            paths = [os.path.join(path, basename) for basename in files]
            return max(paths, key=os.path.getctime)
        else:
            print("Directory ( %s ) is empty\n", path)

    def removefiles(self, folder):
        files_in_directory = os.listdir(folder)
        filtered_files = [file for file in files_in_directory if file.endswith(".wav")]
        dircount = Fileop.countDir('', folder)
        if dircount > 1:
            for file in filtered_files:
                path_to_file = os.path.join(folder, file)
                os.remove(path_to_file)
        else:
            print('Failed to delete files, {0} is empty: \n'.format(folder))

    def moveFiles(self, froDir, toDir, froFile, toFile):
        try:
            shutil.move(os.path.join(froDir, froFile), os.path.join(toDir, toFile))
            print("Successfully moved {0}.\n".format(os.path.join(froDir, froFile)))
        except OSError:
            print("Could not move file ({0}) operation.\n".format(os.path.join(froDir, froFile)))

    def main(self):
        # Check if directories have been created
        source_param = Fileop.CjsonLoad('', "conf.json")
        source_rep = os.path.join(Fileop.dwnDir(''), "reports")
        Fileop.RecFileDir('', source_rep)
        dwn_dir = source_param['download_dir']
        # Recordings directory based on current date
        recFolder = "Recordings" + datetime.datetime.now().strftime("%Y%m%d")
        dirRecs = Fileop.RecFileDir('', recFolder)
        # print(dirRecs)
        # get latest data report file
        newFile = Fileop.newest('', source_rep)
        # print (newFile)
        count = 0
        if Fileop.countDir('', dwn_dir) != 0:
            with open(newFile, "r") as nf:
                lines = nf.readlines()
                for line in lines:
                    count += 1
                    line_id = ' '.join(re.findall(r'\b\w+\b', line)[:+1])
                    line_data = ' '.join(re.findall(r'\b\w+\b', line)[:]).replace(line_id, "")
                    line_data = "_".join(line_data.split())
                    print("line {0} - file ID : {1} file metadata :- {2} \n".format(count, line_id, line_data))
                    # move and rename files
                    Fileop.moveFiles("", dwn_dir, dirRecs, line_id + ".wav", line_data + ".wav")
        else:
            print("Warning: Call recordings download did not run!\n")
# if __name__ == "__main__":
#     main()


import sqlite3
from flask import Flask
import json

app = Flask(__name__)

@app.route('/animals/<idx>')
def animals(idx):
    with sqlite3.connect("animal.db") as connection:
        cursor = connection.cursor()

        query = f"""
            select * from animals_final
            left join outcomes on outcomes.animal_id = animals_final.animal_id
            where animals_final.id = {idx}
        """

        cursor.execute(query)
        result = cursor.fetchall()

        if len(result) == 1:
            line = result[0]
            result_dict = {}
            number = 1
            for i in line:
                result_dict[f"{number}"] = i
                number += 1
        else:
            result_dict = "Nothing found"
        return json.dumps(result_dict)

app.run(debug=True, port=5001)


from django.test import TestCase
from django.urls.base import reverse

from .models import Provinces

# Create your tests here.
class ProvincesModelTests(TestCase):
    def test_get_one_province(self):
        """if not province exist with passed id, return appropiate message"""
        province = Provinces.objects.create(id=1, name='Santa Fe', population=23142323, density=5.8, surface=3252352)
        response = self.client.get(reverse('provinciasCrud:get_one_province', args=[province.id]))
        print(response)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Santa Fe')
        # self.assertQuerysetEqual(response.context['province'], {})

    def test_get_all_provinces(self):
        """if provinces array is empty, return appropiate message"""
        province = Provinces.objects.create(id=1, name='Santa Fe', population=23142323, density=5.8, surface=3252352)
        response = self.client.get(reverse('provinciasCrud:get_provinces'))
        print(response)
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'Santa Fe')


#!/usr/bin/env python3

import sys
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA

NUMBER_OF_WORDS = 50

file_path = sys.argv[1]

lines = pd.read_table(file_path, header=None, delim_whitespace=True)
lines = lines.sample(NUMBER_OF_WORDS).reset_index(drop=True)
words = lines.iloc[:, 0]
vectors = lines.iloc[:, 1:]

pca = PCA(n_components=2)
vecs_transformed = pca.fit_transform(vectors)

plt.figure(figsize=(16, 16))
for i in range(len(words)):
    (x, y) = [float(val) for val in vecs_transformed[i]]
    plt.scatter(x, y)
    plt.annotate(words[i],
                 xy=(x, y),
                 xytext=(5, 2),
                 textcoords='offset points',
                 ha='right',
                 va='bottom')

plt.show()
plt.savefig('evaluation.png')


from os.path import abspath, dirname, join

from preggy import expect
from tornado.testing import gen_test

from tests.base import TestCase
from thumbor.compatibility.storage import Storage
from thumbor.config import Config
from thumbor.context import Context, ServerParameters
from thumbor.importer import Importer

STORAGE_PATH = abspath(join(dirname(__file__), "../fixtures/images/"))

class CompatibilityStorageTestCase(TestCase):
    def get_image_path(self, name):
        return f"./tests/fixtures/images/{name}"

    def get_image_bytes(self, name):
        with open(self.get_image_path(name), "rb") as img:
            return img.read()

    def get_image_url(self, name):
        return f"s.glbimg.com/some/{name}"

    def get_context(self):
        config = Config(
            FILE_LOADER_ROOT_PATH=STORAGE_PATH,
            COMPATIBILITY_LEGACY_STORAGE="tests.compatibility.legacy_file_storage",
            STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True,
        )
        importer = Importer(config)
        importer.import_modules()
        server = ServerParameters(
            8889, "localhost", "thumbor.conf", None, "info", None
        )
        server.security_key = "ACME-SEC"
        return Context(server, config=config, importer=importer)

    @gen_test
    async def test_should_raise_for_invalid_compatibility_storage(self):
        config = Config(
            FILE_LOADER_ROOT_PATH=STORAGE_PATH,
            STORES_CRYPTO_KEY_FOR_EACH_IMAGE=True,
        )
        importer = Importer(config)
        importer.import_modules()
        server = ServerParameters(
            8889, "localhost", "thumbor.conf", None, "info", None
        )
        server.security_key = "ACME-SEC"
        ctx = Context(server, config=config, importer=importer)
        storage = Storage(ctx)

        with expect.error_to_happen(
            RuntimeError,
            message=(
                "The 'COMPATIBILITY_LEGACY_STORAGE' configuration should "
                "point to a valid storage when using compatibility storage."
            ),
        ):
            await storage.get("invalid-path")

    @gen_test
    async def test_should_return_none_for_invalid_image(self):
        storage = Storage(self.context)

        result = await storage.get("invalid-path")

        expect(result).to_be_null()

    @gen_test
    async def test_should_get(self):
        url = self.get_image_url("image.jpg")
        image_bytes = self.get_image_bytes("image.jpg")
        storage = Storage(self.context)
        await storage.put(url, image_bytes)

        result = await storage.get(url)

        expect(result).not_to_be_null()
        expect(result).not_to_be_an_error()
        expect(result).to_equal(image_bytes)

    @gen_test
    async def test_should_put(self):
        url = self.get_image_url("image.jpg")
        image_bytes = self.get_image_bytes("image.jpg")
        storage = Storage(self.context)

        await storage.put(url, image_bytes)

        result = await storage.get(url)
        expect(result).not_to_be_null()
        expect(result).not_to_be_an_error()
        expect(result).to_equal(image_bytes)

    @gen_test
    async def test_should_put_detector_data(self):
        iurl = self.get_image_url("image_7.jpg")
        ibytes = self.get_image_bytes("image.jpg")
        storage = Storage(self.context)
        await storage.put(iurl, ibytes)

        await storage.put_detector_data(iurl, "some-data")

        got = await storage.get_detector_data(iurl)
        expect(got).not_to_be_null()
        expect(got).not_to_be_an_error()
        expect(got).to_equal("some-data")

    @gen_test
    async def test_should_put_crypto(self):
        iurl = self.get_image_url("image_7.jpg")
        ibytes = self.get_image_bytes("image.jpg")
        storage = Storage(self.context)
        await storage.put(iurl, ibytes)

        await storage.put_crypto(iurl)

        got = await storage.get_crypto(iurl)
        expect(got).not_to_be_null()
        expect(got).not_to_be_an_error()
        expect(got).to_equal("ACME-SEC")

    @gen_test
    async def test_exists(self):
        iurl = self.get_image_url("image_7.jpg")
        ibytes = self.get_image_bytes("image.jpg")
        storage = Storage(self.context)
        await storage.put(iurl, ibytes)

        exists = await storage.exists(iurl)
        not_exists = await storage.exists("some-invalid-random-file.jpg")

        expect(exists).to_be_true()
        expect(not_exists).to_be_false()

    @gen_test
    async def test_remove(self):
        iurl = self.get_image_url("image_7.jpg")
        ibytes = self.get_image_bytes("image.jpg")
        storage = Storage(self.context)
        await storage.put(iurl, ibytes)
        exists = await storage.exists(iurl)
        expect(exists).to_be_true()

        await storage.remove(iurl)

        not_exists = await storage.exists(iurl)
        expect(not_exists).to_be_false()


import requests
from .models import Item
import datetime
from django.utils.timezone import make_aware
def fetch_items():
    conn = requests.get('https://hacker-news.firebaseio.com/v0/newstories.json?print=pretty')
    res = sorted(conn.json())
    return list(reversed(res))[:5] # top 5 stories

def fetch_item_by_id(item):
    int_item = int(item)
    conn = requests.get(f'https://hacker-news.firebaseio.com/v0/item/{int_item}.json?print=pretty')
    res = conn.json()
    if res['type'] == 'job':
        print(res)
    return res

def add_kid(kid):
    comment = fetch_item_by_id(kid)
    parent = Item.objects.get(id=comment['parent'])
    if 'deleted'in comment or 'dead' in comment:
        return
    obj = get_obj(comment)
    Item.objects.create(**obj, parent=parent)
    return obj

def get_obj(detail):
    type = detail.get("type")
    id = str(detail.get("id"))
    by = detail.get("by")
    timestamp = datetime.datetime.fromtimestamp(detail.get("time"))
    time = make_aware(timestamp)
    url = detail.get("url")
    title = detail.get("title")
    text = detail.get("text")
    descendants = detail.get("descendants", 0)
    score = detail.get("score", 0)
    obj = {
        "type": type,
        "id": id,
        "by": by,
        "time": time,
        "url": url,
        "title": title,
        "text": text,
        "score": score,
        "fetched": True,
        "descendants": descendants
    }
    return obj

def add_to_db():
    items = fetch_items()
    for single in items:
        details = fetch_item_by_id(single)
        if details['type'] == 'comment' or 'deleted' in details or 'dead' in details:
            return
        if details['type'] == 'job':
            print(details)
        if not Item.objects.filter(id=details['id']).exists():
            item_obj = get_obj(details)
            Item.objects.create(**item_obj)
            if 'kids' in details:
                kids = details['kids']
                for kid in kids:
                    add_kid(kid)


from __future__ import annotations

from PySide6.QtCore import QMargins, QPoint, QRect, QSize, Qt
from PySide6.QtWidgets import QLayout, QSizePolicy, QWidgetItem

class FlowLayout(QLayout):
    def __init__(self, parent=None, center=False):
        super().__init__(parent)

        if parent is not None:
            self.setContentsMargins(QMargins(0, 0, 0, 0))

        self._item_list: list[QWidgetItem] = []
        self.center = center

    def __del__(self):
        item = self.takeAt(0)
        while item:
            item = self.takeAt(0)

    def addItem(self, item):
        self._item_list.append(item)

    def count(self):
        return len(self._item_list)

    def itemAt(self, index):
        if 0 <= index < len(self._item_list):
            return self._item_list[index]

        return None

    def takeAt(self, index):
        if 0 <= index < len(self._item_list):
            return self._item_list.pop(index)

        return None

    def expandingDirections(self):
        return Qt.Orientation(0)

    def hasHeightForWidth(self):
        return True

    def heightForWidth(self, width):
        height = self._do_layout(QRect(0, 0, width, 0), True)
        return height

    def setGeometry(self, rect):
        super().setGeometry(rect)
        self._do_layout(rect, False)

    def sizeHint(self):
        return self.minimumSize()

    def minimumSize(self):
        size = QSize()

        for item in self._item_list:
            size = size.expandedTo(item.minimumSize())

        size += QSize(2 * self.contentsMargins().top(), 2 * self.contentsMargins().top())
        return size

    def _do_layout(self, rect, test_only):
        x = rect.x()
        y = rect.y()
        line_height = 0
        spacing = self.spacing()

        rows: list[tuple[list[QWidgetItem], int, int]] = []

        row = []
        for item in self._item_list:
            style = item.widget().style()
            layout_spacing_x = style.layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Horizontal)
            layout_spacing_y = style.layoutSpacing(QSizePolicy.PushButton, QSizePolicy.PushButton, Qt.Vertical)
            space_x = (
                spacing + layout_spacing_x
            ) * item.widget().isVisible()  # If an item isn't visible, it does not have any influence on the next
            space_y = spacing + layout_spacing_y
            next_x = x + item.sizeHint().width() + space_x
            if next_x - space_x > rect.right() and line_height > 0:
                rows.append(
                    (row, rect.right() - x - space_x, line_height)
                )  # We need to remove the unnecessary extra padding from all rows, not just the last
                row = []
                x = rect.x()
                y = y + line_height + space_y
                next_x = x + item.sizeHint().width() + space_x
                line_height = 0

            if not test_only:
                item.setGeometry(QRect(QPoint(x, y), item.sizeHint()))

            x = next_x
            line_height = max(line_height, item.sizeHint().height())
            row.append(item)

        rows.append((row, rect.right() - x - space_x, line_height))

        if not test_only and self.center:
            for items, x_margin, y_size in rows:
                x_margin /= 2
                for item in items:
                    r = item.geometry()
                    new_y = r.y()
                    if r.height() < y_size:
                        new_y += (y_size - r.height()) / 2
                    item.setGeometry(QRect(QPoint(r.x() + x_margin, new_y), item.sizeHint()))

        return y + line_height - rect.y()


import cv2
smilecascade=cv2.CascadeClassifier('haarcascade\\haarcascade_smile.xml')

cap = cv2.VideoCapture(0)

while 1:
    ret, img=cap.read()
    #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    smiles = smilecascade.detectMultiScale(img, 1.3,50 )

    for (x,y,w,h) in smiles:
        cv2.rectangle(img, (x,y), (x+w, y+h), (255,255,255), 2)

    cv2.imshow('img', img)

    if cv2.waitKey(1) & 0xFF==ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


from __future__ import print_function

import re

import bitarray

def filterFeatures(sr_obj, feature_types=None, qualifier_regexs=None):
    """Filter a `SeqRecord` object's `SeqFeature` list by type and qualifiers.

    Args:
        sr_obj (``SeqRecord``)              : instantiated Biopython
                                              ``SeqRecord`` object

        feature_types (list, optional)      : list of feature types
                                              (e.g., ['gene', 'CDS'])
        qualifier_regexs (dict, optional)   : dict of <field name>:
                                              <value regex> entries

    Returns:
        Filtered list of `SeqRecord` objects

    Raises:
        None

    Examples:

        Return a list of all ``SeqFeature`` objects from ``gb_rec``
        that are of type 'mRNA' or 'CDS'::

            >>>filterFeatures(gb_rec, ['mRNA', 'CDS'])

        Return a list of all ``SeqFeature`` objects from ``gb_rec``
        that are of type 'mRNA' or 'CDS' and that additionally have the
        qualifier field 'gene' with a value that matches the regular expression
        'ubc.*'::

            >>>filterFeatures(gb_rec, ['gene', 'CDS'], {'gene': 'ubc.*'})

        The latter example would match the following genbank records::

            CDS             join(54..567,789..1254)
                            /gene="ubc42"
                            /product="ubiquitin conjugating enzyme"
                            /function="cell division control"

            CDS             join(54..567,789..1254)
                            /gene="ubc51"
                            /product="ubiquitin conjugating enzyme"
                            /function="cell division control"

    """
    qualifier_regexs = qualifier_regexs or {}
    features = sr_obj.features

    def _featureFilter(feature):
        if feature_types is not None and feature.type not in feature_types:
            return False
        for feat_key, feat_value_re in qualifier_regexs.items():
            q_values = feature.qualifiers.get(feat_key, None)
            if q_values is None:
                return False
            for v in q_values:
                if re.search(feat_value_re, v) is None:
                    return False
        return True

    return filter(_featureFilter, features)

def findBorders(sr_obj, feature_types=None, qualifier_regexs=None,
                strand_specific=False):
    """Filter a ``SeqFeature`` list and find the border indices of its members.

    See :func:`filterFeatures` for explanation of filtering functionality.

    Args:
        sr_obj (``SeqRecord``): instantiated Biopython ``SeqRecord`` object

        feature_types (list, optional)      : list of feature types (e.g.,
                                              ['gene', 'CDS'])
        qualifier_regexs (list, optional)   : dict of <field name>:
                                              <value regex> entries
        strand_specific (list, optional)    : boolean determining whether
                                              separate lists should be returned
                                              for each strand (fwd / rev)
    Returns:
        List(s) of (<idx>, <1 if rising edge, 0 if falling edge>) tuples.

    Raises:
        None

    """
    filtered_features = filterFeatures(sr_obj, feature_types, qualifier_regexs)
    if strand_specific:
        fwd_feat_list = []
        rev_feat_list = []
    else:
        feat_list = []
    for feat in filtered_features:
        if strand_specific:
            if feat.location.strand == -1:
                feat_list = rev_feat_list
            else:
                feat_list = fwd_feat_list
        feat_list.append((feat.location.start, 1))
        feat_list.append((feat.location.end, 0))
    if strand_specific:
        return fwd_feat_list, rev_feat_list
    else:
        return feat_list

def buildBorderLUT(sr_obj, feature_types=None, qualifier_regexs=None,
                   strand_specific=False):
    """Filter a ``SeqRecord``'s features and build a binary LUT of border edges.

    See :func:`filterFeatures` for explanation of filtering functionality.

    Args:
        sr_obj (``SeqRecord``): instantiated Biopython ``SeqRecord`` object

        feature_types (list, optional)      : list of feature types (e.g.,
                                              ['gene', 'CDS'])
        qualifier_regexs (list, optional)   : dict of <field name>:
                                              <value regex> entries
        strand_specific (list, optional)    : boolean determining whether
                                              separate lists should be returned
                                              for each strand (fwd / rev)
    Returns:
        Binary bitarray(s) (``bitarray.bitarray``) indicating the indices of
        feature borders (border indices have a value of 1). Strand-specific
        bitarrays are returned if ``strand_specific`` is ``True``.

    Raises:
        None

    """
    if strand_specific:
        fwd_feat_list, rev_feat_list = findBorders(sr_obj, feature_types,
                                                   qualifier_regexs,
                                                   strand_specific)
        fwd_lut = bitarray.bitarray(len(sr_obj.seq))
        fwd_lut.setall(0)
        rev_lut = bitarray.bitarray(len(sr_obj.seq))
        rev_lut.setall(0)
        for rec in fwd_feat_list:
            fwd_lut[rec[0]] = 1
        for rec in rev_feat_list:
            rev_lut[rec[0]] = 1
        return fwd_lut, rev_lut
    else:
        feat_list = findBorders(sr_obj, feature_types, qualifier_regexs,
                                strand_specific)
        feat_lut = bitarray.bitarray(len(sr_obj.seq))
        feat_lut.setall(0)
        for rec in feat_list:
            try:
                feat_lut[rec[0]] = 1
            except IndexError:
                print('IndexError while generating border array {}'.format(
                      rec[0]))
        return feat_lut

def findAggregateBoundaries(sr_obj, feature_types=None, qualifier_regexs=None):
    """Determine the outermost border indices of a group of filtered features.

    See :func:`filterFeatures` for explanation of filtering functionality.

    Args:
        sr_obj (``SeqRecord``): instantiated Biopython ``SeqRecord`` object

        feature_types (list, optional)      : list of feature types (e.g.,
                                              ['gene', 'CDS'])
        qualifier_regexs (list, optional)   : dict of <field name>:
                                              <value regex> entries

    Returns:
        Tuple of (<min index>, <max index>) of the filtered features

    Raises:
        None

    For example, let's say your genbank file has the following features:

        synth_seg   1001..2000
                        /label="seg17_000"
        synth_seg   2001..3000
                        /label="seg17_001"
        synth_seg   3001..4000
                        /label="seg17_002"
        synth_seg   4001..5000
                        /label="seg18_000"

        Then the following call will produce this output::

        >>>findAggregateBoundaries(sr, ['synth_seg'], {'label': r'seg17.*'})
        (1001, 4000)

    """
    filtered_features = list(filterFeatures(sr_obj, feature_types,
                                            qualifier_regexs))
    if len(filtered_features) == 0:
        return None, None
    min_idx = len(sr_obj.seq) + 1
    max_idx = -1
    for ff in filtered_features:
        min_idx = min(int(ff.location.start), min_idx)
        max_idx = max(int(ff.location.end), max_idx)
    return min_idx, max_idx