# -*- coding: utf-8 -*-
#https://www.youtube.com/channel/UCBWVx7ngVu5kWQ9CcGT2tEQ
import pygame

window = pygame.display.set_mode((400, 400))
pygame.display.set_caption('Hello, pygame!')
screen = pygame.Surface((400, 400))

class Sprite:
    def __init__(self,xpos,ypos,filename):
        self.x=xpos
        self.y=ypos
        self.bitmap=pygame.image.load(filename)
        self.bitmap.set_colorkey((0,0,0))
    def render(self):
        screen.blit(self.bitmap,(self.x,self.y))

def Intersect(x1, x2, y1, y2):
    if (x1 > x2-40) and (x1 < x2+40) and (y1 > y2-40) and (y1 < y2+40):
        return 1
    else:
        return 0

hero = Sprite(350, 200, 'images/h.png')
hero.up = True
zet = Sprite(10, 200, 'images/z.png')
zet.up = False

done = True
while done:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            done = False

    screen.fill((50, 50, 50))

    if hero.up == True:
        hero.x -= 1
        if hero.x == 0:
            hero.up = False
    else:
        hero.x += 1
        if hero.x == 350:
            hero.up = True

    if zet.up == True:
        zet.x -= 1
        if zet.x == 0:
            zet.up = False
    else:
        zet.x += 1
        if zet.x == 350:
            zet.up = True

    if Intersect(zet.x, hero.x, zet.y, hero.y) == True:
            hero.up = False
            zet.up = True

    zet.render()
    hero.render()
    window.blit(screen, (0,0))
    pygame.display.flip()
    pygame.time.delay(5)


import pytest

from typing import Any
from typing import Dict
from typing import List

from thoth.common import RuntimeEnvironment
from thoth.python.constraints import Constraints
from thoth.adviser.boots import EnvironmentInfoBoot
from thoth.adviser.context import Context
from thoth.adviser.pipeline_builder import PipelineBuilderContext
from thoth.adviser.enums import RecommendationType
from thoth.common import get_justification_link as jl
from ..base import AdviserUnitTestCase

class TestEnvironmentInfoBoot(AdviserUnitTestCase):
    """Test providing environment information used in the stack information."""

    UNIT_TESTED = EnvironmentInfoBoot

    def test_verify_multiple_should_include(self) -> None:
        """Verify multiple should_include calls do not loop endlessly."""
        builder_context = PipelineBuilderContext(recommendation_type=RecommendationType.LATEST)
        self.verify_multiple_should_include(builder_context)

    def test_should_include(self, builder_context: PipelineBuilderContext) -> None:
        """Test registering this unit for adviser runs."""
        assert list(self.UNIT_TESTED.should_include(builder_context)) == [{}]

        builder_context.add_unit(self.UNIT_TESTED())

        assert list(self.UNIT_TESTED.should_include(builder_context)) == []

    @pytest.mark.parametrize(
        "runtime_environment_dict,expected,use_constraints,use_library_usage",
        [
            (
                {
                    "base_image": "quay.io/thoth-station/s2i-thoth-ubi8-py38:v1.0.0",
                    "cuda_version": "11.1",
                    "cudnn_version": "7.6.5",
                    "hardware": {"cpu_family": 1, "cpu_model": 2, "gpu_model": "Some GPU model"},
                    "mkl_version": "2021.1",
                    "name": "rhel-9",
                    "openblas_version": "0.3.0",
                    "openmpi_version": "4.0.5",
                    "operating_system": {"name": "rhel", "version": "9"},
                    "platform": "linux-x86_64",
                    "python_version": "3.10",
                    "recommendation_type": "latest",
                },
                [
                    {
                        "link": "https://thoth-station.ninja/recommendation-types/",
                        "message": "Using recommendation type 'latest'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Resolving for runtime environment named 'rhel-9'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Resolving for operating system 'rhel' in version '9'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Resolving for Python version '3.6'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Using platform 'linux-x86_64'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Using constraints provided",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Using supplied static source code analysis",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Using containerized environment "
                        "'quay.io/thoth-station/s2i-thoth-ubi8-py38:v1.0.0'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Using CPU family 1 model 2",
                        "type": "INFO",
                    },
                    {"link": jl("env"), "message": "Using CUDA '11.1'", "type": "INFO"},
                    {"link": jl("env"), "message": "Using cuDNN '7.6.5'", "type": "INFO"},
                    {"link": jl("env"), "message": "Using OpenBLAS '0.3.0'", "type": "INFO"},
                    {"link": jl("env"), "message": "Using OpenMPI '4.0.5'", "type": "INFO"},
                    {"link": jl("env"), "message": "Using MKL '2021.1'", "type": "INFO"},
                ],
                True,
                True,
            ),
            (
                {},
                [
                    {
                        "link": "https://thoth-station.ninja/recommendation-types/",
                        "message": "Using recommendation type 'latest'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Resolving for runtime environment named 'UNKNOWN'",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Resolving for operating system None in version None",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Resolving for Python version '3.6'",
                        "type": "INFO",
                    },
                    {"link": jl("env"), "message": "Using platform 'UNKNOWN'", "type": "INFO"},
                    {
                        "link": jl("env"),
                        "message": "No constraints supplied to the resolution process",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "No static source code analysis supplied",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "No containerized environment used",
                        "type": "INFO",
                    },
                    {
                        "link": jl("env"),
                        "message": "Using CPU family 'UNKNWON' model 'UNKNOWN'",
                        "type": "INFO",
                    },
                    {"link": jl("env"), "message": "No CUDA used", "type": "INFO"},
                    {"link": jl("env"), "message": "No cuDNN used", "type": "INFO"},
                    {"link": jl("env"), "message": "No OpenBLAS used", "type": "INFO"},
                    {"link": jl("env"), "message": "No OpenMPI used", "type": "INFO"},
                    {"link": jl("env"), "message": "No MKL used", "type": "INFO"},
                ],
                False,
                False,
            ),
        ],
    )
    def test_run(
        self,
        context: Context,
        runtime_environment_dict: Dict[str, Any],
        expected: List[Dict[str, str]],
        use_constraints: bool,
        use_library_usage: bool,
    ) -> None:
        """Test providing information about the runtime environment."""
        if use_constraints:
            context.project.constraints = Constraints.from_string("flask>=1.3.0")

        if use_library_usage:
            context.library_usage = {"flask": ["flask.App"]}

        context.project.runtime_environment = RuntimeEnvironment.from_dict(runtime_environment_dict)
        assert not context.stack_info

        unit = self.UNIT_TESTED()
        with unit.assigned_context(context):
            assert unit.run() is None

        assert context.stack_info == expected
        assert self.verify_justification_schema(context.stack_info)


from mutagen.easyid3 import EasyID3
import mutagen
import shutil
from os import listdir
from os.path import  join, isfile, isdir
import re
import os
# audio = EasyID3("AlbumEditor/03 Sam Concepcion, Tippy Dos Santos and Quest Dati Official Music Video Philpop 2013.mp3")
# audio['title'] = u"Example Title2"
# audio['album'] = u"My album"
# print(audio['title'])
# print(audio)
# audio.save()

# shutil.move("AlbumEditor/test1.mp3", "AlbumEditor/moved")

class PolishMp3():
    def __init__(self, album=None, artist=None):
        self.baseDir = "AlbumEditor/Rawmp3"
        # self.baseDir = "/Users/nhoj/Desktop/audios/musicdesktop/classic"
        self.MoveDir = "AlbumEditor/ReadyToExportmp3"
        # self.MoveDir = "/Volumes/version2/Third/Visual Studio Code /Python/audioConvert/AlbumEditor/moved   "
        print(self.baseDir)
        print('\n\n')
        self.album = album
        self.artist = artist
        self.getList()

    def getList(self):

        with os.scandir(self.baseDir) as entries:
            for entry in entries:
                if isfile(entry):
                    # os.system('chflags nouchg {}'.format(entry.path))
                    print('Done\n\n')
                    try:
                        print('YES')
                        print(self.baseDir)
                        print(entry.path)
                        # self.checkIfLocked(entry.name)
                        self.checkIfLocked(entry)
                        print('Done Checking Locked Status',entry.name)
                        audio = EasyID3(entry.path)
                        # audio['title'] =  ''.join([i for i in entry.name[:-4] if not i.isdigit()]).lstrip(' ')
                        # audio['title'] =  ''.join([i for i in re.sub("\s\s+", " ",re.sub('[^a-zA-Z0-9 \n\.]', ' ', entry.name[:-4])) if not i.isdigit()]).lstrip(' ').rstrip()
                        audio['title'] =  ''.join([i for i in re.sub("\s\s+", " ",re.sub(r'[^a-zA-Z0-9 \n\.]', ' ', entry.name[:-4])) if not i.isdigit()]).lstrip(' ').rstrip()
                        if self.album is not None:
                            audio['album'] = self.album
                        else:
                            audio['album'] = 'From Lenovo'
                        # audio['artist'] = 'Old Laptop'
                        if self.artist is not None:
                            audio['albumartist'] = self.artist
                        else:
                            audio['albumartist'] = 'Lenovo'
                        audio.save()
                        old_file = os.path.join(entry.path)
                        new_file = os.path.join(self.MoveDir, audio['title'][0]+entry.name[-4::])
                        os.rename(old_file, new_file)
                        print(audio['title'][0])
                        print(audio)

                    except Exception as e:

                        print('Fail')
                        print(e,'\n\n')
                        pass
                print(entry)
                print('\n')

    def checkIfLocked(self,locked_filename):
        print('checking.....',locked_filename)
        print('Dir: ',self.baseDir)
        print("TYPE: ",type(locked_filename))

        # x= os.stat(self.baseDir+'/'+locked_filename).st_flags
        try:
            x= os.stat(locked_filename).st_flags
            print('FIles is Locked: ' ,x)
            # os.stat(locked_filename).st_flags=0
            # print(os.stat(locked_filename).__format__)
            xx = os.system('chflags nouchg {}'.format(locked_filename))
        except Exception as e:
            print("Fail to Check")
            # print(e)
            pass
        # xx = os.system('chflags nouchg {}'.format(self.baseDir+'/'+locked_filename))
        print('Unlocked',os.stat(locked_filename).st_flags)

    def moveMp3(self,fileToMove):
        # shutil.move(fileToMove,self.MoveDir)
        shutil.copy(fileToMove,self.MoveDir)

PolishMp3('My First Album', 'Me Myself and I')


import os
import sys
from re import *

class JackTokenizer:
    # curr_file_name = ""

    keyword_list = {"class", "constructor", "function", "method", "field",
                    "static",
                    "var", "int", "char", "boolean", "void", "true", "false",
                    "null",
                    "false", "let", "do", "if", "else", "while", "return", "this"}

    symbol_list = {'{', '}', '(', ')', '[', ']', '.', ',', ';', '+', '-', '*',
                   '/', '&',
                   '|', '<', '>', '=', '~'}

    def __init__(self, inputFile):
        self.inputPath = inputFile
        self.file = open(inputFile, 'r')
        self.lines = self.file.readlines()
        self.file.close()
        # self.findEndBlock = False
        self.inStringFlag = False
        self.inCommentFlag = False
        self.dontGetIn = False

        self.tokens = list()
        self.goThroughLines()
        self.currIndex = 0
        self.token = self.tokens[self.currIndex]

    def hasMoreTokens(self):
        if self.currIndex == len(self.tokens):
            return False
        else:
            return True

    def advance(self):
        self.currIndex += 1
        self.token = self.tokens[self.currIndex]

    def tokenType(self):
        if self.token in JackTokenizer.keyword_list:
            return "KEYWORD"
        elif self.token in JackTokenizer.symbol_list:
            return "SYMBOL"
        elif match("^[0-9]+", self.token):
            return "INT_CONST"
        elif match("^[\"].*[\"]$", self.token):
            return "STRING_CONST"
        elif match("^[^0-9]+.*", self.token):
            return "IDENTIFIER"
        else:
            print("ruti and nir you've got an error")

    def keyWord(self):
        return self.token

    def symbol(self):
        return self.token

    def identifier(self):
        return self.token

    def intVal(self):
        return self.token

    def stringVal(self):
        return self.token

    def makeOneSpace(self, line):

        flag = False
        found_first_space = False
        if search("^\s+", line) and search("^\s+", line).end() != len(
                line):
            line = line[search("^\s+", line).end():]
        st_list = list(line)
        for i in range(len(line)):

            if st_list[i] == '\"':
                flag = not flag

            if not flag:
                if st_list[i] == ' ' and not found_first_space:
                    found_first_space = True
                    continue
                elif st_list[i] == ' ' and found_first_space:
                    st_list[i] = ''
                else:
                    found_first_space = False
        if st_list:
            if st_list[-1] == " ":
                st_list[-1] = ''
        return ''.join(st_list)

    def splitBySpace(self, line):
        start_index = 0
        lst = list()
        st_list = list(line)
        flag = False
        for i in range(len(line)):

            if st_list[i] == '\"':
                flag = not flag

            if not flag:
                if st_list[i] == ' ' or len(line) - 1 == i:
                    if len(line) - 1 == i and st_list[i] != ' ':
                        i = i + 1
                    lst.append(line[start_index:i])
                    start_index = i + 1
        return lst

    def relevantLines(self, line):
        newline = ""
        for index in range(len(line)):
            char = line[index]
            if not self.inStringFlag:
                if not self.inCommentFlag:

                    if match("(/\*)",line[index: index +2]):
                        self.inCommentFlag = True
                        continue
                    elif match("//",line[index: index +2]) and not self.dontGetIn:
                        break
                else:
                    if match("\*/",line[index:index+2]):
                        self.inCommentFlag = False
                        self.dontGetIn = True
                        continue
            if not self.inCommentFlag:
                if self.dontGetIn:
                    self.dontGetIn = False
                    newline += " "
                    continue
                if self.inStringFlag and char == '\t':
                    char = ' '
                if char == '\"':
                    self.inStringFlag = not self.inStringFlag
                newline += char
                continue

        return newline

    def processLine(self, line):
        line = line.replace("\r\n", "")
        line = line.replace("\n", "")

        line = self.relevantLines(line)
        res = ""
        flag = False
        for i in range(len(line)):
            if not flag and line[i] in JackTokenizer.symbol_list:
                res += " " + line[i] + " "
            elif line[i] == '\"':
                flag = not flag
                res += line[i]
            else:
                res += line[i]
        return self.makeOneSpace(res)

    def goThroughLines(self):
        for index in range(len(self.lines)):
            self.lines[index] = self.processLine(self.lines[index])
        for index in range(len(self.lines)):
            self.lines[index] = self.lines[index].replace("\t","")
            if match("^[\s]*[\t]*$", self.lines[index]):
                pass
            else:
                splited = self.splitBySpace(self.lines[index])
                for token in splited:
                    self.tokens.append(token)

    def revealNext(self):
        if self.currIndex + 1 < len(self.tokens):
            return self.tokens[self.currIndex + 1]
        else:
            return None

    def revealTwoNext(self):
        if self.currIndex + 2 < len(self.tokens):
            return self.tokens[self.currIndex + 2]
        else:
            return None

    def getToken(self):
        return self.token


from django.shortcuts import render, HttpResponseRedirect
from .forms import UserRegistration
from .models import User

# Create your views here.
def index(request):
    if request.method == 'POST':
        fm = UserRegistration(request.POST)
        if fm.is_valid():
            number = fm.cleaned_data['number']
            firstname = fm.cleaned_data['firstname']
            lastname = fm.cleaned_data['lastname']
            birtday = fm.cleaned_data['birtday']
            language = fm.cleaned_data['language']
            country = fm.cleaned_data['country']
            reg = User(
                number=number, firstname=firstname, lastname=lastname,
                birtday=birtday, language=language, country=country)
            reg.save()
            fm = UserRegistration()
    else:
        fm = UserRegistration()
    stud = User.objects.all()

    return render(request, 'index.html', {
        'form': fm, 'stu':stud
    })

def update(request, id):
    if request.method == 'POST':
        pi = User.objects.get(pk=id)
        fm = UserRegistration(request.POST, instance=pi)
        if fm.is_valid():
            fm.save()
    else:
        pi = User.objects.get(pk=id)
        fm = UserRegistration(instance=pi)

    return render(request, 'update.html', {
        'form': fm
    })

def delete(request, id):
    if request.method == 'POST':
        pi = User.objects.get(pk=id)
        pi.delete()

    return HttpResponseRedirect('/')


import pandas as pd

# check whether overlapping folds
training = '/path/to/9_FINAL/data/machine_learning/two_class/one-hot-ecoding/train/cross_validation/training/training_'
validation = '/path/to/9_FINAL/data/machine_learning/two_class/one-hot-ecoding/train/cross_validation/validation/val_fold_'

all_data = []

# get unique values
for x in range(0,5):
    training_name = training+str(x)+'.csv'
    training_file = pd.read_csv(training_name, sep=";") # read data
    training_file = training_file[['instance', 'class', 'id', 'label']] # subset to relevant columns
    all_data.append(training_file) # append data
    print('Training: {}'.format(len(training_file))) # sanity check

    validation_name = validation + str(x) + '.csv'
    validation_file = pd.read_csv(validation_name,sep=";")#
    validation_file = validation_file[['instance', 'class', 'id', 'label']]
    all_data.append(validation_file)
    print('Validation: {}'.format(len(validation_file)))

    unique_ids = training_file.id.tolist()
    unique_ids.extend(validation_file.id.tolist())
    unique_ids = list(set(unique_ids))
    print('Unique values: {}'.format(len(unique_ids)))
    print('All values {}'.format(len(training_file)+len(validation_file)))
    print('----------------------------------------')

all_data = pd.concat(all_data)
print(all_data.head())
all_data.columns = ['instance', 'class', 'id', 'label']

# remove duplicates
all_data = all_data.drop_duplicates(subset='id', keep='first')

print(len(all_data))

all_data.to_csv('/path/to/9_FINAL/data/machine_learning/two_class/distance/raw/all_distance_tuples.csv',sep=";")


import yaml

class CFG:
    def __init__(self, yaml_path):
        if isinstance(yaml_path, str):
            with open(yaml_path, "r") as f:
                yaml_data = yaml.safe_load(f)
        else:
            yaml_data = yaml_path

        for key, value in yaml_data.items():
            if isinstance(value, dict):
                setattr(self, key, CFG(value))
            else:
                setattr(self, key, value)

def get_config(file):
    cfg = CFG(file)
    return cfg

if __name__ == '__main__':
    cfg = get_config("./configs/PRE_CONT_UBFC.yaml")
    print(cfg)


import sys
import heapq

# 시간 초과
n = int(sys.stdin.readline())
nums = []
answer = []
for _ in range(n):
    # 입력 숫자
    number = int(sys.stdin.readline())
    # 힙에 넣기
    heapq.heappush(nums, number)

    mid = (len(nums) - 1) // 2
    idx = 0
    nums_tmp = []
    while nums:
        del_num = heapq.heappop(nums)
        if idx == mid:
            answer.append(del_num)
        idx += 1
        nums_tmp.append(del_num)

    nums += nums_tmp

for a in answer:
    print(a)

# nums.sort()
#
# while nums:
#     print(heapq.heappop(nums))

# print(nums)
# 1 5 2 10 -99 7 5

# -99 1 2 5 5 7 10


import transparentbackup
import os
import tarfile
import codecs
import difflib
import shutil

def readFile (pathName):
  if os.path.isfile(pathName):
    with codecs.open(pathName, 'r', 'utf-8') as f:
      return f.readlines()
  else:
    return []

def listDir (pathName):
  if not os.path.isdir(pathName):
    return ()
  return os.listdir(pathName)

D = "srcs*"

def T (data):
  srcs = sorted(listDir(data))

  DIR_PATH_NAME = u"/tmp/TransparentBackup"
  SRC_PATH_NAME = os.path.join(DIR_PATH_NAME, "src")
  OUT_PATH_NAME = os.path.join(DIR_PATH_NAME, "out")
  PREV_DTML_PATH_NAME = os.path.join(DIR_PATH_NAME, "prevsrc.dtml")
  CURR_DTML_PATH_NAME = os.path.join(DIR_PATH_NAME, "src.dtml")

  firstSrc = True
  for src in srcs:
    os.makedirs(SRC_PATH_NAME)
    with tarfile.open(os.path.join(data, src)) as tf:
      tf.extractall(SRC_PATH_NAME)

    firstScripttype = True
    for scripttypeCls in (transparentbackup.getScripttypeCls(p + "Script") for p in ("Bash", "ZippingPython")):
      t("Backing up {} with {}{}:", src, scripttypeCls.__name__, (" incrementally against prev", "")[firstSrc])
      os.makedirs(OUT_PATH_NAME)
      transparentbackup.transparentbackup(SRC_PATH_NAME, (PREV_DTML_PATH_NAME, None)[firstSrc], None, u".NOBACKUP", 0, OUT_PATH_NAME, scripttypeCls)

      dtmlPathName = os.path.join(OUT_PATH_NAME, "!fullstate.dtml")
      builddiffsPathName = glob.glob(os.path.join(OUT_PATH_NAME, "!builddiffs.*"))[0]
      prePathName = glob.glob(os.path.join(OUT_PATH_NAME, "!pre_applydiffs.*"))[0]
      postPathName = glob.glob(os.path.join(OUT_PATH_NAME, "!post_applydiffs.*"))[0]
      if firstScripttype:
        t("dtml\n--------\n{}\n--------", "".join(readFile(dtmlPathName)))
      else:
        t("dtml diffs\n--------\n{}\n--------", "".join(difflib.unified_diff(readFile(CURR_DTML_PATH_NAME), readFile(dtmlPathName))))
      t("builddiffs\n--------\n{}\n--------", "".join(readFile(builddiffsPathName)))
      t("pre_applydiffs\n--------\n{}\n--------", "".join(readFile(prePathName)))
      t("post_applydiffs\n--------\n{}\n--------", "".join(readFile(postPathName)))

      if firstScripttype:
        os.rename(dtmlPathName, CURR_DTML_PATH_NAME)

      shutil.rmtree(OUT_PATH_NAME)
      firstScripttype = False

    os.rename(CURR_DTML_PATH_NAME, PREV_DTML_PATH_NAME)

    shutil.rmtree(SRC_PATH_NAME)
    firstSrc = False


class Solution:
    def findContinuousSequence(self, target: int) -> List[List[int]]:
        ans, sol = [], [1, 2]
        # 使用双指针
        left, right = 1, 2
        while right <= target // 2 + 1:
            currSum = (left + right) * (right - left + 1) / 2
            if currSum == target:
                ans.append(sol[:])
                right += 1
                sol.append(right)
            elif currSum < target:
                right += 1
                sol.append(right)
            else:
                sol.pop(0)
                left += 1
        return ans


import pandas as pd
import numpy as np
import os
import re
import glob
from pathlib import Path
import chardet
from datetime import datetime

# EXTRACCIÓN

def importar(path):
    # Esta función importa archivos en múltiples formatos, teniendo en cuenta que si el archivo es formato xlsx
    # puede contener varias hojas con tablas. Además, si el archivo trata sobre relevamiento de precios, crea una
    # columna en la cual indica la fecha en la que se realizo el relevamiento extrayendo el valor del nombre del
    # archivo, el objetivo de esto es tener una referencia para hacer cargas incrementales.

    data = pd.DataFrame()
    with open(path, 'rb') as f:
        result = chardet.detect(f.read()) # Obtener encoding del archivo

        # IMPORTAR ARCHIVOS

        # csv
        if Path(path).suffix == '.csv':
            data = pd.read_csv(path, encoding=result['encoding'], sep=',', engine='python', decimal='.')

            data_texto = os.path.split(path)[1].split('.')[0] # Extraer el texto del cual se sacará la fecha (nombre de archivo)

            auxiliar = data_texto.split('_') # Secciono el nombre del archivo
            auxiliar = list(set(auxiliar))  # Creo una lista con los elementos únicos del nombre del archivo

            for e in auxiliar:

                if e.isdigit() == True: # Determino si en el nombre del archivo hay dígitos referentes a la fecha
                    data['fecha_semana'] = datetime.strptime(e, '%Y%m%d') # Creo la columna "fecha_semana" para tener la referencia de cuando
                                                                          # se hizo el relevamiento del precio
                else:
                    data = data

        # txt
        elif Path(path).suffix == '.txt':
            data = pd.read_table(path, encoding=result['encoding'], sep='|', engine='python')
            data_texto = os.path.split(path)[1].split('.')[0] # Extraer el texto del cual se sacará la fecha

            auxiliar = data_texto.split('_') # Secciono el nombre del archivo
            auxiliar = list(set(auxiliar))  # Creo una lista con los elementos únicos del nombre del archivo

            for e in auxiliar:

                if e.isdigit() == True: # Determino si en el nombre del archivo hay dígitos referentes a la fecha
                    data['fecha_semana'] = datetime.strptime(e, '%Y%m%d') # Creo la columna "fecha_semana" para tener la referencia de cuando
                                                                          # se hizo el relevamiento del precio
                else:
                    data = data

        # json
        elif Path(path).suffix == '.json':
            data = pd.read_json(path, encoding=result['encoding'], precise_float=True)
            data_texto = os.path.split(path)[1].split('.')[0] # Extraer el texto del cual se sacará la fecha

            auxiliar = data_texto.split('_') # Secciono el nombre del archivo
            auxiliar = list(set(auxiliar))  # Creo una lista con los elementos únicos del nombre del archivo

            for e in auxiliar:

                if e.isdigit() == True: # Determino si en el nombre del archivo hay dígitos referentes a la fecha
                    data['fecha_semana'] = datetime.strptime(e, '%Y%m%d') # Creo la columna "fecha_semana" para tener la referencia de cuando
                                                                          # se hizo el relevamiento del precio
                else:
                    data = data

        # parquet
        elif Path(path).suffix == '.parquet':

            data = pd.read_parquet(path, engine='pyarrow')
            data_texto = os.path.split(path)[1].split('.')[0].split('.')[0] # Extraer el texto del cual se sacará la fecha

            auxiliar = data_texto.split('_') # Secciono el nombre del archivo
            auxiliar = list(set(auxiliar))  # Creo una lista con los elementos únicos del nombre del archivo

            for e in auxiliar:

                if e.isdigit() == True: # Determino si en el nombre del archivo hay dígitos referentes a la fecha
                    data['fecha_semana'] = datetime.strptime(e, '%Y%m%d') # Creo la columna "fecha_semana" para tener la referencia de cuando
                                                                          # se hizo el relevamiento del precio
                else:
                    data = data

        # xlsx
        elif Path(path).suffix == '.xlsx':
            dict_aux = pd.read_excel(path, sheet_name=None) # Diccionario donde key: nombre de hoja , values: df con valores del archivo
            lst_df = []
            for key in dict_aux.keys():                     # Agrego los df a una lista

                data_fecha = key.split('_')[-1] # fecha semana de relevamiento

                if data_fecha in key:

                    df = dict_aux[key]
                    df['fecha_semana'] = datetime.strptime(data_fecha, '%Y%m%d') # Creo la columna "fecha_semana" para tener la referencia de cuando
                                                                                # se hizo el relevamiento del precio
                    lst_df.append(df)

                else:
                    df = dict_aux[key]
                    lst_df.append(df)

            data = pd.concat(lst_df, axis=0)   # Concateno los df que contiene la lista

            for col in data.columns:
                if 'fecha_semana' in col:
                    data = data.sort_values('fecha_semana')

            data.reset_index(drop=True, inplace = True)

    return data

# TRANSFORMACIÓN

# El parámetro a pasar a la función es un diccionario de dataframes

def transformacion(dicc_df):

    # REGISTROS DUPLICADOS:

    # Bucle para eliminar los resgistros duplicados
    for key in dicc_df.keys():
        dicc_df[key].drop_duplicates(inplace = True)

    # VALORES FALTANTES:

    # Bucle para eliminar las columnas categoria del dataframe producto
    for key in dicc_df.keys():
        if 'producto' in key:
            for col in dicc_df[key].columns:
                if 'categoria' in col:
                    dicc_df[key].drop(columns = col, inplace = True)

    # Hay datos de precios con valores iguales a '' los cuales deberán reemplazarse por np.nan para ser tratados como los demás valores faltantes
    # Reemplazo los valores '' por np.nan
    for key in dicc_df.keys():
        if 'precio' in key:
            for col in dicc_df[key].columns:
                if 'precio' in col:
                    dicc_df[key][col].replace('', np.nan, inplace = True)

    # Bucle para eliminar los registros con valores faltantes
    for key in dicc_df.keys():
        dicc_df[key].dropna(inplace = True)

    # NORMALIZACIÓN

    # Reemplazo id por producto_id en el df producto
    for key in dicc_df.keys():
        if 'producto' in key:
            for col in dicc_df[key].columns:
                if col == 'id':
                    dicc_df[key].rename(columns = {col:'producto_id'}, inplace = True)

    # Reemplazo id por sucursal_id en el df sucursal
    for key in dicc_df.keys():
        if 'sucursal' in key:
            for col in dicc_df[key].columns:
                if col == 'id':
                    dicc_df[key].rename(columns = {col:'sucursal_id'}, inplace = True)

    # Doy el orden correcto a las columnas de los DF de precios_semana
    for key in dicc_df.keys():
        if 'precio' in key:
            dicc_df[key] = dicc_df[key][['precio', 'producto_id', 'sucursal_id', 'fecha_semana']]

    # Cambio el tipo de dato a las columnas 'precio' a float
    for key in dicc_df.keys():
        if 'precio' in key:
            for col in dicc_df[key].columns:
                if 'precio' in col:
                    dicc_df[key][col] = dicc_df[key][col].astype(float)

    # Función para corregir errores en los id y poner el tipo de dato correcto
    def mod_id_prod(x):
        if isinstance(x,str):
            x = x.split('-')[-1]
        elif isinstance(x,float):
            x = int(x)
        else:
            x=x
        return str(x).zfill(13) # Esta línea es para que los id queden con el formato de código EAN de 13 dígitos

    for key in dicc_df.keys():
        if 'precios_semana' in key or 'producto' in key:
            for col in dicc_df[key].columns:
                if col == 'producto_id':
                    dicc_df[key][col] = dicc_df[key][col].apply(mod_id_prod)

    # Función para corregir los elementos de la columna 'sucursal_id'
    # de los DF 'precios_semana' que presentan formato 'datetime'
    def mod_suc_id(x):
        if type(x) == datetime:
            x=x.strftime("%#d-%#m-%Y")
        return x

    for key in dicc_df.keys():
        if 'precio' in key:
            for col in dicc_df[key].columns:
                if 'sucursal_id' in col:
                    dicc_df[key][col] = dicc_df[key][col].apply(mod_suc_id)

    # Bucle para eliminar outliers de precios
    for key in dicc_df.keys():
        if 'precios_semana' in key:
            for col in dicc_df[key].columns:
                if 'precio' in col:
                    dicc_df[key][col] = dicc_df[key][col][dicc_df[key][col] <= 1000000]

    # REGISTROS DUPLICADOS:

    # Bucle para eliminar los resgistros duplicados
    for key in dicc_df.keys():
        dicc_df[key].drop_duplicates(inplace = True)

    # Elimino id duplicados de los DF 'producto' y 'sucursal'
    # debido a que serán primary key en la base de datos
    for key in dicc_df.keys():
        if 'producto' in key or 'sucursal' in key:
            for col in dicc_df[key].columns:
                if 'producto_id' in col or 'sucursal_id' in col:

                    dicc_df[key] = dicc_df[key].drop_duplicates(
                                    dicc_df[key].columns[dicc_df[key].columns.isin([col])],
                                    keep='first'
                                    )

    return dicc_df


import random
from timeit import default_timer
def heapify(arr, n, i):
    largest = i
    l = 2 * i + 1
    r = 2 * i + 2

    if l < n and arr[largest] < arr[l]:
        largest = l

    if r < n and arr[largest] < arr[r]:
        largest = r

    if largest != i:
        arr[i], arr[largest] = arr[largest], arr[i]

        heapify(arr, n, largest)

def heapSort(arr):
    n = len(arr)

    for i in range(n//2 - 1, -1, -1):
        heapify(arr, n, i)

    for i in range(n-1, 0, -1):
        arr[i], arr[0] = arr[0], arr[i]
        heapify(arr, i, 0)

def evaluateheap(ndatos):
    A = []
    tiempo = 0.0
    for i in range(5):
        for j in range(multiplicadordatos*ndatos):
            a = random.randint(1,10000)
            A.append(a)

        inicio = default_timer()
        heapSort(A)
        fin = default_timer()
        tiempo = tiempo + (fin-inicio)
        A.clear()

    return tiempo/5.0


import time
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import patches as mpl_patches
from matplotlib import lines as mpl_lines
from scipy.integrate import ode

# Physical constants
g = 9.8
damping_factor = 0.9 * 0
length_r1 = 2.0
length_r2 = 4.0
mass_bob1 = 10.0
mass_bob2 = 5.0
plotsize = 1.10 * (length_r1 + length_r2)

# initial state
theta1_initial = + 120 / 180 * np.pi
theta2_initial = + 180 / 180 * np.pi
theta1_dot_initial = 0
theta2_dot_initial = 0

def calc_xy(length, theta):
    x = length * np.sin(theta)
    y = - length * np.cos(theta)
    return x, y

_x1, _y1 = calc_xy(length_r1, theta1_initial)
bob1 = mpl_patches.Circle((_x1, _y1), 0.05 * plotsize, fc='g', alpha=1, zorder=2)
bob1.set_picker(0)
stick1 = mpl_lines.Line2D([0, _x1], [0, _y1], zorder=2)

_x2, _y2 = calc_xy(length_r2, theta2_initial)
_x2 += _x1
_y2 += _y1
bob2 = mpl_patches.Circle((_x2, _y2), 0.05 * plotsize, fc='r', alpha=1, zorder=2)
stick2 = mpl_lines.Line2D([_x1, _x2], [_y1, _y2], zorder=2)

def get_derivatives_double_pendulum(t, state):
    ''' definition of ordinary differential equation for a
        double pendulum
    '''
    theta1, theta1_dot, theta2, theta2_dot = state

    _num1 = -g * (2 * mass_bob1 + mass_bob2) * np.sin(theta1)
    _num2 = -mass_bob2 * g * np.sin(theta1-2*theta2)
    _num3 = -2*np.sin(theta1-theta2) * mass_bob2
    _num4 = theta2_dot * theta2_dot * length_r2 + \
            theta1_dot * theta1_dot * length_r1 * np.cos(theta1-theta2)
    _den = length_r1 * (2 * mass_bob1 + mass_bob2 - \
           mass_bob2 * np.cos(2*theta1-2*theta2))
    theta1_doubledot = (_num1 + _num2 + _num3 * _num4) / _den

    _num1 = 2 * np.sin(theta1-theta2)
    _num2 = (theta1_dot * theta1_dot * length_r1 * (mass_bob1 + mass_bob2))
    _num3 = g * (mass_bob1 + mass_bob2) * np.cos(theta1)
    _num4 = (theta2_dot * theta2_dot * length_r2 * \
            mass_bob2 * np.cos(theta1-theta2))
    _den = length_r2 * (2 * mass_bob1 + mass_bob2 - \
           mass_bob2 * np.cos(2*theta1-2*theta2))
    theta2_doubledot = (_num1 * (_num2 + _num3 + _num4)) / _den

    state_differentiated = np.zeros(4)
    state_differentiated[0] = theta1_dot
    state_differentiated[1] = theta1_doubledot
    state_differentiated[2] = theta2_dot
    state_differentiated[3] = theta2_doubledot

    return state_differentiated

dp_integrator = ode(get_derivatives_double_pendulum).set_integrator('vode')

def plot_double_pendulum(fig, trace_line, ax2, theta_line):
    # note a frame per second (fps) > 10 the actual time
    # may not be able to keep up with model time
    fps = 15
    seconds_per_frame = 1/fps

    def current_time():
        return time.time()

    def check_drift(_time, running_time):
        # check every 5 seconds
        if _time % 5 < seconds_per_frame:
            print(f'time (ms): {1000*_time:,.0f}, '
                  f'drift: {1000*(running_time - _time):,.0f}')

    t_initial = 0
    _time = t_initial

    state = np.array([theta1_initial, theta1_dot_initial,
                      theta2_initial, theta2_dot_initial])
    dp_integrator.set_initial_value(state, t_initial)

    _x2, _y2 = bob2.center
    x_traces = [_x2]
    y_traces = [_y2]

    time_window = 20
    time_base = - time_window

    actual_start_time = current_time()
    while dp_integrator.successful():

        theta1, _, theta2, _ = state

        _x1, _y1 = calc_xy(length_r1, theta1)
        bob1.center = (_x1, _y1)
        stick1.set_data([0, _x1], [0, _y1])

        _x2, _y2 = calc_xy(length_r2, theta2)
        _y2 += _y1
        _x2 += _x1
        bob2.center = (_x2, _y2)
        stick2.set_data([_x1, _x2], [_y1, _y2])

        x_traces.append(_x2)
        y_traces.append(_y2)
        trace_line.set_data(x_traces[:], y_traces[:])

        if _time % time_window < seconds_per_frame:
            time_base += time_window
            ax2.set_xlim(time_base, time_base+time_window)
            time_values = []
            theta_values = []

        time_values.append(_time)
        angle = -np.pi + (theta1 - np.pi) % (2 * np.pi)
        theta_values.append(np.degrees(angle))
        theta_line.set_data(time_values, theta_values)

        running_time = current_time() - actual_start_time
        check_drift(_time, running_time)

        while running_time < _time:
            running_time = current_time() - actual_start_time

        else:
            # blip the image
            fig.canvas.draw()
            fig.canvas.flush_events()

        state = dp_integrator.integrate(dp_integrator.t + seconds_per_frame)
        _time += seconds_per_frame

        if _time > 500:
            return

def main():
    '''  set plot and action
    '''
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(5, 5))
    fig.canvas.set_window_title('Double Pendulum')
    ax1.set_title('s1: click on green bob to start ...')
    ax1.set_xlim(-plotsize, plotsize)
    ax1.set_ylim(-plotsize, plotsize)
    ax1.set_aspect(1)
    trace_line, = ax1.plot([0], [0], color='black', linewidth=0.2, zorder=1)

    theta_line, = ax2.plot([0], [0], color='black', linewidth=0.5, zorder=1)
    ax2.set_ylim(-200, 200)

    def on_pick(event):
        plot_double_pendulum(fig, trace_line, ax2, theta_line)

    ax1.add_patch(bob1)
    ax1.add_line(stick1)
    ax1.add_patch(bob2)
    ax1.add_line(stick2)

    bob1.figure.canvas.mpl_connect('pick_event', on_pick)

    plt.show()

if __name__ == "__main__":
    main()


"""Main entry point."""
import logging
from argparse import ArgumentParser, Namespace
from os import path
from shutil import rmtree

from beku.kuttl import renderer_from_file, expand
from .version import __version__

def parse_cli_args() -> Namespace:
    """Parse command line args."""
    parser = ArgumentParser(
        description="Kuttl test expander for the Stackable Data Platform")
    parser.add_argument(
        "-v",
        "--version",
        help="Display application version",
        action='version',
        version=f'%(prog)s {__version__}'
    )

    parser.add_argument(
        "-i",
        "--test_definition",
        help="Test definition file.",
        type=str,
        required=False,
        default="tests/test-definition.yaml",
    )
    parser.add_argument(
        "-t",
        "--template_dir",
        help="Folder with test templates.",
        type=str,
        required=False,
        default="tests/templates/kuttl",
    )
    parser.add_argument(
        "-o",
        "--output_dir",
        help="Output folder for the expanded test cases.",
        type=str,
        required=False,
        default="tests/_work",
    )

    parser.add_argument(
        "-l",
        "--log_level",
        help="Set log level.",
        type=str,
        required=False,
        choices=["debug", "info"],
        default="info",
    )

    parser.add_argument(
        "-k",
        "--kuttl_test",
        help="Kuttl test suite definition file.",
        type=str,
        required=False,
        default="tests/kuttl-test.yaml.jinja2",
    )

    parser.add_argument(
        "-s",
        "--suite",
        help="Name of the test suite to expand. Default: default",
        type=str,
        required=False,
        default="default",
    )

    return parser.parse_args()

def _cli_log_level(cli_arg: str) -> int:
    if cli_arg == "debug":
        return logging.DEBUG
    return logging.INFO

def main() -> int:
    """Main"""
    cli_args = parse_cli_args()
    logging.basicConfig(
        encoding="utf-8", level=_cli_log_level(cli_args.log_level))
    effective_test_suites = renderer_from_file(cli_args.test_definition)
    rmtree(path=cli_args.output_dir, ignore_errors=True)
    # Compatibility warning: add 'tests' to output_dir
    output_dir = path.join(cli_args.output_dir, "tests")
    return expand(cli_args.suite, effective_test_suites, cli_args.template_dir, output_dir, cli_args.kuttl_test)


"""
预处理
预测未完待续...
"""

import paddle
import cv2
import skimage.measure as measure
import numpy as np

licence_plate=cv2.imread('./car_licence_test.png')

# h,w,c=licence_plate.shape
# print(h,w,c,licence_plate.shape)
# cv2.imshow('car licence',licence_plate)
# cv2.waitKey(0)

#预处理
#灰度化
gray_plate=cv2.cvtColor(licence_plate,cv2.COLOR_RGB2GRAY)
# cv2.imshow('gary',gray_plate)
# cv2.waitKey(0)

#二值化
ret,binary_plate=cv2.threshold(gray_plate,175,255,cv2.THRESH_BINARY)
# print(binary_plate.shape)
# cv2.imshow('binary',binary_plate)
# print('thresold value',ret)
# cv2.waitKey(0)

labels,labels_num=measure.label(binary_plate,return_num=True,connectivity=2)
print(labels.shape,labels_num)
# print(np.unique(labels))

dst=np.zeros_like(licence_plate,dtype='uint8')

# print((labels==1).shape)
for label in np.unique(labels):
    if label==0:
        continue

    # [b,g,r]=np.random.randint(0,256,size=(3))
    # dst[:,:,0][labels==label],dst[:,:,1][labels==label],dst[:,:,2][labels==label]=[b,g,r]
    dst[:,:,0][labels==label],dst[:,:,1][labels==label],dst[:,:,2][labels==label]=np.random.randint(0,256,size=(3))

    cv2.imshow('dst',dst)
    cv2.waitKey(1000)
    # break

# cv2.imshow('dst',dst)
cv2.waitKey(0)


import requests
from datetime import datetime

class VK:
    URL = 'https://api.vk.com/method/'

    def __init__(self, access_token, qty_photo, user_id, version='5.131'):
        self.token = access_token
        self.user_id = user_id
        self.version = version
        self.params = {'access_token': self.token, 'v': self.version}
        self.qty_photo = qty_photo

    def user_info(self, user_id):
        user_url = self.URL + 'users.get'
        user_params = {
            'user_ids': user_id
        }
        params = {**self.params, **user_params}
        response = requests.get(user_url, params).json()
        first_name = response['response'][0]['first_name']
        last_name = response['response'][0]['last_name']
        self.user_id = response['response'][0]['id']
        print(f'По введенным данным мы нашли: {first_name} {last_name} id: {self.user_id}')
        return first_name, last_name, self.user_id

    def photos_info(self):
        items = self.photos_get()['response']['items']
        photos_info = []
        likes_count = []
        repeat_likes_count = []

        for like in items:
            likes_count.append(like['likes']['count'])

        for like in likes_count:
            if likes_count.count(like) > 1:
                repeat_likes_count.append(like)

        for item in items:
            like = item['likes']['count']
            date_photo = datetime.utcfromtimestamp(item['date']).strftime('%d-%m-%Y')
            info = {
                'size': item['sizes'][-1]['type'],
                'link': item['sizes'][-1]['url']
            }

            if like in repeat_likes_count:
                info['file_name'] = f'{like}_{date_photo}.jpg'
                photos_info.append(info)
            else:
                info['file_name'] = f'{like}.jpg'
                photos_info.append(info)
        return photos_info

    def photos_get(self):
        self.user_info(self.user_id)
        album = input('Фото забираем со стены или из профиля?\n'
                      ' Введите wall или profile: ').lower()
        photos_url = self.URL + 'photos.get'
        photos_params = {
            'owner_id': self.user_id,
            'album_id': album,
            'rev': 0,
            'extended': 1,
            'count': self.qty_photo
        }

        params = {**self.params, **photos_params}
        response = requests.get(photos_url, params).json()

        return response


"""
COSMOS_IRAC_redshift_cuts.py
Author: Benjamin Floyd

Uses the COSMOS catalog to examine our IR-bright AGN selection cuts as a function of redshift to determine if we have
significant contamination in our sample.
"""

import matplotlib.pyplot as plt
import numpy as np
from astropy.table import Table
from matplotlib.lines import Line2D

# Read in th COSMOS catalog
cosmos = Table.read('Data/COSMOS2015_Laigle+_v1.1.fits.gz')

#%%
# Remove non-detections
cosmos = cosmos[(cosmos['SPLASH_1_MAG'] > -99) &
                (cosmos['SPLASH_2_MAG'] > -99) &
                (cosmos['SPLASH_3_MAG'] > -99) &
                (cosmos['SPLASH_4_MAG'] > -99)]
cosmos = cosmos[(cosmos['PHOTOZ'] >= 0) | (cosmos['ZQ'] >= 0)]

# Convert the IRAC magnitudes from AB to Vega (because I don't want to have to convert the selections to AB).
cosmos['SPLASH_1_MAG'] += -2.788
cosmos['SPLASH_2_MAG'] += -3.255
cosmos['SPLASH_3_MAG'] += -3.743
cosmos['SPLASH_4_MAG'] += -4.372

# Apply our 4.5 um magnitude cuts as we would in SDWFS/SPT
cosmos = cosmos[(10.45 < cosmos['SPLASH_2_MAG']) & (cosmos['SPLASH_2_MAG'] < 17.46)]

# Apply Stern Wedge selection
stern_agn = cosmos[(cosmos['SPLASH_3_MAG'] - cosmos['SPLASH_4_MAG'] > 0.6) &
                   (cosmos['SPLASH_1_MAG'] - cosmos['SPLASH_2_MAG'] >
                    0.2 * (cosmos['SPLASH_3_MAG'] - cosmos['SPLASH_4_MAG']) + 0.18) &
                   (cosmos['SPLASH_1_MAG'] - cosmos['SPLASH_2_MAG'] >
                    2.5 * (cosmos['SPLASH_3_MAG'] - cosmos['SPLASH_4_MAG']) - 3.5)]

# Separate the non-AGN galaxies from the AGN
stern_complement_ids = list(set(cosmos['NUMBER']) - set(stern_agn['NUMBER']))
non_agn = cosmos[np.in1d(cosmos['NUMBER'], stern_complement_ids)]

#%%
non_agn_0_2 = non_agn[non_agn['PHOTOZ'] <= 4]
stern_agn_0_2 = stern_agn[stern_agn['ZQ'] <= 4]

# [3.6] - [4.5] color
agn_color = stern_agn_0_2['SPLASH_1_MAG'] - stern_agn_0_2['SPLASH_2_MAG']
non_agn_color = non_agn_0_2['SPLASH_1_MAG'] - non_agn_0_2['SPLASH_2_MAG']

#%%
fig = plt.figure()
gs = fig.add_gridspec(nrows=1, ncols=2, width_ratios=(8, 3), wspace=0)

# Main plot
ax = fig.add_subplot(gs[0])
ax.hexbin(non_agn_0_2['PHOTOZ'], non_agn_color, gridsize=(2500, 100), bins='log', mincnt=1, cmap='Blues')
ax.hexbin(stern_agn_0_2['ZQ'], agn_color, gridsize=(50, 75), bins='log', mincnt=1, cmap='Reds', alpha=0.5)
ax.set(title='COSMOS', xlabel='Photometric Redshift', ylabel='[3.6] - [4.5] (Vega)', xlim=[0, 4], ylim=[0., 1.5])

ax.axhline(y=0.7, color='k', linewidth=2)
# ax.arrow(0.25, 0.7, 0, 0.2, color='k', width=0.004, head_width=6 * 0.004, length_includes_head=True)

handles, labels = ax.get_legend_handles_labels()
handles.extend([Line2D([0], [0], marker='h', color='w', markerfacecolor='lightcoral', markeredgecolor='firebrick',
                       markersize=10),
                Line2D([0], [0], marker='h', color='w', markerfacecolor='lightblue', markeredgecolor='steelblue',
                       markersize=10)
                ])
labels.extend(['Stern Wedge AGN', 'Non-Active Galaxies'])
ax.legend(handles, labels, frameon=False)

# Side histogram
ax_hist = fig.add_subplot(gs[1], sharey=ax)
ax_hist.tick_params(axis='y', labelleft=False)
min_z, max_z = ax.get_xlim()
binwidth = 0.05
bins_nonAGN = np.arange(np.min(non_agn_color), np.max(non_agn_color) + binwidth, binwidth)
bins_AGN = np.arange(np.min(agn_color), np.max(agn_color) + binwidth, binwidth)
ax_hist.hist(agn_color[(stern_agn_0_2['ZQ'] > min_z) & (stern_agn_0_2['ZQ'] < max_z)], bins=bins_AGN,
             orientation='horizontal', color='lightcoral', alpha=0.6)
ax_hist.hist(non_agn_color[(non_agn_0_2['PHOTOZ'] > min_z) & (non_agn_0_2['PHOTOZ'] < max_z)], bins=bins_nonAGN,
             orientation='horizontal', color='lightblue', alpha=0.6)
ax_hist.axhline(y=0.7, color='k', linewidth=2)
ax_hist.set(xlabel=r'$N$', xscale='log')

# fig.savefig('Data/Plots/COSMOS_IRAC_Redshift_z4.pdf')
plt.show()


# -*- coding: utf-8 -*-
from apis.books import BooksAPI
from apis.homes import HomesAPI
from apis.orders import OrdersApi
from router.router import Router

__all__ = (
    'router'
)

mapping_list = [
    (r"/", {"GET": HomesAPI.do_index, "POST": HomesAPI.do_create}),
    (r"/api/books/", {"GET": BooksAPI.do_index, "POST": BooksAPI.do_create}),
    (r"/api/books/{id:int}/", {"GET": BooksAPI.do_index, "PUT": BooksAPI.do_create}),
    (r"/api/orders/", {"GET": OrdersApi.do_show, "POST": OrdersApi.do_update})
]

router = Router(mapping_list)


#!/usr/bin/env python
#
import os
import time
import requests
import json
import logging
import uuid
from datadog import initialize, api

# [start config]
# GCP image file url
GCP_IMAGE = 'https://storage.googleapis.com/xxx-testing-monitor/sample-invoice.png'

# S3 image file url
S3_IMAGE = 'https://s3-eu-west-1.amazonaws.com/xxx-public/xxx-testing-monitor/sample-invoice.png'

# Configure this environment variable via Dockerfile ENV
#
# Google API Key
API_KEY = os.environ['API_KEY']

# Datadog authentication api
options = {
    'api_key': 'xxx',
    'app_key': 'xxx'
}

initialize(**options)
#
logging.basicConfig(format='%(asctime)s %(levelname)s: %(message)s', level=logging.INFO,
                    datefmt='%Y-%m-%d %I:%M:%S')
# [end config]

def _generate_payload_data(image_uri):
    """Generate the request payload data
    Format copied from https://cloud.google.com/vision/docs/ocr"""
    sending_request = {
        "requests": [
            {
                "image": {
                    "source": {
                        "imageUri": image_uri
                    }
                },
                "features": [
                    {
                        "type": "DOCUMENT_TEXT_DETECTION",
                        "maxResults": 1000
                    }
                ]
            }
        ]
    }
    return sending_request

def detect_document_uri(image_uri=GCP_IMAGE, image_source='gcp_storage', env='staging'):
    """Input image url location ,image source location,
       post response status code to datadog"""

    # make a UUID based on the host ID and current time
    uid = uuid.uuid1()

    # cache brake
    cache_brake = '?uuid={}'.format(uid)

    sending_request = _generate_payload_data("{}{}".format(image_uri, cache_brake))

    # start the timer
    start_timer = time.time()

    # submit the post
    response = requests.post(
        url='https://vision.googleapis.com/v1/images:annotate?key={}'.format(API_KEY),
        data=json.dumps(sending_request),
        headers={'Content-Type': 'application/json', 'Cache-Control': 'no-cache'}
    )

    status_code = str(response.status_code)

    # stop the timer second to millisecond
    latency = (time.time() - start_timer) * 1000

    metric = "probe.google.vision.gauge.latency"
    # Post data to datadog
    api.Metric.send([{
        'metric': metric,
        'type': 'gauge',
        'host': 'k8s',
        'points': [[time.time(), float(latency)]],
        'tags': {'service': 'google-vision', 'env': env,
                            'status-code': status_code,
                            'location': 'kuberntes',
                            'image_location': image_source
                 }

    }])
    logging.info("METRIC:{} STATUS_CODE:{} LATENCY:{}".format(metric, status_code, float(latency)))
    return float(latency)

if __name__ == '__main__':
        print(detect_document_uri())
        print(detect_document_uri(S3_IMAGE, image_source='s3_storage'))


import qplot as qp
import numpy as np

qp.figure('subplot', 3, 3)

qp.subplot(2,1,1)
xx=np.linspace(0, 2*np.pi, 50)
qp.plot(xx, np.cos(xx))
qp.shrink(10)

qp.subplot(2,1,2)

qp.plot(xx, np.sin(xx))
qp.shrink(10)


#!/usr/bin/python3
def list_division(my_list_1, my_list_2, list_length):
    c = 0
    div = 0
    new_list = []
    while c != list_length:
        try:
            div = my_list_1[c] / my_list_2[c]
        except ZeroDivisionError:
            print('division by 0')
            div = 0
        except (TypeError, ValueError):
            print('wrong type')
            div = 0
        except IndexError:
            print('out of range')
            div = 0
        finally:
            new_list.append(div)
        c = c + 1
    return new_list


import re
import bs4
import real_estate.real_estate_property as rep

class PageScraper(object):
    MIN_PRICE = 10000
    UNDER_CONTRACT_REGEX = '.*(under contract|under offer)(?i)'

    DIGITS_ONLY = re.compile(r'\A(\d+)\Z')
    APPROX_LAND_AREA = re.compile(r'\A(\d+) m² \(approx\)')

    def html_to_soup(html):
        return bs4.BeautifulSoup(html, "html.parser")

    def no_results_check(soup, page_num):
        no_results = PageScraper.check_for_no_results(soup)
        if no_results:
            print("Found the 'no results' page, final page is number %i" %
                  (page_num - 1))
        return no_results

    def check_for_no_results(soup):
        ds_contents = PageScraper.get_ds_contents(soup)
        search_results = ds_contents.find(
            'form', {'id': 'searchResultsForm'}, recursive=False
        )

        err = RuntimeError('HTML not understood.')

        if search_results is not None:
            no_results = search_results.find(
                'div', {'id': 'noresults'}, recursive=False
            )
            if no_results is not None:
                return True
            else:
                raise(err)
        else:
            results = PageScraper.get_results(ds_contents)
            if results is not None:
                return False
            else:
                raise(err)

    def find_articles(soup):
        ds_contents = PageScraper.get_ds_contents(soup)
        results = PageScraper.get_results(ds_contents)

        articles = results.find(
            'div', {'id': 'searchResultsTbl'}
        ).find_all(
            'article', recursive=False
        )

        PageScraper.num_articles_check(results, len(articles))
        return articles

    def get_ds_contents(soup):
        return soup.find(
            'body', {'id': 'searchResults'}
        ).find(
            'div', {'id': 'DSContents'}
        )

    def get_results(ds_contents):
        return ds_contents.find('div', {'id': 'results'}, recursive=False)

    def num_articles_check(results, articles_len):
        results_info_text = results.find(
            'div', {'id': 'resultsInfo'}
        ).find(
            'p'
        ).get_text()

        results_on_page_search = re.search('(\d+) - (\d+)', results_info_text)
        num_articles_lower = int(results_on_page_search.group(1))
        num_articles_upper = int(results_on_page_search.group(2))
        num_articles_on_page = num_articles_upper - num_articles_lower + 1

        if num_articles_on_page != articles_len:
            raise(RuntimeError(
                'Inconsistent number of articles on page: ' +
                '%i v. %i' % (num_articles_on_page, articles_len)
            ))

    def create_properties(articles):
        properties = []
        for article in articles:
            data_content_type = article['data-content-type']

            if data_content_type == 'residential':
                p = PageScraper.scrape_residential_property(article)
                properties.append(p)
            elif data_content_type == 'new apartment project':
                child_properties = PageScraper.scrape_new_apartment_project(
                    article)
                for p in child_properties:
                    properties.append(p)
            elif data_content_type == 'residential land':
                p = PageScraper.scrape_residential_land(article)
                properties.append(p)
            elif data_content_type == 'house land package':
                p = PageScraper.scrape_house_land_package(article)
                properties.append(p)
            elif data_content_type == 'rural':
                p = PageScraper.scrape_rural_property(article)
                properties.append(p)
            else:
                p = rep.DataContentTypeNotSupported(data_content_type)
                properties.append(p)
        return properties

    def populate_state_and_postcode(properties, state, postcode):
        for p in properties:
            p.state_and_postcode = rep.StateAndPostcode(state, postcode)
        return properties

    def scrape_residential_property(article):
        listing_info = PageScraper.get_listing_info(article)

        sale_type = PageScraper.residential_sale_type(listing_info, False)
        vcard_name_soup = PageScraper.find_vcard_name_soup(listing_info)
        property_type = PageScraper.extract_property_type(vcard_name_soup)
        features = PageScraper.extract_property_features(listing_info)
        details = PageScraper.create_property_details(
            property_type, features)
        address_text = PageScraper.get_address_text(article)
        residential_property = rep.Property(sale_type, details, address_text)
        return residential_property

    def scrape_residential_land(article):
        listing_info = PageScraper.get_listing_info(article)

        sale_type = PageScraper.residential_sale_type(listing_info, False)
        features = PageScraper.maybe_extract_property_features(listing_info)
        vcard_name_soup = PageScraper.find_vcard_name_soup(listing_info)
        property_type = PageScraper.extract_property_type(vcard_name_soup)
        details = PageScraper.create_property_details(property_type, features)
        address_text = PageScraper.get_address_text(article)
        residential_land = rep.Property(sale_type, details, address_text)
        return residential_land

    def scrape_new_apartment_project(article):
        project_wrapper = article.find(
            'div', {'class': 'resultBodyWrapper projectWrapper rui-clearfix'}
        )

        children = article.find(
            'div', {'class': 'project-child-listings'}
        ).find_all(
            'a', recursive=False
        )

        child_properties = []
        for child in children:
            sale_type = PageScraper.new_project_sale_type(child)

            features_soup = child.find(
                'div', {'class': 'child'}
            ).find(
                'div', {'class': 'features'}
            )

            property_type = PageScraper.extract_property_type(child)
            features = PageScraper.extract_property_features(
                features_soup)
            details = PageScraper.create_property_details(
                property_type, features)
            address_text = PageScraper.get_address_text(child)

            child_properties.append(
                rep.Property(sale_type, details, address_text)
            )

        return child_properties

    def scrape_house_land_package(article):
        listing_info = PageScraper.get_listing_info(article)

        sale_type = PageScraper.residential_sale_type(listing_info, True)
        vcard_name_soup = PageScraper.find_vcard_name_soup(listing_info)
        property_type = PageScraper.extract_property_type(vcard_name_soup)
        features = PageScraper.extract_property_features(listing_info)
        details = PageScraper.create_property_details(
            property_type, features)
        address_text = PageScraper.get_address_text(article)
        residential_property = rep.Property(sale_type, details, address_text)
        return residential_property

    def scrape_rural_property(article):
        listing_info = PageScraper.get_listing_info(article)

        sale_type = PageScraper.residential_sale_type(listing_info, False)
        vcard_name_soup = PageScraper.find_vcard_name_soup(listing_info)

        property_type_text = PageScraper.get_property_type_text(
            vcard_name_soup)
        if property_type_text in (
            'other', 'mixed+farming', 'cropping', 'horticulture', 'dairy',
            'livestock', 'farmlet', 'viticulture'
        ):
            property_type = rep.Rural()
        elif property_type_text in ('lifestyle',):
            property_type = rep.PropertyTypeNotSupported(
                property_type_text, vcard_name_soup
            )
        else:
            raise ValueError(
                "Rural property type text was not 'other', it was: %s" %
                property_type_text
            )

        features = PageScraper.maybe_extract_property_features(listing_info)
        details = PageScraper.create_property_details(
            property_type, features)
        address_text = PageScraper.get_address_text(article)

        residential_property = rep.Property(sale_type, details, address_text)
        return residential_property

    def get_listing_info(article):
        return article.find(
            'div', {'class': 'listingInfo rui-clearfix'}
        )

    def extract_property_type(soup_with_href):
        property_type_text = PageScraper.get_property_type_text(soup_with_href)

        if property_type_text == 'house':
            return rep.House()
        elif (property_type_text == 'townhouse' or
                property_type_text == 'villa' or
                property_type_text == 'terrace'):
            return rep.TownHouse()
        elif (property_type_text == 'unit' or
                property_type_text == 'apartment' or
                property_type_text == 'flat'):
            return rep.Unit()
        elif property_type_text == 'serviced+apartment':
            return rep.ServicedApartment()
        elif property_type_text == 'studio':
            return rep.Studio()
        elif property_type_text == 'residential+land':
            return rep.Land()
        elif property_type_text == 'duplex+semi+detached':
            return rep.Duplex()
        elif property_type_text == 'retirement+living':
            return rep.RetirementLiving()
        elif property_type_text == 'unitblock':
            return rep.UnitBlock()
        elif property_type_text == 'acreage+semi+rural':
            return rep.SemiRural()
        elif property_type_text == 'other':
            return rep.NotSpecified()
        else:
            return rep.PropertyTypeNotSupported(
                property_type_text, soup_with_href)

    def get_property_type_text(soup):
        return re.search(
            '^\/property-(\w+\+?\w*\+?\w*\+?\w*)', soup['href']
        ).group(1)

    def find_vcard_name_soup(listing_info):
        return listing_info.find(
            'div', {'class': 'vcard'}
        ).find(
            'a', {'class': 'name'}
        )

    def maybe_extract_property_features(soup):
        property_features = PageScraper.get_property_features_soup(soup)
        if property_features is None:
            return {}
        else:
            return PageScraper.parse_property_features(property_features)

    def get_property_features_soup(soup):
        return soup.find(
            'dl', {'class': 'rui-property-features rui-clearfix'}
        )

    def extract_property_features(soup):
        property_features = PageScraper.get_property_features_soup(soup)
        return PageScraper.parse_property_features(property_features)

    def parse_property_features(features_soup):
        names = PageScraper.find_and_get_all_text(features_soup, ['dt'])
        names = [x.lower() for x in names]
        values = [
            PageScraper.feature_value_to_int(x, names, features_soup) for x in
            PageScraper.find_and_get_all_text(features_soup, ['dd'])
        ]
        features = dict(zip(names, values))
        return features

    def feature_value_to_int(x, names, soup):
        if PageScraper.DIGITS_ONLY.match(x) is not None:
            return int(x)
        elif PageScraper.APPROX_LAND_AREA.match(x) is not None:
                return int(PageScraper.APPROX_LAND_AREA.match(x).group(1))
        else:
            raise ValueError(
                ('Feature value string not parsable, value: %s' % x) +
                ('For names:' + ', '.join([str(a) for a in names])) +
                ('Full feature soup:\n' + str(soup))
            )

    def create_property_details(property_type, features):
        property_details = rep.Details(
            property_type=property_type,
            bedrooms=features.get('bedrooms', None),
            bathrooms=features.get('bathrooms', None),
            garage_spaces=features.get('car spaces', None),
            land_area=None,
            floor_area=None
        )
        return property_details

    def find_and_get_all_text(soup, inputs):
        return [x.get_text() for x in soup.find_all(*inputs)]

    def residential_sale_type(listing_info, off_plan):
        property_stats = PageScraper.get_property_stats(listing_info)
        under_contract = PageScraper.check_if_under_contract(property_stats)
        sale_type_text = PageScraper.find_sale_type_text(
            property_stats)
        sale_type = PageScraper.deduce_sale_type(
            sale_type_text, under_contract, off_plan)
        return sale_type

    def search_for_price_text(property_stats):
        return property_stats.find(
            'p', {'class': 'priceText'}, recursive=False
        )

    def get_property_stats(listing_info):
        return listing_info.find(
            'div', {'class': 'propertyStats'}
        )

    def find_sale_type_text(property_stats):
        price_search = PageScraper.search_for_price_text(property_stats)
        contact_agent_search = property_stats.find(
            'p', {'class': 'contactAgent'}, recursive=False
        )
        type_search = property_stats.find(
            'p', {'class': 'type'}, recursive=False
        )

        if price_search is not None and price_search.has_attr("title"):
            return price_search['title']
        elif price_search is not None:
            return price_search.get_text()
        elif type_search is not None:
            return type_search.get_text()
        elif contact_agent_search is not None:
            return contact_agent_search.get_text()
        else:
            return 'UnableToFindSaleTypeText'

    def new_project_sale_type(child):
        price_text = child.find(
            'div', {'class': 'child'}
        ).find(
            'div', {'class': 'priceAndPropertyTypeContainer'}
        ).find(
            'span', {'class': 'price rui-truncate'}
        ).get_text()

        sale_type = PageScraper.deduce_sale_type(price_text, False, False)
        return sale_type

    def deduce_sale_type(sale_text, under_contract, off_plan):
        prices = PageScraper.extract_prices(sale_text, PageScraper.MIN_PRICE)

        if off_plan:
            return rep.OffPlan(prices, under_contract=under_contract)
        elif re.match('^(?i)auction', sale_text) is not None:
            return rep.Auction(under_contract=under_contract)
        elif re.match('^(?i)tender', sale_text) is not None:
            return rep.Tender(under_contract=under_contract)
        elif PageScraper.check_for_sale_by_negotiation(sale_text):
            return rep.Negotiation(under_contract=under_contract)
        elif prices is not None:
            return rep.PrivateTreaty(prices, under_contract=under_contract)
        elif re.match('^(?i)contact agent', sale_text) is not None:
            return rep.ContactAgent(under_contract)
        elif sale_text == 'UnableToFindSaleTypeText':
            return rep.UnableToFindSaleTypeText()
        else:
            return rep.SaleTypeParseFailed()

    def check_for_sale_by_negotiation(sale_text):
        if (re.match('(?i)(price )?by negotiation', sale_text) is not None or
                re.match('(?i)by negotiaton', sale_text) is not None or
                re.match('(?i)by negotation', sale_text) is not None):
            # Found typos when scraping from the website
            return True
        else:
            return False

    def extract_prices(price_text, min_price):
        dollar_price_regex = '(\$\d+(,\d+)*)'
        dollarless_price_regex = '(\d+(,\d+)*)'

        if re.search(dollar_price_regex, price_text) is not None:
            return PageScraper.text_to_prices(dollar_price_regex, price_text)
        elif re.search(dollarless_price_regex, price_text) is not None:
            prices = PageScraper.text_to_prices(
                dollarless_price_regex, price_text)
            prices = [x for x in prices if x >= min_price]
            if len(prices) != 0:
                return prices
            else:
                return None
        else:
            return None

    def check_for_missed_prices(price_text):
        digits_regex = '(\d+,?\d*)'
        if re.search(digits_regex, price_text) is not None:
            digit_strings = re.findall(digits_regex, price_text)
            numbers = [int(x.replace(',', ''))for x in digit_strings]
            if any([x > 999 for x in numbers]):
                print(
                    'Note: Possible price will be missed: %s' % price_text
                )

    def text_to_prices(regex, price_text):
        price_strings = re.findall(regex, price_text)
        prices = [
            int(x.replace('$', '').replace(',', ''))
            for x, _ in price_strings
        ]
        return prices

    def check_if_under_contract(property_stats):
        return PageScraper.check_if_under_special(
            property_stats, PageScraper.UNDER_CONTRACT_REGEX
        )

    def check_if_under_special(property_stats, regex):
        searches = PageScraper.under_special_searches(property_stats)
        tests = [PageScraper.maybe_check_for_match(x, regex) for x in searches]
        return any(tests)

    def under_special_searches(property_stats):
        type_search = property_stats.find('p', {'class': 'type'})
        price_search = PageScraper.search_for_price_text(property_stats)
        return [type_search, price_search]

    def maybe_check_for_match(search, regex):
        if search is not None:
            text = search.get_text()
            return PageScraper.check_for_match(text, regex)
        else:
            return False

    def check_for_match(text, regex):
        if re.match(regex, text) is not None:
            return True
        else:
            return False

    def find_and_parse_address(article):
        # address_text = PageScraper.find_address_text(article)
        # address = PageScraper.parse_address(address_text)
        # return address
        raise RuntimeError('This method has been deprecated.')

    def get_address_text(article):
        return rep.AddressText(PageScraper.find_address_text(article))

    def find_address_text(article):
        photoviewer_search = article.find(
            'div', {'class': 'photoviewer'}
        )

        property_image_search = article.find(
            'div', {'class': 'propertyImage'}
        )

        if photoviewer_search is not None:
            return photoviewer_search.find('a').find(
                'img', recursive=False
            )['alt']
        elif property_image_search is not None:
            return property_image_search.find('img', recursive=False)['alt']
        else:
            raise RuntimeError('Could not find address text.')


import os
import torch
from torch.utils import data
import torchaudio

from torch.utils.data import DataLoader, Dataset
from pathlib import Path

import matplotlib.pyplot as plt

def load_audio_files(path:str, label:str):
    dataset = []
    walker = sorted(str(p) for p in Path(path).glob(f'*.wav'))

    for i, file_path in enumerate(walker):
        path, filename = os.path.split(file_path)
        speaker, _ = os.path.splitext(filename)
        speaker_id, utterance_number = speaker.split("_nohash_")
        utterance_number = int(utterance_number)

        waveform, sample_rate = torchaudio.load(file_path)
        dataset.append([waveform, sample_rate, label, speaker_id, utterance_number])

    return dataset

trainset_speech_commands_yes = load_audio_files('./data/SpeechCommands/speech_commands_v0.02/yes', 'yes')
trainset_speech_commands_no = load_audio_files('./data/SpeechCommands/speech_commands_v0.02/no', 'no')

trainloader_yes = data.DataLoader(
    trainset_speech_commands_yes,
    batch_size=1,
    shuffle=True,
    num_workers=0
)

trainloader_no = data.DataLoader(
    trainset_speech_commands_no,
    batch_size=1,
    shuffle=True,
    num_workers=0
)

def show_waveform(waveform, sample_rate, label):
    """
    docstring
    """
    print("Waveform: {}\nSample rate: {}\nLabels: {}".format(waveform, sample_rate, label))
    new_sample_rate = sample_rate / 10
    print(new_sample_rate)

    channel = 0

    waveform_transformed = torchaudio.transforms.Resample(
        sample_rate, new_sample_rate)(waveform[channel,:].view(1,-1)
    )

yes_waveform = trainset_speech_commands_yes[0][0]
yes_sample_rate = trainset_speech_commands_yes[0][1]
no_waveform = trainset_speech_commands_no[0][0]
no_sample_rate = trainset_speech_commands_no[0][1]

show_waveform(yes_waveform, yes_sample_rate, "yes")

def show_spectrogram(waveform):
    spectrogram = torchaudio.transforms.Spectrogram()(waveform)
    #print(spectrogram)
    print("Shape of spectrogram: {}".format(spectrogram.size()))

    plt.figure()
    plt.imsave(f'test/spectrogram_img.png', spectrogram.log2()[0,:,:].numpy(), cmap='gray')

show_spectrogram(yes_waveform)

def show_merspectrogram(waveform, sample_rate):
    """
    docstring
    """
    mel_spectrogram = torchaudio.transforms.MelSpectrogram(
        sample_rate
    )(waveform)
    plt.figure()
    plt.imsave(f'test/spectrogram_img.png', mel_spectrogram.log2()[0,:,:].numpy(), cmap='gray')

def show_mfcc(waveform,sample_rate):
    mfcc_spectrogram = torchaudio.transforms.MFCC(sample_rate= sample_rate)(waveform)
    print("Shape of spectrogram: {}".format(mfcc_spectrogram.size()))

    plt.figure()
    fig1 = plt.gcf()
    plt.imshow(mfcc_spectrogram.log2()[0,:,:].numpy(), cmap='gray')

    plt.figure()
    plt.plot(mfcc_spectrogram.log2()[0,:,:].numpy())
    plt.draw()

show_mfcc(no_waveform, no_sample_rate)


# Importamos las bibliotecas

from multiprocessing.connection import wait
import os
import sys
import random
import pygame

from .config import *
from .platform import Platform
from .player import Player
from .wall import Wall
from .coin import Coin

# Defenimos una clase para el videojuego
class Game:

    # Definimos un metodo de inicializacion del videojuego
    def __init__(self):
        # Pintamos nuestra ventana
        pygame.init()
        # Generamos una ventana
        self.surface = pygame.display.set_mode((WIDTH,HEIGHT))
        # Titulo de la ventana
        pygame.display.set_caption(TITLE)
        # Conocer si la aplicacion se esta ejecutando o no
        self.running = True
        #
        # self.playing = True
        # Actualizar los frames por segundo
        self.clock = pygame.time.Clock()
        # Colocamos una funete a nuestro score (Alcance)
        self.font = pygame.font.match_font(FONT)
        # Ruta absoluta de un archivo
        self.dir = os.path.dirname(__file__)
        # Ruta de la carpeta de sonidos
        self.dir_sounds = os.path.join(self.dir, 'sources/sounds')
        # Ruta de la carpeta de imagenes
        self.dir_images = os.path.join(self.dir, 'sources/sprites')

    # Definimos un metodo para iniciar el juego
    def start(self):
        # Damos un menu de opciones
        self.menu()
        # Ejecutar el metodo new
        self.new()

    # Definimos un metodo para crear un nuevo juego (Nueva partida)
    def new(self):
        # El scor comienza en 0
        self.score = 0
        # Nivel 0 del juego
        self.level = 0
        #
        self.playing = True
        self.background =  pygame.image.load(os.path.join(self.dir_images, 'background.png'))
        #
        self.generate_elements()
        # Ejecutar el metodo run
        self.run()

    # Crea los elementos deljuego
    def generate_elements(self):
        self.platform = Platform()
        self.player = Player(100, self.platform.rect.top - 200, self.dir_images)

        # Agregamos las paredes
        # self.wall = Wall(500, self.platform.rect.top)

        # Agrupar los diferentes sprites a utilizar en el video juego
        self.sprites = pygame.sprite.Group()
        self.walls = pygame.sprite.Group()
        self.coins = pygame.sprite.Group()

        # Agregamos la plataforma a la lista
        self.sprites.add(self.platform)
        self.sprites.add(self.player)
        # self.sprites.add(self.wall)

        self.generate_walls()
        # self.generate_coins()

    # Genera nuevos obstaculos
    def generate_walls(self):
        last_position = WIDTH + 400
        # Si no hay obstaculos entonces los generamos
        if not len(self.walls) > 0:
            for w in range(0, MAX_WALLS):
                # Posiciones aleatorias
                left = random.randrange( last_position + 800, last_position + 1600)
                # Generamos objetos de tipo wall
                wall = Wall(left, self.platform.rect.top, self.dir_images)
                last_position = wall.rect.right

                # Agrgar a las listas
                self.sprites.add(wall)
                self.walls.add(wall)

            # Cuando se genera un obstaculo se incrementa en 1 el nivel
            self.level += 1
            # Generamos mas monedas
            self.generate_coins()

    #
    def generate_coins(self):
        last_position = WIDTH + 100

        for c in range(0, MAX_COINS):
            pos_x = random.randrange(last_position + 180, last_position + 300)

            # Colocamos todas las monedas a un altura de 100 pixeles
            coin = Coin(pos_x, 120, self.dir_images)

            last_position = coin.rect.right

            self.sprites.add(coin)
            self.coins.add(coin)

    # Definimos un metodo para correr el juego
    def run(self):
        # Iniciamos el ciclo del juego
        while self.running:
            self.clock.tick(FPS)
            self.events()
            self.update()
            self.draw()

    # Definimos un metodo para escuchar eventos
    def events(self):
        # Optenemos los objetos de eventos realizados
        for event in pygame.event.get():
            # Si cerramos la ventana detenemos la ejecucion del codigo
            if event.type == pygame.QUIT:
                self.running = False
                pygame.quit
                sys.exit()
        key = pygame.key.get_pressed()

        if key[pygame.K_SPACE]:
            self.player.jump()

        # Reiniciar el juego
        if key[pygame.K_r] and not self.playing:
            self.new()

    # Definimos un metodo para colocar los elementos en el juego
    def draw(self):
        # Colocar color a la superficie
        # self.surface.fill(BLACK)
        self.surface.blit(self.background, (0,0))
        # Pintamos el score en pantalla
        self.draw_text()
        # Dibujar todos los sprites que la lista almacene
        self.sprites.draw(self.surface)
        # Actualizamos la ventana
        pygame.display.flip()

    # Definimos un metodo para actualizar la pantalla
    def update(self):
        if not self.playing:
            return

        # Si hubo alguna colicion
        wall = self.player.collide_with(self.walls)
        if wall:
            if self.player.collide_bottom(wall):
                self.player.skid(wall)
            else:
                self.stop()

        # obsevamos los eventos de colicion
        coin = self.player.collide_with(self.coins)
        # Si existe una colicion
        if coin:
            self.score += 1
            # La moneda se destruye una vez se a colicionado con ella
            coin.kill()
            sound = pygame.mixer.Sound(os.path.join(self.dir_sounds, 'coin.wav'))
            sound.play()

        # Actualizamos los sprites
        self.sprites.update()

        # validamos los desplazamientos con la plataforma
        self.player.validate_platform(self.platform)

        # Actualizamos lo elementos visibles y quitamos el resto
        self.update_elements(self.walls)
        self.update_elements(self.coins)

        # Generar obstaculos cuando no halla elementos en la lista walls
        self.generate_walls()

        # Damos un retardo a todas la animaciones
        pygame.time.delay(21)

    # Eliminamos Todos los elementos que no son visibles en pantalla para liberar memoria
    def update_elements(self, elements):
        for element in elements:
            # Si el elemento no es visible lo quitamos
            if not element. rect. right > 0:
                # Elimina el objeto
                element.kill()

    # Definimos un metodo para detener el video juego
    def stop(self):
        sound = pygame.mixer.Sound(os.path.join(self.dir_sounds, 'lose.wav'))
        sound.play()
        # Detenemos al jugador
        self.player.stop()
        # Detenemos los objetos
        self.stop_elements(self.walls)

        self.playing = False

    # Detener todos los elementos
    def stop_elements(self, elements):
        for element in elements:
            element.stop()

    # Formato para el score
    def score_format(self):
        return 'Score : {}'.format(self.score)

    # Formato del nivel
    def level_format(self):
        return 'Level : {}'.format(self.level)

    # Pinta el score
    def draw_text(self):
        self.display_text(self.score_format(), 36, BLACK, WIDTH // 2, 30)
        self.display_text(self.level_format(), 36, BLACK, 80, TEXT_POSY)

        # Si el jugador ya no esta jugan 'Perdio'
        if not self.playing:
            self.display_text('Perdiste', 60, BLACK, WIDTH // 2, HEIGHT // 2)
            self.display_text('Preciona r para volver a comenzar', 30, BLACK, WIDTH // 2, 70)

    # Texto emn pantalla
    def display_text(self, text, size, color, pos_x, pos_y):
        # Obtenemos la fuente
        font = pygame.font.Font(self.font, size)
        # obtenemos el texto
        text = font.render(text, True, color)
        # Obtenemos el rectangulo
        rect = text.get_rect()
        # Posicion del texto
        rect.midtop = (pos_x, pos_y)
        # Pintamos el texto en pantalla
        self.surface.blit(text, rect)

    # Menu del juego
    def menu(self):
        self.surface.fill(GREEN_LIGHT)
        self.display_text('Presiona una tecla para comenzar', 36, BLACK, WIDTH // 2, 10)
        # Actualizamos la pantalla
        pygame.display.flip()
        # Esperamos un evento
        self.wait()

    # Metodo a la espera de eventos
    def wait(self):
        wait = True

        while wait:
            self.clock.tick(FPS)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    wait = False
                    self.running = False
                    pygame.quit()
                    sys.exit()

                if event.type == pygame.KEYUP:
                    wait = False


from vllm import LLM, SamplingParams
import torch
from constants_prompt import build_autoj_input
from zh_constants_prompt import zh_build_autoj_input
import argparse

def extract_pariwise_result(raw_output):
    raw_output = raw_output.strip()
    pos = raw_output.rfind('final decision is ')
    pred_label = -1
    if pos != -1:
        pred_rest = raw_output[pos + len('final decision is '):].strip().lower()
        if pred_rest.startswith('response 1'):
            pred_label = 0
        elif pred_rest.startswith('response 2'):
            pred_label = 1
        elif pred_rest.startswith('tie'):
            pred_label = 2
    return pred_label

def zh_extract_pariwise_result(raw_output):
    raw_output = raw_output.strip()
    pos = raw_output.rfind('最终决定是')
    pred_label = -1
    if pos != -1:
        # pred_rest = raw_output[pos + len('final decision is '):].strip().lower()
        pred_rest = raw_output[pos + len('最终决定是'):].strip()
        if pred_rest.startswith('回应1'):
            pred_label = 0
        elif pred_rest.startswith('回应2'):
            pred_label = 1
        elif pred_rest.startswith('平局'):
            pred_label = 2
    return pred_label

def extract_single_rating(score_output):
    if "Rating: [[" in score_output:
        pos = score_output.rfind("Rating: [[")
        pos2 = score_output.find("]]", pos)
        assert pos != -1 and pos2 != -1
        return float(score_output[pos + len("Rating: [["):pos2].strip())
    else:
        return 0.0

def zh_extract_single_rating(score_output):
    if "评分:[[" in score_output:
        pos = score_output.rfind("评分:[[")
        pos2 = score_output.find("]]", pos)
        assert pos != -1 and pos2 != -1
        return float(score_output[pos + len("评分:[["):pos2].strip())
    elif "打分:[[" in score_output:
        pos = score_output.rfind("打分:[[")
        pos2 = score_output.find("]]", pos)
        assert pos != -1 and pos2 != -1
        return float(score_output[pos + len("打分:[["):pos2].strip())
    else:
        return 0.0

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument("--language", type=str, default="Chinese", help="Choose Chinese or English evaluation")
    args = parser.parse_args()
    assert args.language == "Chinese" or args.language == "English"
    num_gpus = torch.cuda.device_count()
    model_name_or_dir = "GAIR/autoj-bilingual-6b"  # or "local path to auto-j"
    llm = LLM(model=model_name_or_dir, tensor_parallel_size=num_gpus,)
    sampling_params = SamplingParams(temperature=0.0, top_p=1.0, max_tokens=1024)

    if args.language == "Chinese":
        # input_single = zh_build_autoj_input(prompt="中国的首都是哪里？",
        #                                 resp1="中国的首都是上海。",
        #                                 protocol="zh_single")
        input_pairwise = zh_build_autoj_input(prompt="中国的首都是哪里?",
                                        resp1="中国的首都是北京。",
                                        resp2="中国的首都是上海。",
                                        protocol="zh_pairwise_tie")
        input = input_pairwise  # or input_single
        # input = input_single

        outputs = llm.generate(input, sampling_params)

        judgment = outputs[0].outputs[0].text

        print(judgment)

        evaluation_result = zh_extract_pariwise_result(judgment)
        # single_score = zh_extract_single_rating(judgment)
        # print(single_score)

        print(evaluation_result)

    elif args.language == "English":
        input_pairwise = build_autoj_input(prompt="What's the capital of the United States?",
                                       resp1="The capital of the United States is New York.",
                                       resp2="The captical of the United States is Washington D.C.",
                                       protocol="pairwise_tie")

            # input = input_pairwise  # or input_single
        input = input_pairwise

        outputs = llm.generate(input, sampling_params)

        judgment = outputs[0].outputs[0].text

        print(judgment)

        evaluation_result = extract_pariwise_result(judgment)

        print(evaluation_result)


import logging

import aiohttp.web_request
from aiohttp import web
from aiomisc import bind_socket

from disk.db import db_session
from disk.db import models
from disk.utils.erase import erase
from disk.utils.tree import get_tree
from disk.utils.validation import datetime_valid

routes = web.RouteTableDef()

@routes.post('/imports')
async def imports(request: aiohttp.web_request.Request):
    items = []
    try:
        json_data = await request.json()
        update_date = json_data['updateDate']
        for item in json_data['items']:
            item: dict
            db_item = models.items.Item()
            item_id = item['id']
            parent_id = item.get('parentId', None)

            db_item.id = item_id
            db_item.parent_id = parent_id
            if not datetime_valid(update_date):
                raise KeyError
            db_item.date = update_date

            if 'FILE' == item['type']:
                size = int(item['size'])
                url = item.get('url', None)

                db_item.size = size
                db_item.url = url
            elif 'FOLDER' == item['type']:
                pass
            else:
                raise KeyError
            db_item.type = item['type']
            items.append(db_item)
    except KeyError:
        result = {
            "code": 400,
            "message": "Validation Failed"
        }
        return web.json_response(result, status=400)

    db_sess = db_session.create_session()

    for item in items:
        item: models.items.Item
        if db_sess.query(models.items.Item).filter_by(id=item.id).count() < 1:
            db_sess.add(item)
        else:
            old_item = db_sess.query(models.items.Item).filter_by(id=item.id).first()
            old_item: models.items.Item
            old_item.copy(item)

        if not item.parent_id is None and item.parent_id:
            try:
                parent = db_sess.query(models.items.Item).filter_by(id=item.parent_id).first()
                parent: models.items.Item
                parent.add_child(item.id)
            except Exception as e:
                print(e)
                db_sess.close()
                result = {
                    "code": 400,
                    "message": "Validation Failed"
                }
                return web.json_response(result, status=400)
    db_sess.commit()
    db_sess.close()
    return web.Response(status=200)

@routes.delete('/delete/{id}')
def delete(request: aiohttp.web_request.Request):
    item_id = request.match_info.get('id', None)
    try:
        date = request.rel_url.query['date']
        if not datetime_valid(date):
            result = {
                "code": 400,
                "message": "Validation Failed"
            }
            return web.json_response(result, status=400)
    except Exception:
        result = {
            "code": 400,
            "message": "Validation Failed"
        }
        return web.json_response(result, status=400)
    if item_id is None:
        result = {
            "code": 400,
            "message": "Validation Failed"
        }
        return web.json_response(result, status=400)
    try:
        erase(item_id)
    except ValueError:
        result = {
            "code": 404,
            "message": "Item not found"
        }
        return web.json_response(result, status=404)
    return web.Response(status=200)

@routes.get('/nodes/{id}')
def nodes(request: aiohttp.web_request.Request):
    item_id = request.match_info.get('id', None)
    if item_id is None:
        result = {
            "code": 400,
            "message": "Validation Failed"
        }
        return web.json_response(result, status=400)

    try:
        result = get_tree(item_id)
        return web.json_response(result, status=200)
    except ValueError:
        result = {
            "code": 404,
            "message": "Item not found"
        }

def main():
    logging.basicConfig(level=logging.DEBUG)

    db_session.global_init("../db/data.db")

    sock = bind_socket(address='0.0.0.0', port=8080, proto_name='http')

    app = web.Application()
    app.router.add_routes(routes)
    web.run_app(app, sock=sock)

if __name__ == '__main__':
    main()


import numpy as np

def cgls(A, b, tol=1e-6, maxit=20, x0=np.array([]), Pl=np.array(1)):
  """
  intend to solve argmin_{x}Pl*||A*x - b||
  Toy, no sanity checks and exception-flag-returns written
  """
  if x0.size == 0: x0 = np.zeros([A.shape[1], b.shape[1]])

  H = lambda X: X.conj().T # Hermitian
  sqtol = np.power(tol, 2)  # sq the res norm tol to avoid sqrt
  sqnorm_p = lambda X: np.real(np.sum(X.conj()*X, axis=0)) # primal/dual sqnorm
  sqnorm_d = lambda X: np.real(np.sum(X.conj()*(Pl.dot(X)), axis=0))
  eps = np.spacing(1)

  bp_sqnorm = sqnorm_p(H(A).dot(Pl.dot(b)))
  bp_sqnorm_sqtol = sqtol*bp_sqnorm

  x  = x0
  rd = b - A.dot(x)         # dual residual (w/o Pl)
  rp = H(A).dot(Pl.dot(rd)) # primal residual
  pp = rp
  rp_sqnorm_old = sqnorm_p(rp)

  k, flag, exceptFlag = 0, False, 0
  while k < maxit and not flag:
    k += 1
    pd = A.dot(pp)
    alpha = rp_sqnorm_old/(sqnorm_d(pd) + eps)

    x  = x + alpha*pp
    rd = rd - alpha*pd # w/o Pl
    rp = H(A).dot(Pl.dot(rd))

    rp_sqnorm = sqnorm_p(rp)
    beta = rp_sqnorm/rp_sqnorm_old
    rp_sqnorm_old = rp_sqnorm

    pp = rp + beta*pp

    if rp_sqnorm <= bp_sqnorm_sqtol: flag = True

  return x, rp_sqnorm/bp_sqnorm, exceptFlag

def test_main():
  print('%% testing cgls %%')
  A = np.random.rand(5,3)
  b = np.random.rand(5,1)

  x_star = np.linalg.lstsq(A, b)[0]
  x, ratio, exceptFlag = cgls(A, b)

  e = x_star - x
  print('results:')
  print('- error:', e)
  print('- ratio:', ratio)
  print('- eFlag:', exceptFlag)
  print('%% testend cgls %%')

if __name__ == '__main__':
  test_main()


from Plugin import Plugin
import Settings
class Help(Plugin):

    def on_message(self, message):
        super(Help, self).on_message(message)
        help_triggers = [self.get_name(), self.get_name() + '@' + Settings.username]
        if(message.text[1:] in help_triggers):
            self.bot.send_message(self.cid, self.build_help())
            return
        if(len(self.words) >= 2):
            query = self.words[1]
            for x in Settings.plugins:
                #print('testing [' + query + '] against [' + x.get_name() + ']')
                if(query == x.get_name()):
                    self.bot.send_message(self.cid, Settings.command_char + x.get_help())
                    return
            self.bot.send_message(self.cid, '[' + self.words[1] + '] not found.')

    def get_help(self):
        return "help <plugin>\nReturns help for plugin."
    def extract_help(self, plugin):
        return plugin.get_help()[:plugin.get_help().index('\n')]
    def build_help(self):
        result = []
        for x in Settings.plugins:
            help_string = self.extract_help(x)
            if(x.need_admin):
                help_string = help_string + '[*]'
            result.append(Settings.command_char + help_string)
        l = str(len(Settings.plugins))
        response = 'Detected Plugins: ' + l + '\n' + '\n'.join(result)
        return response + '\n[*] = Admins Only'