# -*- coding: utf-8 -*-

import os
import shutil
from datetime import datetime

from vilya.libs.signals import (
    gist_created_signal, gist_forked_signal, gist_updated_signal)
from vilya.libs.store import store
from vilya.libs import gyt
from vilya.libs.permdir import get_repo_root
from vilya.models.git import GitRepo
from vilya.models.ngit.repo import GistRepo
from vilya.models.user import User
from vilya.models.gist_comment import GistComment
from vilya.models.gist_star import GistStar

from vilya.config import DOMAIN

PAGE_LIMIT = 10
DATETIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
GIST_FILE_RAW = DOMAIN + '/gist/%s/raw/master/%s'

PRIVILEGE_PUBLIC = 1
PRIVILEGE_SECRET = 0

SORTS = ('created', 'updated')
DIRECTIONS = ('desc', 'asc')

GIST_NAME = 'gist:%s'

def init_gist_folder():
    GISTS_PATH = os.path.join(get_repo_root(), 'gist')
    if not os.path.exists(GISTS_PATH):
        os.makedirs(GISTS_PATH)

init_gist_folder()

class Gist(object):

    ANONYMOUS = 'anonymous'

    def __init__(self, id, name, description, owner_id, is_public,
                 fork_from, created_at, updated_at):
        self.id = id
        self.name = name.decode('utf-8') or GIST_NAME % id
        self.description = description.decode('utf-8')
        self.owner_id = owner_id
        self.is_public = is_public
        self.fork_from = fork_from
        self.created_at = created_at
        self.updated_at = updated_at

    def __repr__(self):
        return '<Gist name:%s, owner:%s>' % (self.name, self.owner_id)

    def __eq__(self, target):
        return self.id == target.id

    @property
    def repo_root_path(self):
        return get_repo_root()

    def as_dict(self):
        data = {
            'type': 'gist',
            'url': self.url,
            'description': self.description,
            'author': self.owner.name,
        }
        data['time'] = self.created_at.strftime('%Y-%m-%dT%H:%M:%S')
        if self.updated_at:
            data['time'] = self.updated_at.strftime('%Y-%m-%dT%H:%M:%S')
        content = []
        data['content'] = {}
        for path in self.files:
            path = path.encode('utf8')
            blob = self.repo.get_file(path, 'HEAD')
            src = blob if blob else ''
            content.append(path)
            content.append(src)
        data['content'] = '\n'.join(content)
        return data

    @property
    def full_name(self):
        return '%s/%s' % (self.owner_id, self.name)

    # TODO: remove this, please use gist.repo_path
    @property
    def git_real_path(self):
        return os.path.join(self.repo_root_path, 'gist/%s.git' % self.id)

    # TODO: remove this, please use gist.repo
    @property
    def git(self):
        try:
            repo = GitRepo(self.git_real_path)
        except gyt.GytRepoNotInited:
            repo = None
        return repo

    @property
    def git_path(self):
        return 'gist/%s.git' % self.id

    @property
    def git_url(self):
        return '%s/%s' % (DOMAIN, self.git_path)

    @property
    def url(self):
        return '%s/gist/%s/%s' % (DOMAIN, self.owner_id, self.id)

    @property
    def download_url(self):
        return self.url + '/download'

    @property
    def embed_url(self):
        return self.url + '.js'

    @property
    def n_star(self):
        rs = store.execute(
            "select count(1) from gist_stars where gist_id=%s", (self.id,))
        return rs[0][0]

    @property
    def stars(self):
        rs = store.execute(
            "select user_id from gist_stars where gist_id=%s", (self.id,))
        return [User(user_id) for user_id, in rs]

    def star(self, user_id):
        if not GistStar.get_by_gist_and_user(self.id, user_id):
            GistStar.add(self.id, user_id)
        return True

    def unstar(self, user_id):
        gs = GistStar.get_by_gist_and_user(self.id, user_id)
        if gs:
            gs.delete()
        return True

    @property
    def n_fork(self):
        rs = store.execute(
            "select count(1) from gists where fork_from=%s", (self.id,))
        return rs[0][0]

    @property
    def forks(self):
        rs = store.execute(
            "select id, name, description, owner_id, is_public, fork_from, "
            "created_at, updated_at from gists where fork_from=%s", (self.id,))
        return [Gist(*r) for r in rs]

    @property
    def n_revision(self):
        if self.repo:
            return len(self.repo.get_commits('HEAD'))
        return 0

    @property
    def n_comments(self):
        rs = store.execute(
            "select count(1) from gist_comments where gist_id=%s", (self.id,))
        return rs[0][0]

    @property
    def n_files(self):
        return len(self.files)

    @property
    def files(self):
        files = []
        for sha, name in self.repo.get_files():
            files.append(name)
        #if not self.repo.empty:
        #    files = [item['path'] for item in self.git._list_tree('HEAD', '')]
        return files

    # TODO: remove this later
    @property
    def list_sha1_with_files(self):
        files = self.repo.get_files()
        return files
        #return self.git.list_sha1_with_files('HEAD')

    @property
    def forked_from(self):
        return Gist.get(self.fork_from)

    def get_revlist_with_renames(self, max_count=3, skip=0, rev='HEAD',
                                 path='', author=None):
        revlist = self.repo.get_commits(rev,
                                        max_count=max_count,
                                        skip=skip,
                                        path=path,
                                        author=author)
        return revlist

    # TODO: remove this, please use gist.fork_repo
    def clone_git(self, to_path):
        git_path = os.path.join(self.repo_root_path, self.git_path)
        to_path = os.path.join(self.repo_root_path, to_path)
        rep = gyt.repo(git_path)
        rep.clone(to_path)

    @property
    def owner(self):
        return User(self.owner_id)

    @property
    def comments(self):
        return GistComment.gets_by_gist_id(self.id)

    @classmethod
    def get(cls, id):
        rs = store.execute(
            "select id, name, description, owner_id, is_public, fork_from, "
            "created_at, updated_at from gists where id=%s", (id,))
        return rs and cls(*rs[0]) or None

    @classmethod
    def gets(cls, ids):
        return [cls.get(id) for id in ids]

    @classmethod
    def add(cls, description, owner_id, is_public, gist_names=[],
            gist_contents=[], fork_from=None):
        now = datetime.now()
        if fork_from:
            name = cls.get(fork_from).name
            id = store.execute(
                "insert into gists "
                "(`name`, `description`, `owner_id`, `created_at`, `fork_from`) "  # noqa
                "values (%s, %s, %s, %s, %s)",
                (name, description, owner_id, now, fork_from))
            store.commit()
            gist = cls.get(id)
            fork_from = cls.get(fork_from)
            fork_from.fork_repo(gist)
            gist_forked_signal.send(gist, gist_id=gist.id)
        else:
            name = cls._get_name(names=gist_names)
            id = store.execute(
                "insert into gists "
                "(`name`, `description`, `owner_id`, `is_public`, `created_at`) "  # noqa
                "values (%s, %s, %s, %s, %s)",
                (name, description, owner_id, is_public, now))
            store.commit()
            gist = cls.get(id)
            gist.create_repo()
            gist._commit_all_files(gist_names, gist_contents, create=True)
            gist_created_signal.send(gist, gist_id=gist.id)
        return gist

    def update(self, description, gist_names=[], gist_contents=[],
               gist_oids=[]):
        name = self._get_name(gist_names)
        store.execute(
            "update gists set name=%s, description=%s, updated_at=%s where id=%s",  # noqa
            (name, description, datetime.now(), self.id))
        store.commit()
        self._commit_all_files(gist_names, gist_contents, gist_oids)
        gist_updated_signal.send(self, gist_id=self.id)

    def _commit_all_files(self, gist_names, gist_contents, gist_oids=[],
                          create=False):
        _gets = lambda x: x if isinstance(x, list) else [x]
        gist_names = _gets(gist_names)
        gist_contents = _gets(gist_contents)
        gist_oids = _gets(gist_oids) or [''] * len(gist_names)

        if create and gist_names and not gist_names[0]:
            gist_names = gist_names * len(gist_contents)
            gist_oids = [''] * len(gist_contents)

        self.repo.commit_all_files(gist_names, gist_contents,
                                   gist_oids, User(self.owner_id))

    @classmethod
    def _get_name(cls, names=[]):
        if not isinstance(names, list):
            names = [names]
        name = names and names[0]
        if name and not name.startswith('gistfile'):
            return name
        return ''

    def fork(self, user_id):
        return Gist.add(
            self.description, user_id, self.is_public, fork_from=self.id)

    @classmethod
    def gets_by_owner(cls, owner_id, is_self=False, start=0, limit=10,
                      sort='created', direction='desc'):
        assert sort in SORTS
        assert direction in DIRECTIONS
        sql = ("select id, name, description, owner_id, is_public, fork_from, "
               "created_at, updated_at from gists where owner_id=%s ")
        if not is_self:
            sql += " and is_public=1 "
        sql += "order by %s %s limit %s, %s" % (
            sort + '_at', direction, start, limit)
        rs = store.execute(sql, owner_id)
        return [cls(*r) for r in rs]

    @classmethod
    def forks_by_user(cls, owner_id, start=0, limit=10, sort='created',
                      direction='desc'):
        assert sort in SORTS
        assert direction in DIRECTIONS
        sortby = "order by %s_at %s " % (sort, direction)
        rs = store.execute(
            "select id, name, description, owner_id, is_public, fork_from, "
            "created_at, updated_at from gists where owner_id=%s and "
            "fork_from!=0 " + sortby + "limit %s, %s",
            (owner_id, start, limit))
        return [cls(*r) for r in rs]

    @classmethod
    def stars_by_user(cls, owner_id, start=0, limit=10):
        rs = store.execute(
            "select gist_id from gist_stars "
            "where user_id=%s order by id desc limit %s, %s",
            (owner_id, start, limit))
        return filter(None, [cls.get(r) for r, in rs])

    @classmethod
    def publics_by_user(cls, owner_id, start=0, limit=10, sort='created',
                        direction='desc'):
        return cls._privilege_by_user(
            owner_id, start=start, limit=limit, privilege=1,
            sort=sort, direction=direction)

    @classmethod
    def secrets_by_user(cls, owner_id, start=0, limit=10, sort='created',
                        direction='desc'):
        return cls._privilege_by_user(
            owner_id, start=start, limit=limit, privilege=0,
            sort=sort, direction=direction)

    @classmethod
    def _privilege_by_user(cls, owner_id, start=0, limit=10, privilege=1,
                           sort='created', direction='desc'):
        assert sort in SORTS
        assert direction in DIRECTIONS
        sortby = "order by %s_at %s " % (sort, direction)
        rs = store.execute(
            "select id, name, description, owner_id, is_public, fork_from, "
            "created_at, updated_at from gists where owner_id=%s and "
            "is_public=%s " + sortby + "limit %s, %s",
            (owner_id, privilege, start, limit))
        return [cls(*r) for r in rs]

    @classmethod
    def count_user_all(self, owner_id, is_self=False):
        if is_self:
            rs = store.execute(
                "select count(1) from gists where owner_id=%s", (owner_id,))
        else:
            rs = store.execute(
                "select count(1) from gists where owner_id=%s "
                "and is_public=1", (owner_id,))
        return rs[0][0]

    @classmethod
    def count_user_fork(self, owner_id):
        rs = store.execute(
            "select count(1) from gists where owner_id=%s and "
            "fork_from!=0", (owner_id,))
        return rs[0][0]

    @classmethod
    def count_user_star(self, owner_id):
        rs = store.execute(
            "select count(1) from gist_stars where user_id=%s", owner_id)
        return rs[0][0]

    @classmethod
    def count_public_by_user(cls, owner_id):
        return cls._count_privilege_by_user(
            owner_id, privilege=PRIVILEGE_PUBLIC)

    @classmethod
    def count_secret_by_user(cls, owner_id):
        return cls._count_privilege_by_user(
            owner_id, privilege=PRIVILEGE_SECRET)

    @classmethod
    def _count_privilege_by_user(cls, owner_id, privilege=PRIVILEGE_PUBLIC):
        rs = store.execute(
            "select count(1) from gists where owner_id=%s and is_public=%s",
            (owner_id, privilege))
        return rs[0][0]

    def delete(self):
        shutil.rmtree(self.git_real_path, ignore_errors=True)
        store.execute("delete from gists where id=%s", (self.id,))
        store.execute("delete from gist_stars where gist_id=%s", (self.id,))
        store.execute("delete from gist_comments where gist_id=%s", (self.id,))
        store.commit()

    def is_starred(self, user_id):
        rs = store.execute(
            "select id from gist_stars where gist_id=%s and user_id=%s",
            (self.id, user_id))
        return True if rs else False

    @classmethod
    def discover(cls, name, sort='created', direction='desc', start=0,
                 limit=5):
        assert sort in SORTS
        assert direction in DIRECTIONS
        sortby = "order by %s_at %s " % (sort, direction)
        sort = '%s_at' % sort
        reverse = direction == 'desc'
        if name == 'forked':
            rs = store.execute("select distinct(fork_from) from gists "
                               "where fork_from!=0 and is_public=1 " +
                               sortby + "limit %s, %s",
                               (start, limit))
            return [cls.get(r) for r, in rs]
        elif name == 'starred':
            rs = store.execute("select distinct(gist_id) from gist_stars "
                               "order by created_at " +
                               direction + " limit %s, %s",
                               (start, limit))
            gists = filter(None, [cls.get(r) for r, in rs])
            return sorted(gists, key=lambda g: getattr(g, sort),
                          reverse=reverse)
        else:
            rs = store.execute(
                "select id, name, description, owner_id, is_public, "
                "fork_from, created_at, updated_at from gists where "
                "is_public=1 " + sortby + "limit %s, %s",
                (start, limit))
            return [cls(*r) for r in rs]

    @property
    def repo(self):
        return GistRepo(self)

    @property
    def repo_path(self):
        return os.path.join(self.repo_root_path, 'gist/%s.git' % self.id)

    def create_repo(self):
        GistRepo.init(self)

    def fork_repo(self, gist):
        self.repo.clone(gist)

    def get_file(self, path, rev='master'):
        blob = self.repo.get_file(rev, path)
        if not blob:
            # FIXME: value convention
            return False
        return blob.data

    @property
    def updated_time(self):
        commit = self.repo.get_last_commit('HEAD')
        if not commit:
            return 0
        return int(commit.author_timestamp)

def fork_detail(gist):
    return dict(user=user_detail(gist.owner),
                url=gist.url,
                created_at=gist.created_at.strftime(DATETIME_FORMAT))

def user_detail(user):
    return dict(login=user.name, id=user.name, avatar_url=user.avatar_url,
                url=user.url)

def gist_detail(gist, include_forks=False, include_history=False):
    files = {
        f: dict(filename=f, raw_url=GIST_FILE_RAW % (gist.id, f))
        for f in gist.files
    }
    ret = dict(url=gist.url,
               id=gist.id,
               description=gist.description,
               public=bool(gist.is_public),
               user=user_detail(gist.owner),
               files=files,
               comments=gist.n_comments,
               html_url=gist.url,
               git_pull_url=gist.git_url,
               git_push_url=gist.git_url,
               created_at=gist.created_at.strftime(DATETIME_FORMAT))

    if include_forks:
        ret.update(dict(forks=[fork_detail(f) for f in gist.forks]))

    if include_history:
        # TODO
        pass

    return ret


import io
import os
import re
import sys
import argparse
# if re.match("^\d+?\.\d+?$", element) is None:
#     print "Not float"

class word():
    """docstring for word"""
    def __init__(self, description, vertices):# lower_left, lower_right, upper_right, upper_left):
        self.description = description
        self.lleft = vertices[0]
        self.lright = vertices[1]
        self.uright = vertices[2]
        self.uleft = vertices[3]

def detect_text(path):
    """Detects text in the file."""
    from google.cloud import vision
    client = vision.ImageAnnotatorClient()

    with io.open(path, 'rb') as image_file:
        content = image_file.read()

    image = vision.types.Image(content=content)

    response = client.text_detection(image=image)
    texts = response.text_annotations
    # print('Texts:')

    word_list = []
    i = 0

    for text in texts:
        # print('\n"{}"'.format(text.description))
        if i == 0:
            i += 1
        else:
            vertices = []
            for vertex in text.bounding_poly.vertices:
                v = (vertex.x, vertex.y)
                vertices.append(v)
            # vertices = (['({},{})'.format(vertex.x, vertex.y)
            #             for vertex in text.bounding_poly.vertices])

            # string = 'bounds: {}'.format(','.join(vertices))
            # print(string)

            new_word = word(text.description, vertices)
            word_list.append(new_word)
    return word_list

def check_close(curr_y_coord, y_coords_keys):
    # if len(y_coords_keys) == 0:
    #     return curr_y_coord
    for coord in y_coords_keys:
        # print('Coord: ', coord)
        # print('Current Coord: ', curr_y_coord)
        if abs(coord - curr_y_coord) <= 5:
            return coord
        # else:
        #     return 0
    return 0

def find_same_line(word_list):
    which_line = {}
    for w in word_list:
        # print(w.description)
        xD = check_close(w.lleft[1], which_line.keys())
        # print(w.lleft[1])
        if xD:
            # print(xD)
            # print('fffffff')
            which_line[xD] = which_line[xD] + " " + w.description
        else:
            # print(int(w.lleft[1]))
            # print('truuu')
            which_line[w.lleft[1]] = w.description
    return which_line

def extract_item_price(line_dic):
    new_dic = {}
    quantity_dic = {}
    for k,v in line_dic.items():
        split_value = v.split(" ")
        last_item = split_value[len(split_value) - 1]
        last_item = re.sub('[^0-9\.]', '', last_item)
        if re.match("^\d+\.\d+$", last_item):
            first_item = split_value[0]
            if re.match("^\d+$", first_item):
                new_key = " ".join(split_value[:-1])
                new_key = new_key.lstrip('0123456789.- ')
                quantity_dic[new_key] = int(first_item)
                new_dic[new_key] = float(last_item)
            else:
                new_key = " ".join(split_value[:-1])
                quantity_dic[new_key] = 1
                new_dic[new_key] = float(last_item)
    return new_dic

        # last_item = split_value[len(split_value) - 1]
        # last_item = re.sub('[^0-9\.]', '', last_item)
        #     if re.match("^\d+$", first_item):
        #         new_key = " ".join(split_value[:-1])
        #         quantity_dic[new_key] = int(first_item)
        #         new_key.lstrip('0123456789.- ')

        #     new_dic[new_key] = float(last_item)

special_words = ['subtotal', 'sub total', 'total', 'tax', 'gratuity', 'tip']
special_words2 = ['subtotal', 'sub total', 'total']
def checker(lst, word):
    for elem in lst:
        if elem in re.sub("[^a-zA-Z]", "", word).lower():
            return True
    return False
    # return re.sub("[^a-zA-Z]", "", word).lower() in lst

def mainer(filepath):
    w_list = detect_text(filepath)
    tester = find_same_line(w_list)
    temp_dic = extract_item_price(tester)
    item_price = {}
    for item, price in temp_dic.items():
        if not checker(special_words2, item):
            item_price[item] = price
    return item_price
# if __name__ == '__main__':
    # parser = argparse.ArgumentParser()
    # parser.add_argument("--file", "-f", type=str, required=True)
    # args = parser.parse_args()
    # w_list = detect_text(args.file)
    # # './inputs/easy/easy1.jpg'
    # tester = find_same_line(w_list)
    # # print(tester)
    # item_price = extract_item_price(tester)
    # print(item_price)


with open("2.txt") as file:
    intcode=file.read().split(",")
for i in range(len(intcode)):
    intcode[i]=int(intcode[i])
intcode[1]=12   # given
intcode[2]=2

def Intcode(intcode):
    i=0
    while True:
        number=intcode[i]
        if number == 1:
            source1=intcode[i+1]
            source2=intcode[i+2]
            n1=intcode[source1]
            n2=intcode[source2]
            target=intcode[i+3]
            intcode[target]=n1+n2
            i+=4
        elif number == 2:
            source1=intcode[i+1]
            source2=intcode[i+2]
            n1=intcode[source1]
            n2=intcode[source2]
            target=intcode[i+3]
            intcode[target]=n1*n2
            i+=4
        elif number == 99:
            return intcode[0]

print(Intcode(intcode))       # answer part 1: 3306701

# part 2: find noun and verb s.t. intcode[0] = 19690720
with open("2.txt") as file:
    intcode2=file.read().split(",")
for i in range(len(intcode2)):
    intcode2[i]=int(intcode2[i])

for i in range(0,100):
    for j in range(0,100):
        copy=intcode2.copy()
        copy[1]=i
        copy[2]=j
        if Intcode(copy) == 19690720:
            noun=i
            verb=j
            break
print(100*noun + verb)      # answer part 2: 7621


f = open("text.in", 'r')
s = f.read()

f.close()
nrtotal = 0
d={}
for c in s:
    if 97 <= ord(c) <= 122:
        nrtotal += 1
        if c in d:
            d[c] +=1
        else:
            d[c] = 1
    elif 65<= ord(c)<= 90:
        nrtotal += 1
        n = ord(c)+32
        if n in d:
            d[chr(n)] += 1
        else:
            d[chr(n)] = 1

for x in d:
    d[x] = d[x]/nrtotal
d = {x: v for x, v in sorted(d.items(), key=lambda item: item[1], reverse=True)}
g = open("text.out", "w")
for i in d:
    g.write(f"{i}: {d[i]: .3f}")
    g.write("\n")
g.close()


from bs4 import BeautifulSoup as bs
try:
    import cld3
except:
    pass

# from googletrans import Translator
# from google_trans_new import google_translator

from .dictWords import *

def find_els_contains_word(web_comp , word: str): # changing //*[contains(text(),"Cookies")] to //*[text()[contains(.,"Cookies")]]
    return web_comp.find_elements_by_xpath("// *[text()[contains(., '"+word.capitalize()+"') or contains(., '"+word.lower()+"') or contains(., '"+word.upper()+"')]]")

def find_variations_of_word(word: str):
    return [word.title(), word.lower(), word.upper()]

def find_variations_of_words(words: list[str]):
    all = []
    for word in words:
        if "contains(.," in word:
            continue
        all.extend(find_variations_of_word(word))
    return all

def concat_with_or(words: list[str], variation=True):
    temp_srt = ''
    if variation:
        temp_words = find_variations_of_words(words)
    else:
        temp_words = words
    for word in temp_words:
        if 'contains(.,' in word:
            if temp_srt:
                temp_srt = temp_srt + ' or (' + word + ')'
            else:
                temp_srt = temp_srt + '(' + word + ')'
            continue
        if temp_srt:
            temp_srt = temp_srt + ' or contains(., "' + word + '")'
        else:
            temp_srt = temp_srt + 'contains(., "' + word + '")'
    return temp_srt

def concat_with_and(words: list[str]):
    temp_srt = ''
    for word in words:
        if 'contains(.,' in word:
            if temp_srt:
                temp_srt = temp_srt + ' and (' + word + ')'
            else:
                temp_srt = temp_srt + '(' + word + ')'
            continue
        if temp_srt:
            temp_srt = temp_srt + ' and contains(., "' + word + '")'
        else:
            temp_srt = temp_srt + 'contains(., "' + word + '")'
    return temp_srt

def to_xpath_text(string: str):
    string = './/*[text()[' + string + ']]'
    return string

def to_xpath_class(string: str):
    string = './/*[@class[' + string + ']]'
    return string

def to_xpath_id(string: str):
    string = './/*[@id[' + string + ']]'
    return string

def to_xpathtest(string: str):
    string = '//*[text()[' + string + ']]'
    return string

def remove_classes(html: str): # remove all the classes from the tags in a given HTML string (used for rendering banner without access to corresponding CSS files.
    soup = bs(html, features="lxml")
    tags = soup.recursiveChildGenerator()
    for tag in tags:
        try:
            # tag.attrs = dict()
            del tag.attrs['class']
        except (AttributeError, KeyError) as ex:
            # print("No such key: '%s'" % ex.__str__())
            pass
    return soup.prettify()

def prettify(html: str):
    soup = bs(html, features="lxml")  # make BeautifulSoup
    return soup.prettify()  # prettify the html

def detect_lang(text: str):
    try:
        detected_obj = cld3.get_language(text)
    except:
        return None
    if detected_obj:
        return detected_obj.language
    else:
        return None

def extend_all_words(word_list, lang):
    all_words = [words["en"][word] for word in word_list]
    if lang is not None and lang in words:
        all_words.extend([words[lang][word] for word in word_list])
    return all_words


#!/usr/bin/env python

# Adapted from ascii.py of Mahesh Venkitachalam

# Python code to convert an image to ASCII image.
import sys, random, argparse
import array, fcntl, termios
import numpy as np
import math

from PIL import Image, ImageDraw, ImageFont, ImageFilter, ImageColor

try:
    import curses
except ImportError:
    print('curses is required!')
    exit(1)

COLORS = {
    "BLACK" : curses.COLOR_BLACK,
    "BLUE" : curses.COLOR_BLUE,
    "CYAN" : curses.COLOR_CYAN,
    "GREEN" : curses.COLOR_GREEN,
    "MAGENTA" : curses.COLOR_MAGENTA,
    "RED" : curses.COLOR_RED,
    "WHITE" : curses.COLOR_WHITE,
    "YELLOW" : curses.COLOR_YELLOW,
    "DEFAULT": -1
}

# gray scale level values from:
# http://paulbourke.net/dataformats/asciiart/

# 10 levels of gray
GSCALE = '@%#*+=-:. '

def getAverageL(image):
    """
    Given PIL Image, return average value of grayscale value
    """
    # get image as numpy array
    im = np.array(image)

    # get shape
    w,h = im.shape

    # get average
    return np.average(im.reshape(w*h))

def covertImageToAscii(image, rows, cols):
    """
    Given Image and dims (rows, cols) returns an m*n list of Images
    """
    # open image and convert to grayscale
    image = image.convert('L')

    # store dimensions
    width, height = image.size

    pixel_per_row = height/rows
    pixel_per_col = width/cols

    # ascii image is a list of character strings
    aimg = []

    # generate list of dimensions
    for j in range(rows):
        y1 = int(j*pixel_per_row)
        y2 = int((j+1)*pixel_per_row)

        # correct last tile
        if j == rows-1:
            y2 = height

        # append an empty string
        aimg.append("")

        for i in range(cols):

            # crop image to tile
            x1 = int(i*pixel_per_col)
            x2 = int((i+1)*pixel_per_col)

            # correct last tile
            if i == cols-1:
                x2 = width

            # crop image to extract tile
            img = image.crop((x1, y1, x2, y2))

            # get average luminance
            avg = int(getAverageL(img))

            # look up ascii char
            gsval = GSCALE[int((avg*9)/255)]

            # append ascii char to string
            aimg[j] += gsval

    # return txt image
    return aimg

# main() function
def main(stdscr):
    # create parser
    descStr = "This program shows a letter on full terminal screen."
    parser = argparse.ArgumentParser(description=descStr)

    # add expected arguments
    parser.add_argument('--letter', dest='letter', required=False, default='0')
    parser.add_argument('--font-size', dest='fontSize', required=False, default=None)
    parser.add_argument('--fore-color', dest='foreColor', required=False, default='red')
    parser.add_argument('--back-color', dest='backColor', required=False, default='default')

    # parse args
    args = parser.parse_args()

    # initialize curses environment
    curses.curs_set(0)
    curses.use_default_colors()
    curses.init_pair(9, COLORS[args.foreColor.upper()], COLORS[args.backColor.upper()])
    stdscr.bkgd(curses.color_pair(9))
    curses.start_color()

    # Your application can determine the size of the screen by using the curses.LINES
    # and curses.COLS variables to obtain the y and x sizes.
    # Legal coordinates will then extend from (0,0) to (curses.LINES - 1, curses.COLS - 1).
    # Legal coordinates will be from (0,0) to (cols-1, rows-1)
    rows, cols = stdscr.getmaxyx()

    buf = array.array('H', [0,0,0,0])
    fcntl.ioctl(1, termios.TIOCGWINSZ, buf)
    prow, pcol, pxx, pxy = buf
    fontsize = int(min(pxx, pxy) * 0.90)

    if args.fontSize is not None:
        fontsize = int(args.fontSize)

    if prow != rows or pcol != cols:
        print(f"inconsistant row and cols {rows}, {cols} -- {prow}, {pcol}")

    image = Image.new('RGB', (pxx, pxy), (255, 255, 255))
    font = ImageFont.truetype('./Arial Black.ttf', fontsize)
    draw = ImageDraw.Draw(image)
    x, y = pxx / 2, pxy / 2
    draw.text((x, y), args.letter, font=font, fill=ImageColor.getrgb('black'), anchor='mm')

    # convert image to ascii txt
    aimg = covertImageToAscii(image, rows, cols)

    # write to screen
    for idx, row in enumerate(aimg):
        stdscr.addstr(idx, 0, row[0:cols-1])

    stdscr.border()
    stdscr.refresh()
    while stdscr.getkey() != 'q':
        pass

# call main
if __name__ == '__main__':
    curses.wrapper(main)


from rest_framework import serializers , status
from library.api_response import ApiResponse

ID = 5

def input_validation(value):

    if float(value) >= 0 and float(value) <= 20:
        return True

    api_response = ApiResponse()
    response = api_response.set_data("errors", "Invalid PH Sensor Value").get()
    raise serializers.ValidationError(detail=response)


"""
You will be given a list of integers, arr, and a single integer k. You must
create an array of length k from elements of arr such that its unfairness is
minimized. Call that array arr'. Unfairness of an array is calculated as
        max(arr')-min(arr')
Where:
- max denotes the largest integer in arr'
- min denotes the smallest integer in arr'
Example
    arr=[1,4,7,2]
    k=2
    Pick any two elements, say arr'=[4,7].
        unfairness=max(4,7)-min(4,7)=7-4=3
    Testing for all pairs, the solution [1,2] provides the minimum unfairness.
    Note: Integers in arr may not be unique.
Function Description
    Complete the maxMin function in the editor below.
    maxMin has the following parameter(s):
        int k: the number of elements to select
        int arr[n]:: an array of integers
Returns
    int: the minimum possible unfairness
Input Format
    The first line contains an integer n, the number of elements in array arr.
    The second line contains an integer k.
    Each of the next n lines contains an integer arr[i] where 0<=i<n.
Constraints
    2<=n<=10^5
    2<=k<=n
    0<=arr[i]<=10^9
Sample Input 0
    7
    3
    10
    100
    300
    200
    1000
    20
    30
Sample Output 0
    20
Explanation 0
    Here k=3; selecting the 3 integers 10,20,30, unfairness equals
        max(10,20,30) - min(10,20,30) = 30 - 10 = 20
Sample Input 1
    10
    4
    1
    2
    3
    4
    10
    20
    30
    40
    100
    200
Sample Output 1
    3
Explanation 1
    Here k=4; selecting the 4 integers 1,2,3,4, unfairness equals
        max(1,2,3,4) - min(1,2,3,4) = 4 - 1 = 3
Sample Input 2
    5
    2
    1
    2
    1
    2
    1
Sample Output 2
    0
Explanation 2
    Here k=2. arr'=[2,2] or arr'=[1,1] give the minimum unfairness of 0.
"""

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'maxMin' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER k
#  2. INTEGER_ARRAY arr
#

def maxMin(k, arr):
    # Write your code here
    arr.sort()
    return min(arr[i+k-1]-arr[i] for i in range(len(arr)-k+1))
    """
    ans=1_000_000_000

    arr.sort()
    for i, val in enumerate(arr[:len(arr)-1-k]):
        ans=min(ans, arr[i+k-1] - arr[i])

    return ans
    """
    """
    #to slow
    arr.sort()
    arrPrime = []
    ans = 9999999
    for j in range(0, len(arr)-k):
        arrPrime = []
        for i in range(j,j+k):
            arrPrime.append(arr[i])
        if( ans > (max(arrPrime) - min(arrPrime))):
            ans = (max(arrPrime) - min(arrPrime))
    return ans
    """

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    k = int(input().strip())

    arr = []

    for _ in range(n):
        arr_item = int(input().strip())
        arr.append(arr_item)

    result = maxMin(k, arr)

    fptr.write(str(result) + '\n')

    fptr.close()


from threading import Thread
from Api import sms, call
from time import sleep
from inspect import getmembers, isfunction
from os import system, name

SMS_SERVICES = list(i[0] for i in getmembers(sms, isfunction))
CALL_SERVICES = list(i[0] for i in getmembers(call, isfunction))

def printLow(Str):
    for char in Str:
        print(char, end='', flush=True)
        sleep(0.01)

def bombing(phone, count):
    x = 0
    phone = f"+98{phone[1:]}"
    for j in range(count):
        for k in range(len(SMS_SERVICES)):
            Thread(target=getattr(sms, SMS_SERVICES[k]), args=[phone]).start()
        if (j !=0) and (j % 5) == 0:
            Thread(target=getattr(call, CALL_SERVICES[x]), args=[phone]).start()
            x += 1
            if x > len(CALL_SERVICES) - 1:
            	x = 0
        print(f"\033[1m\033[96mRound \033[1;31m{j+1} \033[1m\033[96mCompleted")
        sleep(0.2)
    printLow("\033[32;1m[\033[1;33mFinished\033[32;1m]")

if __name__ == "__main__":
    printLow(f"""\033[32;1m[+] \033[1;33mSMS Api's: \033[32;1m{len(SMS_SERVICES)}\n\033[32;1m[+] \033[1;33mCALL Api's: \033[32;1m{len(CALL_SERVICES)}\n\033[32;1m[+] \033[1;33mDeveloper: \033[32;1m@ExpireSourc""")
    num = input('\n\n\033[32;1m[$] \033[1m\033[96mEnter Phone Number\n\033[1;33m  Ex:09190000000\n \033[1;31m-> \033[32;1m')
    yy = int(input("\n\033[32;1m[$] \033[1;33mEnter The Count of Round of Bombing\n\033[1;31m-> \033[32;1m"))
    system('clear' if name == 'posix' else 'cls')
    printLow("\033[32;1m[+]\033[1;33m Phone Number:\033[1m\033[96m {}\n\033[32;1m[+]\033[1;33m Rounds:\033[1m\033[96m {}\n\n".format(num,yy))
    printLow("\033[32;1m[\033[1;31mStart\033[32;1m]\n")
    bombing(phone=num,count=yy)


# to check whether the give string as a repeated letters if so print the first repeated letter
def rep_string_check (name):
    d = {}
    for x in name:
        if x not in d.keys():
           # print (d.items())
           # print(x)
            d[x] = 1
        else:
            return x
    return "no"

print(rep_string_check("baba"))


import ast
import re

import numpy as np
import scipy.linalg

from src.calculate import Calculate

__author__ = "Khashayar Ghamati"
__email__ = "khashayarghamati@gmail.com"

class GaussLU(object):

    def getEquation(self):
        n = int(input("insert number of row: "))
        m = int(input("insert number of column: "))

        if n != m:
            print("Your Matrix is not square !")
        else:
            self.value = []
            self.matrix = []

            for i in range(n):
                equation = input(f"insert vector {i+1} :")
                vector = self.convertStringToList(list=equation)

                if len(self.matrix) == 0:
                    self.matrix = np.array(vector)
                else:
                    self.matrix = np.vstack([self.matrix, vector])

            self.value = self.convertStringToList(input(f"insert values :"))

            isMatrixValid, msg = self._isMatrixValid()
            if isMatrixValid:
                gwp = Calculate(matrix=self.matrix, n=n)
                P, L, U = scipy.linalg.lu(self.matrix)

                print(f"\nYour matrix is: \n {self.matrix}")
                print(f"\nP is: \n {P}")
                print(f"\nL is: \n {L}")
                print(f"\nU is: \n {U}")

                gwp.getLU()
                solution = gwp.getSolution(self.value)
                print(f"\nSolution is: \n {solution}")

            else:
                print(msg)

    def _isEquationValid(self, equation):

        if '=' not in equation:
            return "Your equation must equel to a scaler"
        elif '+' not in equation:
            return "Your equation is not valid"

        return True

    def convertStringToList(self, list):
        return ast.literal_eval(list)

    def _parseEquation(self, equation):
        elements = equation.split('+')
        value = int(re.search(r'-?\d+', equation.split('=')[1]).group())

        vector = []
        for idx, element in enumerate(elements):
            vector.append(int(re.search(r'-?\d+', element).group()))

        return vector, value

    def _isMatrixValid(self):

        if np.linalg.det(self.matrix) == 0:
            return False, "the determinant must not be zero"

        diagonal = self.matrix.diagonal()

        for idx, element in enumerate(diagonal):
            if idx != 0 and element == 0:
                return False, "the main diagonal must not contain zero"

        return True, "Your matrix is ready :)"

if __name__ == '__main__':
    lu = GaussLU()
    lu.getEquation()


class Solution(object):
    def countNegatives(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        output = 0
        for nums in grid:
            for num in nums:
                if num < 0:
                    output += 1
        return output


def eelarve(külalised):
    ruumirent = 55
    summa = külalised * 10 + ruumirent
    return summa
kindlad_tulijad = 0
vb_tulijad = 0

fail = open(input("Sisestage failinimi: "), "r")

for line in fail:
    for char in line:
        if char == "+":
            kindlad_tulijad += 1
        elif char == "?":
            vb_tulijad += 1

inim_kokku = kindlad_tulijad + vb_tulijad

print("Kutsutud on", inim_kokku, "inimest")
print(kindlad_tulijad, "inimest tuleb")
print("Maksimaalne eelarve:", eelarve(inim_kokku), "eurot")
print("Minimaalne eelarve:", eelarve(kindlad_tulijad), "eurot")


class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        """
        位运算 a[i] ^ b[i] 是无进位相加， a[i] & b[i]是进位
        carry得到每一位的进位
        a ^ b 得到无进位相加结果
        """
        carry = 0
        while b > 0:
            carry = a & b
            print('carry', carry)
            a = a ^ b
            b = carry << 1

        return a

if __name__ == '__main__':
    solution = Solution()
    print(solution.getSum(123, 45))


# Week 03 assignment
child_meal = float(input("What is the price of a child meal? "))
adult_meal = float(input("What is the price of an adult meal? "))
children = int(input("How many children are there? "))
adults = int(input("How many adults are there? "))
tax = float(input("What is the sales tax rate? "))

child_total = child_meal * children
adult_total = adult_meal * adults
subtotal = adult_total + child_total
print()
print(f"Subtotal: ${subtotal:.2f}")

# Week 04 assignment
sales_tax = tax * subtotal / 100
print(f"Sales Tax: ${sales_tax:.2f}")
# Added a gratuity input asking how much they want to tip.
tip = float(input("Gratuity: "))

total = subtotal + sales_tax + tip
print(f"Total: ${total:.2f}")

print()
payment = float(input("What is the payment amount? "))
amount = payment - total
print(f"Change: ${amount:.2f}")


import re
from datetime import datetime

import flask

def check_dates(startDate, endDate):
    start_date = None
    end_date = None
    if startDate:
        start_date = datetime.strptime(startDate, '%Y-%m-%d')
    if endDate:
        end_date = datetime.strptime(endDate, '%Y-%m-%d')

    if start_date and end_date:
        if end_date < start_date:
            return flask.make_response(flask.jsonify({'msg': 'startDate must be lower or equal than endDate'}), 401)

    return start_date, endDate

def sanitize_date(date, pattern=r'^\d{4}-\d{2}-\d{2}', as_date=False):
    temp_date = re.search(pattern=pattern, string=date).group(0)
    if as_date:
        temp_date = datetime.strptime(temp_date, "%Y-%m-%d")
    return temp_date


import json

class RocchioClassifier:

    def __init__(self):
        self.classes = {}
        self.similarities = {}

    def calculateCentroids(self, classes, beta, gamma):
        self.classes = classes
        for className in self.classes:
            totalDocs = self.classes[className]["totalDocs"]
            totalNonDocs = self.classes[className]["totalNonDocs"]
            for term in self.classes[className]["terms"].keys():
                calc1 = (beta / totalDocs) * self.classes[className]["terms"][term]["avgRel"]
                calc2 = (gamma / totalNonDocs) * self.classes[className]["terms"][term]["avgNonRel"]
                centroid = calc1 - calc2
                self.classes[className]["terms"][term]["centroid"] = centroid
        with open(f'results/RocchioCentroids_{beta}_{gamma}.json', 'w') as outfile:
            json.dump(self.classes, outfile, indent=4)

    def calculateSimilarities(self, testDocs, beta, gamma):
        for docId in testDocs:
            scale = []
            for className in self.classes:
                sumOfProducts = 0
                for termData in testDocs[docId]["terms"]:
                    if termData[0] in self.classes[className]["terms"]:
                        sumOfProducts += termData[1] * self.classes[className]["terms"][termData[0]]["centroid"]
                scale += [(className, sumOfProducts)]
            scale.sort(key=lambda tup: tup[1])
            scale.reverse()
            self.similarities[docId] = {
                                            "originalClass" : testDocs[docId]["class"],
                                            "assignedClass" : scale[0][0],
                                            "scale" : scale.copy()
                                       }
        with open(f'results/RocchioSimilarities_{beta}_{gamma}.json', 'w') as outfile:
            json.dump(self.similarities, outfile, indent=4)


import numpy as np
import pygame
from random import randint

class Apple(pygame.sprite.Sprite):
    def __init__(self, h = 20, w = 20):
        super().__init__()
        self.w = w
        self.h = h
        self.pos = pygame.math.Vector2(randint(self.w, 1000 - self.w),randint(self.h, 1000 - self.h))
        self.image, self.rect = self.load_image()

    def load_image(self):
        image = pygame.image.load('graphics/apple.png').convert_alpha()
        player_surf = pygame.transform.scale(image, (self.w, self.h))
        player_rect = player_surf.get_rect(center=(self.pos))
        player_image = player_surf

        return player_image, player_rect


# -*- coding: utf-8 -*-

import logging
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

import amayadori
import timeutil
import areamanager
import png
import giflib
import jmalib

class IndexPage(webapp.RequestHandler):
  def get(self, area):
    area         = int(area)
    radar_time   = amayadori.get_radar_time()
    nowcast_time = amayadori.get_nowcast_time()

    links = []
    for areainfo in areamanager.areas:
      if areainfo.code == area:
        links.append("" + areainfo.name + "")
      else:
        links.append("" + areainfo.name + "")

    values = {
      "area" : ("%03i" % area),
      "radar_time": radar_time.strftime("%Y%m%d%H%M"),
      "nowcast_time": nowcast_time.strftime("%Y%m%d%H%M"),
      "link" : "[ " + " | ".join(links) + " ]",
    }

    path = os.path.join(os.path.dirname(__file__), "views/image.html")
    html = template.render(path, values)
    self.response.out.write(html)

class WholeImage(webapp.RequestHandler):
  def get(self, area, time, ordinal):
    area    = int(area)
    time    = timeutil.yyyymmddhhnn_to_datetime(time)
    ordinal = int(ordinal)

    pngbin = amayadori.get_image(area, time, ordinal)

    self.response.headers["Content-Type"] = "image/png"
    self.response.out.write(pngbin)

class PartialReducedImage(webapp.RequestHandler):
  def get(self, area, time, ordinal, x, y):
    area    = int(area)
    time    = timeutil.yyyymmddhhnn_to_datetime(time)
    ordinal = int(ordinal)
    x, y    = int(x), int(y)

    sx = max([0, x - 20])
    sy = max([0, y - 20])
    dx = 41
    dy = 41

    pngbin = amayadori.get_image(area, time, ordinal)
    pngimg = png.Png8bitPalette.load(pngbin)

    gifimg = giflib.Image(dx, dy, 8)
    gifimg.allocate_color((192, 192, 192))

    # 色を単純化
    for yy in xrange(dy):
      for xx in xrange(dx):
        rgb1  = pngimg.get_color((sx + xx, sy + yy))
        rgb2  = jmalib.color_reduction(rgb1)
        index = gifimg.allocate_color(rgb2)
        gifimg.set_pixel((xx, yy), index)

    # ボーダーライン
    #border = gifimg.allocate_color((255, 255, 255))
    #for xx in xrange(dx):
    #  gifimg.set_pixel((xx, 0     ), border)
    #  gifimg.set_pixel((xx, dy - 1), border)
    #for yy in xrange(dy):
    #  gifimg.set_pixel((0     , yy), border)
    #  gifimg.set_pixel((dx - 1, yy), border)

    # センターマーク
    center = gifimg.allocate_color((32, 32, 32))
    for i in xrange(10):
      gifimg.set_pixel((i + 1,      dy / 2), center)
      gifimg.set_pixel((dx - i - 2, dy / 2), center)
      gifimg.set_pixel((dx / 2, i + 1     ), center)
      gifimg.set_pixel((dx / 2, dy - i - 2), center)

    self.response.headers["Content-Type"] = "image/gif"
    gifimg.write(self.response.out)

if __name__ == "__main__":
  application = webapp.WSGIApplication(
    [
      (r"/image/(\d{3})\.html",                               IndexPage),
      (r"/image/(\d{3})/(\d{12})/(\d{2})\.png",               WholeImage),
      (r"/image/(\d{3})/(\d{12})/(\d{2})\.(\d+)\.(\d+)\.gif", PartialReducedImage),
    ],
    debug = True)
  run_wsgi_app(application)


import logging
import os
import signal
import time
from abc import ABCMeta
from uuid import uuid4

import psutil

from toil.job import Job
from toil.exceptions import FailedJobsException
from toil.lib.threading import cpu_count
from toil.test import ToilTest, slow

logger = logging.getLogger(__name__)

class DeferredFunctionTest(ToilTest, metaclass=ABCMeta):
    """Test the deferred function system."""
    # This determines what job store type to use.
    jobStoreType = 'file'

    def _getTestJobStore(self):
        if self.jobStoreType == 'file':
            return self._getTestJobStorePath()
        elif self.jobStoreType == 'aws':
            return f'aws:{self.awsRegion()}:cache-tests-{uuid4()}'
        elif self.jobStoreType == 'google':
            projectID = os.getenv('TOIL_GOOGLE_PROJECTID')
            return f'google:{projectID}:cache-tests-{str(uuid4())}'
        else:
            raise RuntimeError('Illegal job store type.')

    def setUp(self):
        super().setUp()
        testDir = self._createTempDir()
        self.options = Job.Runner.getDefaultOptions(self._getTestJobStore())
        self.options.logLevel = 'INFO'
        self.options.workDir = testDir
        self.options.clean = 'always'
        self.options.logFile = os.path.join(testDir, 'logFile')

    # Tests for the various defer possibilities
    def testDeferredFunctionRunsWithMethod(self):
        """
        Refer docstring in _testDeferredFunctionRuns.
        Test with Method
        """
        self._testDeferredFunctionRuns(_writeNonLocalFilesMethod)

    def testDeferredFunctionRunsWithClassMethod(self):
        """
        Refer docstring in _testDeferredFunctionRuns.
        Test with Class Method
        """
        self._testDeferredFunctionRuns(_writeNonLocalFilesClassMethod)

    def testDeferredFunctionRunsWithLambda(self):
        """
        Refer docstring in _testDeferredFunctionRuns.
        Test with Lambda
        """
        self._testDeferredFunctionRuns(_writeNonLocalFilesLambda)

    def _testDeferredFunctionRuns(self, callableFn):
        """
        Create 2 files. Make a job that writes data to them. Register a deferred function that
        deletes the two files (one passed as an arg, and one as a kwarg) and later assert that
        the files have been deleted.

        :param function callableFn: The function to use in the test.
        :return: None
        """
        workdir = self._createTempDir(purpose='nonLocalDir')
        nonLocalFile1 = os.path.join(workdir, str(uuid4()))
        nonLocalFile2 = os.path.join(workdir, str(uuid4()))
        open(nonLocalFile1, 'w').close()
        open(nonLocalFile2, 'w').close()
        assert os.path.exists(nonLocalFile1)
        assert os.path.exists(nonLocalFile2)
        A = Job.wrapJobFn(callableFn, files=(nonLocalFile1, nonLocalFile2))
        Job.Runner.startToil(A, self.options)
        assert not os.path.exists(nonLocalFile1)
        assert not os.path.exists(nonLocalFile2)

    @slow
    def testDeferredFunctionRunsWithFailures(self):
        """
        Create 2 non local filesto use as flags.  Create a job that registers a function that
        deletes one non local file.  If that file exists, the job SIGKILLs itself. If it doesn't
        exist, the job registers a second deferred function to delete the second non local file
        and exits normally.

        Initially the first file exists, so the job should SIGKILL itself and neither deferred
        function will run (in fact, the second should not even be registered). On the restart,
        the first deferred function should run and the first file should not exist, but the
        second one should.  We assert the presence of the second, then register the second
        deferred function and exit normally.  At the end of the test, neither file should exist.

        Incidentally, this also tests for multiple registered deferred functions, and the case
        where a deferred function fails (since the first file doesn't exist on the retry).
        """
        self.options.retryCount = 1
        workdir = self._createTempDir(purpose='nonLocalDir')
        nonLocalFile1 = os.path.join(workdir, str(uuid4()))
        nonLocalFile2 = os.path.join(workdir, str(uuid4()))
        open(nonLocalFile1, 'w').close()
        open(nonLocalFile2, 'w').close()
        assert os.path.exists(nonLocalFile1)
        assert os.path.exists(nonLocalFile2)
        A = Job.wrapJobFn(_deferredFunctionRunsWithFailuresFn,
                          files=(nonLocalFile1, nonLocalFile2))
        Job.Runner.startToil(A, self.options)
        assert not os.path.exists(nonLocalFile1)
        assert not os.path.exists(nonLocalFile2)

    @slow
    def testNewJobsCanHandleOtherJobDeaths(self):
        """
        Create 2 non-local files and then create 2 jobs. The first job registers a deferred job
        to delete the second non-local file, deletes the first non-local file and then kills
        itself.  The second job waits for the first file to be deleted, then sleeps for a few
        seconds and then spawns a child. the child of the second does nothing. However starting
        it should handle the untimely demise of the first job and run the registered deferred
        function that deletes the first file.  We assert the absence of the two files at the
        end of the run.
        """

        # Check to make sure we can run two jobs in parallel
        cpus = cpu_count()
        assert cpus >= 2, "Not enough CPUs to run two tasks at once"

        # There can be no retries
        self.options.retryCount = 0
        workdir = self._createTempDir(purpose='nonLocalDir')
        nonLocalFile1 = os.path.join(workdir, str(uuid4()))
        nonLocalFile2 = os.path.join(workdir, str(uuid4()))
        open(nonLocalFile1, 'w').close()
        open(nonLocalFile2, 'w').close()
        assert os.path.exists(nonLocalFile1)
        assert os.path.exists(nonLocalFile2)
        files = [nonLocalFile1, nonLocalFile2]
        root = Job()
        # A and B here must run in parallel for this to work
        A = Job.wrapJobFn(_testNewJobsCanHandleOtherJobDeaths_A, files=files, cores=1)
        B = Job.wrapJobFn(_testNewJobsCanHandleOtherJobDeaths_B, files=files, cores=1)
        C = Job.wrapJobFn(_testNewJobsCanHandleOtherJobDeaths_C, files=files,
                          expectedResult=False, cores=1)
        root.addChild(A)
        root.addChild(B)
        B.addChild(C)
        try:
            Job.Runner.startToil(root, self.options)
        except FailedJobsException as e:
            pass

    def testBatchSystemCleanupCanHandleWorkerDeaths(self):
        """
        Create some non-local files. Create a job that registers a deferred
        function to delete the file and then kills its worker.

        Assert that the file is missing after the pipeline fails, because we're
        using a single-machine batch system and the leader's batch system
        cleanup will find and run the deferred function.
        """

        # There can be no retries
        self.options.retryCount = 0
        workdir = self._createTempDir(purpose='nonLocalDir')
        nonLocalFile1 = os.path.join(workdir, str(uuid4()))
        nonLocalFile2 = os.path.join(workdir, str(uuid4()))
        # The first file has to be non zero or meseeks will go into an infinite sleep
        file1 = open(nonLocalFile1, 'w')
        file1.write('test')
        file1.close()
        open(nonLocalFile2, 'w').close()
        assert os.path.exists(nonLocalFile1)
        assert os.path.exists(nonLocalFile2)
        # We only use the "A" job here, and we fill in the first file, so all
        # it will do is defer deleting the second file, delete the first file,
        # and die.
        A = Job.wrapJobFn(_testNewJobsCanHandleOtherJobDeaths_A,
                          files=(nonLocalFile1, nonLocalFile2))
        try:
            Job.Runner.startToil(A, self.options)
        except FailedJobsException:
            pass
        assert not os.path.exists(nonLocalFile1)
        assert not os.path.exists(nonLocalFile2)

def _writeNonLocalFilesMethod(job, files):
    """
    Write some data to 2 files.  Pass them to a registered deferred method.

    :param tuple files: the tuple of the two files to work with
    :return: None
    """
    for nlf in files:
        with open(nlf, 'wb') as nonLocalFileHandle:
            nonLocalFileHandle.write(os.urandom(1 * 1024 * 1024))
    job.defer(_deleteMethods._deleteFileMethod, files[0], nlf=files[1])
    return None

def _writeNonLocalFilesClassMethod(job, files):
    """
    Write some data to 2 files.  Pass them to a registered deferred class method.

    :param tuple files: the tuple of the two files to work with
    :return: None
    """
    for nlf in files:
        with open(nlf, 'wb') as nonLocalFileHandle:
            nonLocalFileHandle.write(os.urandom(1 * 1024 * 1024))
    job.defer(_deleteMethods._deleteFileClassMethod, files[0], nlf=files[1])
    return None

def _writeNonLocalFilesLambda(job, files):
    """
    Write some data to 2 files.  Pass them to a registered deferred Lambda.

    :param tuple files: the tuple of the two files to work with
    :return: None
    """
    lmd = lambda x, nlf: [os.remove(x), os.remove(nlf)]
    for nlf in files:
        with open(nlf, 'wb') as nonLocalFileHandle:
            nonLocalFileHandle.write(os.urandom(1 * 1024 * 1024))
    job.defer(lmd, files[0], nlf=files[1])
    return None

def _deferredFunctionRunsWithFailuresFn(job, files):
    """
    Refer testDeferredFunctionRunsWithFailures

    :param tuple files: the tuple of the two files to work with
    :return: None
    """
    job.defer(_deleteFile, files[0])
    if os.path.exists(files[0]):
        os.kill(os.getpid(), signal.SIGKILL)
    else:
        assert os.path.exists(files[1])
        job.defer(_deleteFile, files[1])

def _deleteFile(nonLocalFile, nlf=None):
    """
    Delete nonLocalFile and nlf
    :param str nonLocalFile:
    :param str nlf:
    :return: None
    """
    logger.debug("Removing file: %s", nonLocalFile)
    os.remove(nonLocalFile)
    logger.debug("Successfully removed file: %s", nonLocalFile)
    if nlf is not None:
        logger.debug("Removing file: %s", nlf)
        os.remove(nlf)
        logger.debug("Successfully removed file: %s", nlf)

def _testNewJobsCanHandleOtherJobDeaths_A(job, files):
    """
    Defer deletion of files[1], then wait for _testNewJobsCanHandleOtherJobDeaths_B to
    start up, and finally delete files[0] before sigkilling self.

    :param tuple files: the tuple of the two files to work with
    :return: None
    """

    # Write the pid to files[1] such that we can be sure that this process has died before
    # we spawn the next job that will do the cleanup.
    with open(files[1], 'w') as fileHandle:
        fileHandle.write(str(os.getpid()))
    job.defer(_deleteFile, files[1])
    logger.info("Deferred delete of %s", files[1])
    while os.stat(files[0]).st_size == 0:
        time.sleep(0.5)
    os.remove(files[0])
    os.kill(os.getpid(), signal.SIGKILL)

def _testNewJobsCanHandleOtherJobDeaths_B(job, files):
    # Write something to files[0] such that we can be sure that this process has started
    # before _testNewJobsCanHandleOtherJobDeaths_A kills itself.
    with open(files[0], 'w') as fileHandle:
        fileHandle.write(str(os.getpid()))
    while os.path.exists(files[0]):
        time.sleep(0.5)
    # Get the pid of _testNewJobsCanHandleOtherJobDeaths_A and wait for it to truly be dead.
    with open(files[1]) as fileHandle:
        pid = int(fileHandle.read())
    assert pid > 0
    while psutil.pid_exists(pid):
        time.sleep(0.5)
    # Now that we are convinced that_testNewJobsCanHandleOtherJobDeaths_A has died, we can
    # spawn the next job

def _testNewJobsCanHandleOtherJobDeaths_C(job, files, expectedResult):
    """
    Asserts whether the files exist or not.

    :param Job job: Job
    :param list files: list of files to test
    :param bool expectedResult: Are we expecting the files to exist or not?
    """
    for testFile in files:
        assert os.path.exists(testFile) is expectedResult

class _deleteMethods:
    @staticmethod
    def _deleteFileMethod(nonLocalFile, nlf=None):
        """
        Delete nonLocalFile and nlf

        :return: None
        """
        os.remove(nonLocalFile)
        if nlf is not None:
            os.remove(nlf)

    @classmethod
    def _deleteFileClassMethod(cls, nonLocalFile, nlf=None):
        """
        Delete nonLocalFile and nlf

        :return: None
        """
        os.remove(nonLocalFile)
        if nlf is not None:
            os.remove(nlf)


from flask import Flask, render_template, request
from flask_socketio import SocketIO, emit, join_room
#from qa_service import query_document

app = Flask(__name__)
socketio = SocketIO(app)

# Store user and admin rooms
user_room = "user_room"
admin_room = "admin_room"

# Initialize bot_enabled flag
bot_enabled = False

# Dictionary to store user messages
user_messages = {}

@app.route("/user_interface")
def user_interface():
    return render_template("user_interface.html")

@app.route("/admin_interface")
def admin_interface():
    return render_template("admin_interface.html", users=list(user_messages.keys()))

@app.route("/admin_interface/<username>")
def admin_with_user(username):
    if username not in user_messages:
        user_messages[username] = []
    return render_template("admin_interface_with_user.html", username=username, messages=user_messages[username])

@socketio.on("join_room")
def join_user_room():
    join_room(user_room)

@socketio.on("message")
def handle_message(data):
    if bot_enabled:
        query = data["message"]
        bot_response = 'Hi bot reply here'  # Assuming query_document function is available
        emit("message", {"user": "Admin", "message": bot_response}, room=user_room)
    else:
        emit("message", data, room=user_room, broadcast=True)

@socketio.on("user_send_message")
def handle_user_message(data):
    username = data["user"]
    message = data["message"]
    if username not in user_messages:
        user_messages[username] = []
    user_messages[username].append({"user": username, "message": message})
    emit("message", data, room=user_room)

@socketio.on("admin_join_room")
def join_admin_room():
    join_room(admin_room)

@socketio.on("admin_send_message")
def handle_admin_send_message(data):
    emit("message", data, room=user_room)

@socketio.on("toggle_bot")
def toggle_bot_reply():
    global bot_enabled
    bot_enabled = not bot_enabled

if __name__ == "__main__":
    socketio.run(app, debug=True)


from __future__ import print_function

import numpy as np
from matplotlib import pyplot as plot
from scipy.io import loadmat
from sklearn.svm import libsvm

def plot_data(X, y, show=True):
    pos = y.nonzero()[0]
    neg = (y == 0).nonzero()[0]
    plot.plot(X[pos, 0], X[pos, 1], 'k+', markersize=7, linewidth=2)
    plot.plot(X[neg, 0], X[neg, 1], 'ko', markerfacecolor='y', markersize=7, linewidth=2)
    if show:
        plot.show()

def visualize_boundary_linear(X, y, model):
    support_vectors = model[1]
    coeffs = model[3]
    intercept = model[4]
    normal_vector = coeffs.dot(support_vectors).flatten()
    xp = np.linspace(np.amin(X[:, 0]), np.amax(X[:, 0]), 100)
    yp = -(normal_vector[0] * xp + intercept) / normal_vector[1]
    plot_data(X, y, show=False)
    plot.plot(xp, yp, '-b')
    plot.show()

def visualize_boundary(X, y, model, gamma):
    plot_data(X, y, show=False)
    x1plot = np.linspace(np.amin(X[:, 0]), np.amax(X[:, 0]), 100)
    x2plot = np.linspace(np.amin(X[:, 1]), np.amax(X[:, 1]), 100)
    X1, X2 = np.meshgrid(x1plot, x2plot)
    predictions = np.zeros_like(X1)
    for i in range(X1.shape[1]):
        currentX = np.require(np.vstack((X1[:, i], X2[:, i])).T, requirements='C_CONTIGUOUS')
        predictions[:, i] = libsvm.predict(
            currentX,
            support=model[0],
            SV=model[1],
            nSV=model[2],
            sv_coef=model[3],
            intercept=model[4],
            label=model[5],
            probA=model[6],
            probB=model[7],
            kernel='rbf',
            gamma=gamma
        )
    plot.contour(X1, X2, predictions, [0.0, 0.0])
    plot.show()

def gaussian_kernel(x1, x2, sigma):
    return np.exp(-sum((x1 - x2) ** 2) / (2.0 * sigma ** 2))

def dataset3_params(X, y, Xval, yval):
    all_C = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30]
    all_sigma = [0.01, 0.03, 0.1, 0.3, 1, 3, 10, 30]
    best_C = all_C[0]
    best_sigma = all_sigma[0]
    previous_err = 1000.0
    for C in all_C:
        for sigma in all_sigma:
            gamma = 1.0 / (2.0 * sigma ** 2)
            model = libsvm.fit(X, y, kernel='rbf', C=C, gamma=gamma)
            predictions = libsvm.predict(
                Xval,
                support=model[0],
                SV=model[1],
                nSV=model[2],
                sv_coef=model[3],
                intercept=model[4],
                label=model[5],
                probA=model[6],
                probB=model[7],
                kernel='rbf',
                gamma=gamma
            )
            err = np.mean(predictions != yval)
            if err < previous_err:
                best_C = C
                best_sigma = sigma
                previous_err = err
    return (best_C, best_sigma)

if __name__ == '__main__':
    data = loadmat('../../octave/mlclass-ex6/ex6data1.mat')
    X = np.require(data['X'], dtype=np.float64, requirements='C_CONTIGUOUS')
    y = np.require(data['y'].flatten(), dtype=np.float64)
    plot_data(X, y)
    print('Training Linear SVM ...')
    C = 1.0
    model = libsvm.fit(X, y, kernel='linear', tol=0.001, C=C, max_iter=20)
    visualize_boundary_linear(X, y, model)
    # evaluate gaussian kernel
    x1 = np.array([1.0, 2.0, 1.0])
    x2 = np.array([0.0, 4.0, -1.0])
    sigma = 2.0
    value = gaussian_kernel(x1, x2, sigma)
    print('Gaussian Kernel between x1 = [1; 2; 1], x2 = [0; 4; -1], sigma = 0.5: %f' % value)
    print('(this value should be about 0.324652)')
    # dataset 2
    data = loadmat('../../octave/mlclass-ex6/ex6data2.mat')
    X = np.require(data['X'], dtype=np.float64, requirements='C_CONTIGUOUS')
    y = np.require(data['y'].flatten(), dtype=np.float64)
    plot_data(X, y)
    print('Training SVM with RBF Kernel ...')
    C = 1.0
    sigma = 0.1
    gamma = 1.0 / (2.0 * sigma ** 2)
    model = libsvm.fit(X, y, kernel='rbf', C=C, gamma=gamma)
    visualize_boundary(X, y, model, gamma)
    # dataset 3
    data = loadmat('../../octave/mlclass-ex6/ex6data3.mat')
    X = np.require(data['X'], dtype=np.float64, requirements='C_CONTIGUOUS')
    y = np.require(data['y'].flatten(), dtype=np.float64)
    Xval = np.require(data['Xval'], dtype=np.float64, requirements='C_CONTIGUOUS')
    yval = np.require(data['yval'].flatten(), dtype=np.float64)
    plot_data(X, y)
    best_C, best_sigma = dataset3_params(X, y, Xval, yval)
    best_gamma = 1.0 / (2.0 * best_sigma ** 2)
    model = libsvm.fit(X, y, kernel='rbf', C=best_C, gamma=best_gamma)
    visualize_boundary(X, y, model, best_gamma)


# people : 사람들의 몸무게를 담은 배열 (정수)
# limit : 구명보트의 무게 제한 (정수)
# return : 모든 사람을 구출하기 위해 필요한 구명보트 개수의 최솟값 (정수)

## 중요 포인트 !! 한 보트에 2명까지 밖에 못 탐..
def solution(people, limit):
    answer = 0

    # 무거운 순으로 정렬
    people.sort(reverse=True)

    # boat[] : 1명 타고 있는 보트
    boat = []

    for wp in people:
        # 1. 무게 제한의 절반 보다 무거운 사람들은 서로 같은 보트에 탈 수 없다.
        if wp > limit - wp:
            boat.append(limit - wp)
        # 2. boat[-1] 은 1명씩 타고 있는 보트 중 무게 여유가 가장 큰 보트이다.
        elif boat[-1] >= wp:
            boat.pop()
            answer += 1
        else:
            boat.append(limit - wp)

    return answer + len(boat)

# 시간복잡도 : O(nlogn)


import logging
from functools import cached_property

from django.db.models import Q
from langchain.callbacks.manager import CallbackManager

from ix.agents.models import Agent
from ix.chat.models import Chat
from ix.task_log.models import Task

logger = logging.getLogger(__name__)

class IxCallbackManager(CallbackManager):
    """
    Custom callback manager that adds iX functionality.
    """

    stack_id: str
    task: Task

    def __init__(
        self,
        task: Task,
        agent: Agent,
        stack_id: str = None,
        parent: "IxCallbackHandler" = None,  # noqa: F821
    ):
        super().__init__(handlers=[])

        self.task = task
        self.agent = agent
        self.stack_id = stack_id or "root"
        self.parent = parent

    def child(self, stack_id: str) -> "IxCallbackManager":
        """Return a child clone with nested stack_id"""
        child = type(self)(
            parent=self,
            task=self.task,
            agent=self.agent,
            stack_id=f"{self.stack_id}.{stack_id}",
        )
        child.think_msg = self.think_msg
        return child

    @property
    def task_id(self) -> str:
        return str(self.task.id)

    @property
    def agent_id(self) -> str:
        return str(self.task.agent_id)

    @property
    def user_id(self) -> str:
        # HAX: this is currently always the owner of the chat. Likely need to update
        # this in the future to be the user making the request.
        return str(self.task.user_id)

    @cached_property
    def chat_id(self) -> str:
        try:
            chat = Chat.objects.get(Q(task=self.task) | Q(task_id=self.task.parent_id))
        except Chat.DoesNotExist:
            return None
        return chat.id


class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        n = len(nums)
        my_set = set(range(n+1))
        for num in nums:
            if num in my_set:
                my_set.remove(num)

        for k in my_set:
            return k


__author__ = 'roehrig'
# ftp://ftp.dwd.de/pub/data/gpcc/full_data/full_data_v7_05.nc.gz

import os
import numpy as np
import pandas as pd
from netCDF4 import Dataset, num2date
import ogr
import osr

class FullDataV0705(object):

    def __init__(self, filename,
                 min_lon=-180.0, max_lon=180.0, min_lat=-90.0, max_lat=90.0):
        self.filename = filename
        self.min_lon = min_lon
        self.max_lon = max_lon
        self.min_lat = min_lat
        self.max_lat = max_lat
        self._time = None
        self._longitudes = None
        self._latitudes = None
        self._precipitations = None
        self.dataset = Dataset(self.filename, 'r')

    def get_time(self):
        if self._time is None:
            t = self.dataset.variables['time']
            self._time = num2date(t[:], t.units)
        return self._time

    def get_longitudes(self):
        if self._longitudes is None:
            self._longitudes = self.dataset.variables['lon'][:]
        return self._longitudes

    def get_latitudes(self):
        if self._latitudes is None:
            self._latitudes = self.dataset.variables['lat'][:]
        return self._latitudes

    def get_precipitations(self):
        if self._precipitations is None:
            p = np.squeeze(self.dataset.variables[u'p'])  # time, lat, lon
            lon = self.get_longitudes()
            lat = self.get_latitudes()
            i_lon = np.where((lon <= self.max_lon) & (lon >= self.min_lon))[0]
            i_lat = np.where((lat <= self.max_lat) & (lat >= self.min_lat))[0]
            p = p[:, i_lat[0]:i_lat[-1]+1, i_lon[0]:i_lon[-1]+1]
            self._precipitations = p.swapaxes(0, 2)  # lon, lat, t
        return self._precipitations

    def create_shapefile(self, filename=None):
        if not filename:
            f = os.path.splitext(os.path.basename(self.filename))[0] + '.shp'
            d = os.path.join(os.path.dirname(self.filename), 'gis')
            filename = os.path.join(d, f)
            if not os.path.isdir(d):
                os.mkdir(d)
        sr = osr.SpatialReference()
        sr.ImportFromEPSG(4326)
        driver = ogr.GetDriverByName('ESRI Shapefile')
        if os.path.isfile(filename) and os.stat(filename):
            driver.DeleteDataSource(filename)
        ds = driver.CreateDataSource(filename)

        layer = ds.CreateLayer('', sr, ogr.wkbPoint)
        layer.CreateField(ogr.FieldDefn('id', ogr.OFTString))
        layer.CreateField(ogr.FieldDefn('Latitude', ogr.OFTReal))
        layer.CreateField(ogr.FieldDefn('Longitude', ogr.OFTReal))

        ld = layer.GetLayerDefn()
        for lon in self.get_longitudes():
            str_lon = str(lon) + '_'
            for lat in self.get_latitudes():
                feat = ogr.Feature(ld)
                feat.SetField('id', str_lon + str(lat))
                feat.SetField('Longitude', lon)
                feat.SetField('Latitude', lat)
                point = ogr.Geometry(ogr.wkbPoint)
                point.AddPoint(lon, lat)
                feat.SetGeometry(point)
                layer.CreateFeature(feat)

        ds = layer = feat = point = None

    def get_column_names_and_values(self):
        lon = self.get_longitudes()
        lat = self.get_latitudes()
        i_lon = np.where((lon <= self.max_lon) & (lon >= self.min_lon))[0]
        i_lat = np.where((lat <= self.max_lat) & (lat >= self.min_lat))[0]
        for iLon, pLon in enumerate(self.get_precipitations()):
            lon0 = lon[i_lon[iLon]]
            str_lon = ("%06.2f"%-lon0 + 'E') if lon0 < 0.0 else ("%06.2f"%lon0 + 'W')
            for iLat, pLat in enumerate(pLon):
                if np.sum(pLat > -99999) > 0:  # any value < -99999
                    lat0 = lat[i_lat[iLat]]
                    str_lat = ("%05.2f"%-lat0 + 'S') if lat0 < 0.0 \
                        else ("%05.2f"%lat0 + 'N')
                    col_name = str_lon + '_' +  str_lat
                    yield (col_name, pLat)

    def to_data_frame(self):
        df = pd.DataFrame(index=num2date(self.get_time()[:], self.dataset.variables['time'].units))
        for col_name, precipitations in self.get_column_names_and_values():
            df[col_name] = precipitations
            df[df[col_name]<-99999] = np.nan
        return df

    def to_csv(self, output_dir=None, sep=';', compression=None):
        prefix = os.path.splitext(os.path.basename(self.filename))[0] + '_'
        if not output_dir:
            output_dir = os.path.join(os.path.dirname(self.filename), 'csv')
        if not os.path.isdir(output_dir):
            os.mkdir(output_dir)
        df = pd.DataFrame(index=self.get_time())
        df.index.name = 'Date'
        for col_name, precipitations in self.get_column_names_and_values():
            df['P' + col_name] = precipitations
            filename = os.path.join(output_dir, prefix + col_name + '.csv')
            if compression == 'gzip':
                filename += '.gz'
            elif compression == 'bz2':
                filename += '.bz2'
            df.to_csv(filename, sep=sep, compression=compression)
            del df['P' + col_name]


#!/usr/bin/env python
# encoding: utf-8
'''
@author: baibing
@contact: 243061887(qq)
@software: pycharm
@file: 冒充飞Q.py
@time: 7/3/19 3:18 PM
@desc:
'''

'''
TCP是建立可靠的连接，并且通信双方都可以以流的形式发送数据，相对于TCP，UDP则是面向无连接的协议

使用UDP协议时，不需建立连接，只需要知道对方的IP地址和端口号，就可以直接发送数据包，但是能不能到达就不知道了

虽然UDP传输数据不可靠，但他的优点和TCP相比，速度快，对于要求不高的三数据可以用UDP

'''

import socket
import time

#>>>>>>>>>>>>>>>>>>>>客户端<<<<<<<<<<<<<<<<<<<<<<<

udp = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)       #创建一个socket
udp.connect(("172.20.124.131",8091))                        #连接
udp.sendto("hello,ice bai man ".encode("utf-8"),("172.20.124.131",8091))
while True:
    # udp.send("ice bai is a good man ".encode("utf-8"))          #直接发送数据
    time.sleep(5)


#
# programmed by Chris, 02/17/2023
#

import json
import base64
import logging
import os.path
import requests

from bs4 import BeautifulSoup
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from email.message import EmailMessage

import email_info

SCOPES = ['https://www.googleapis.com/auth/gmail.send']

# dictionary of the items at full price
full_prices = {
    'TOMS Carlo Sneaker'                         : 54.95,
    'MoonGoat Pocket Shop T-Shirt'               : 22.27,
    'Sony WH-1000XM4 Noise Canceling Headphones' : 349.99,
    'Hades No Escape Shirt'                      : 32.00,
    'Battlecry Acre Crusader Broadsword'         : 329.95,
    'CROM Dark Splendor T-shirt'                 : 31.00,
    'LG 34WQ75C-B Monitor'                       : 599.99
}

# configure the logging to output
def config_logging():

    logging.basicConfig(filename='output.log', filemode='a', level=logging.INFO,
                        format='%(asctime)s %(levelname)s %(message)s')

    # to avoid - INFO file_cache is only supported with oauth2client<4.0.0
    logging.getLogger('googleapiclient.discovery_cache').setLevel(logging.ERROR)

# get data for TOMS shoe
def get_toms_data():

    link = 'https://www.toms.com/us/men/shoes/sneakers/' \
           'black-on-black-heritage-canvas-mens-carlo-sneaker-topanga-collection/10012282.html'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    product_data = soup.find('div', {'data-product': True})['data-product']
    product_dict = json.loads(product_data)['product']

    size_data = soup.find('button', {'aria-label' : 'Select Men Size 10'})

    if size_data is None:
        size_data = 'N/A'
    else:
        size_data = size_data['data-size']

    shoe_variant = product_dict['variants'][0]

    name = ' '.join([product_dict['brand_name'], product_dict['name']])
    price = float(shoe_variant['price'])
    size = size_data
    in_stock = shoe_variant['in_stock']
    image_link = shoe_variant['image_url']

    return name, price, size, link

# get data for MoonGoat shirt
def get_moongoat_data():

    link = 'https://moongoat.com/products/pocket-shop-t-shirt'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    product_data = soup.find('script', id='wcp_json_7807686967547')
    product_dict = json.loads(product_data.string)

    shirt_variant = product_dict['variants'][1]

    name = ' '.join([product_dict['vendor'], product_dict['title']])
    price = str(shirt_variant['price'])
    size = shirt_variant['title']
    in_stock = shirt_variant['available']
    image_link = product_dict['featured_image']

    # fix formatting of data
    name = ''.join(char.upper() if (index == 0 or index == 4) else char for index, char in enumerate(name))
    price = float(price[:2] + '.' + price[2:])

    return name, price, size, link

# get data for Sony WH-1000XM4 Noise Canceling Headphones
def get_headphone_data():

    link = 'https://electronics.sony.com/audio/headphones/headband/p/wh1000xm4-b'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    product_data = soup.find('script', id='pdp-jsonld-data')
    product_dict = json.loads(product_data.string)

    stock_data = soup.find('button', {'class' : 'sony-btn sony-btn--primary sony-btn--primary w-100'}).text[1:12]

    name = ' '.join([product_dict['brand']['name'], product_dict['description'][3:13], product_dict['description'][31:57]])
    price = product_dict['offers']['price']
    size = 'N/A'
    in_stock = stock_data == 'Add to cart'
    image_link = product_dict['image']

    return name, price, size, link

# get data for Hades Shirt
def get_hades_data():

    link = 'https://www.fangamer.com/collections/hades/products/hades-shirt-no-escape'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    price_size_data = soup.find('option', value='40367665610809').text

    stock_data = soup.find('meta', content='InStock')

    image_data = ''.join(['https:', soup.find_all('a', {'class' : 'item'})[1]['href']])

    name = 'Hades No Escape Shirt'
    price = float(price_size_data[-5:])
    size = price_size_data[7:8]
    in_stock = stock_data['content']
    image_link = 'N/A'

    return name, price, size, link

# get data for the battlecry acre crusader broadsword
def get_broadsword_data():

    link = 'https://www.museumreplicas.com/acre-crusader-broadsword'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    name_data = soup.find('meta', property='og:title')['content']

    price_data = soup.find('span', {'class' : 'price-value-2878 sezzle-price'})['content']

    stock_data = soup.select_one('span[id=stock-availability-value-2878]').text

    image_data = soup.find_all('a', {'class' : 'cloud-zoom-gallery thumb-item'})[-1]['href']

    name = name_data
    price = float(price_data)
    size = '39-1/4"'
    in_stock = stock_data
    image_link = image_data

    return name, price, size, link

# get data for the crom dark splendor t-shirt
def get_crom_data():

    link = 'https://crom.ink/shop/dark-splendor-t-shirt'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    name_data = soup.find('title').text

    product_data = soup.find('div', {'class' : 'product-variants'})

    variant = json.loads(product_data['data-variants'])[0]

    name = ' '.join([name_data[24:28], name_data[0:21]])
    price = float(variant['salePriceMoney']['value'])
    size = variant['attributes']['Size']
    in_stock = int(variant['qtyInStock']) > 0
    image_link = variant['mainImage']['assetUrl']

    return name, price, size, link

# get data for the LG 34WQ75C-B Monitor
def get_monitor_data():

    link = 'https://www.lg.com/us/monitors/lg-34wq75c-b'

    page = requests.get(link)
    soup = BeautifulSoup(page.content, 'html.parser')

    name_data = soup.find('meta', {'property' : 'og:description'})

    price_data = soup.find('meta', {'itemprop' : 'price'})

    stock_data = soup.find('div', {'class' : 'in-stock-pdp-new'})\

    image_data = soup.find('img', {'class' : 'pc'})

    name = ' '.join([name_data['content'][5:17], 'Monitor'])
    price = float(price_data['content'])
    size = 'N/A'
    in_stock = stock_data.text[0:9]
    image_link = image_data['src']

    return name, price, size, link

# scrape HTML from web pages, get basic data, send email if sale found
def get_website_data():

    items = [get_toms_data, get_moongoat_data, get_headphone_data, get_hades_data, get_broadsword_data,
             get_crom_data, get_monitor_data]
    on_sale = []

    for item in items:

        name, price, size, link = item()
        full_price = full_prices[name]

        if(price < full_price):
            data = (name, price, size, link)
            on_sale.append(data)

    if on_sale:
        send_sale_email(on_sale)
    else:
        logging.info('no sales found, no email sent')

# send an email to myself with the data of the item(s) on sale
def send_sale_email(sales):

    creds = None

    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)

        # refresh the credentials
        creds.refresh(Request())

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)

        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('gmail', 'v1', credentials=creds)
        message = EmailMessage()

        email_body = 'sales bot found a sale\n'

        for sale in sales:

            name, price, size, link = sale

            sale_str = f'\n| {name} |\n  on sale ${price}, size {size}\n{link}\n'

            email_body = ''.join((email_body, sale_str))

            logging.info(f'item on sale - {name} (${price})')

        message.set_content(email_body)

        message['To'] = email_info.get_email()
        message['From'] = email_info.get_email()
        message['Subject'] = 'you\'ve got sale'

        encoded_message = base64.urlsafe_b64encode(message.as_bytes()).decode()

        create_message = {
            'raw': encoded_message
        }

        send_message = (service.users().messages().send(userId="me", body=create_message).execute())
        logging.info(f'sent email, id {send_message["id"]}')

    except HttpError as error:
        send_message = None
        logging.error(f'An error occurred: {error}')

if __name__ == '__main__':
    config_logging()
    get_website_data()


import argparse
import json
import os
import pathlib
import shutil
import subprocess
import sys

SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
REPO_DIR = os.path.normpath(os.path.join(SCRIPT_DIR, "..", "..", "..", ".."))
BUILD_PY = os.path.join(REPO_DIR, "tools", "ci_build", "build.py")
JAVA_ROOT = os.path.join(REPO_DIR, "java")
DEFAULT_BUILD_VARIANT = "Full"

sys.path.insert(0, os.path.join(REPO_DIR, "tools", "python"))
from util import is_windows  # noqa: E402

# We by default will build all 4 ABIs
DEFAULT_BUILD_ABIS = ["armeabi-v7a", "arm64-v8a", "x86", "x86_64"]

# Onnx Runtime native library is built against NDK API 21 by default
# It is possible to build from source for Android API levels below 21, but it is not guaranteed
DEFAULT_ANDROID_MIN_SDK_VER = 21

# Android API 24 is the default target API version for Android builds, based on Microsoft 1CS requirements
# It is possible to build from source using API level 21 and higher as the target SDK version
DEFAULT_ANDROID_TARGET_SDK_VER = 24

def _parse_build_settings(args):
    setting_file = args.build_settings_file.resolve()

    if not setting_file.is_file():
        raise FileNotFoundError(f"Build config file {setting_file} is not a file.")

    with open(setting_file) as f:
        build_settings_data = json.load(f)

    build_settings = {}

    if "build_abis" in build_settings_data:
        build_settings["build_abis"] = build_settings_data["build_abis"]
    else:
        build_settings["build_abis"] = DEFAULT_BUILD_ABIS

    build_params = []
    if "build_params" in build_settings_data:
        build_params += build_settings_data["build_params"]
    else:
        raise ValueError("build_params is required in the build config file")

    if "android_min_sdk_version" in build_settings_data:
        build_settings["android_min_sdk_version"] = build_settings_data["android_min_sdk_version"]
    else:
        build_settings["android_min_sdk_version"] = DEFAULT_ANDROID_MIN_SDK_VER
    build_params += ["--android_api=" + str(build_settings["android_min_sdk_version"])]

    if "android_target_sdk_version" in build_settings_data:
        build_settings["android_target_sdk_version"] = build_settings_data["android_target_sdk_version"]
    else:
        build_settings["android_target_sdk_version"] = DEFAULT_ANDROID_TARGET_SDK_VER

    if build_settings["android_min_sdk_version"] > build_settings["android_target_sdk_version"]:
        raise ValueError(
            "android_min_sdk_version {} cannot be larger than android_target_sdk_version {}".format(
                build_settings["android_min_sdk_version"], build_settings["android_target_sdk_version"]
            )
        )

    build_settings["build_params"] = build_params
    build_settings["build_variant"] = build_settings_data.get("build_variant", DEFAULT_BUILD_VARIANT)

    return build_settings

def _build_aar(args):
    build_settings = _parse_build_settings(args)
    build_dir = os.path.abspath(args.build_dir)
    ops_config_path = os.path.abspath(args.include_ops_by_config) if args.include_ops_by_config else None

    # Setup temp environment for building
    temp_env = os.environ.copy()
    temp_env["ANDROID_HOME"] = os.path.abspath(args.android_sdk_path)
    temp_env["ANDROID_NDK_HOME"] = os.path.abspath(args.android_ndk_path)

    # Temp dirs to hold building results
    intermediates_dir = os.path.join(build_dir, "intermediates")
    build_config = args.config
    aar_dir = os.path.join(intermediates_dir, "aar", build_config)
    jnilibs_dir = os.path.join(intermediates_dir, "jnilibs", build_config)
    exe_dir = os.path.join(intermediates_dir, "executables", build_config)
    base_build_command = [sys.executable, BUILD_PY] + build_settings["build_params"] + ["--config=" + build_config]
    header_files_path = ""

    # Build binary for each ABI, one by one
    for abi in build_settings["build_abis"]:
        abi_build_dir = os.path.join(intermediates_dir, abi)
        abi_build_command = [*base_build_command, "--android_abi=" + abi, "--build_dir=" + abi_build_dir]

        if ops_config_path is not None:
            abi_build_command += ["--include_ops_by_config=" + ops_config_path]

        subprocess.run(abi_build_command, env=temp_env, shell=False, check=True, cwd=REPO_DIR)

        # create symbolic links for libonnxruntime.so and libonnxruntime4j_jni.so
        # to jnilibs/[abi] for later compiling the aar package
        abi_jnilibs_dir = os.path.join(jnilibs_dir, abi)
        os.makedirs(abi_jnilibs_dir, exist_ok=True)
        for lib_name in ["libonnxruntime.so", "libonnxruntime4j_jni.so"]:
            target_lib_name = os.path.join(abi_jnilibs_dir, lib_name)
            # If the symbolic already exists, delete it first
            # For some reason, os.path.exists will return false for a symbolic link in Linux,
            # add double check with os.path.islink
            if os.path.exists(target_lib_name) or os.path.islink(target_lib_name):
                os.remove(target_lib_name)
            os.symlink(os.path.join(abi_build_dir, build_config, lib_name), target_lib_name)

        # copy executables for each abi, in case we want to publish those as well
        abi_exe_dir = os.path.join(exe_dir, abi)
        for exe_name in ["libonnxruntime.so", "onnxruntime_perf_test", "onnx_test_runner"]:
            os.makedirs(abi_exe_dir, exist_ok=True)
            target_exe_name = os.path.join(abi_exe_dir, exe_name)
            shutil.copyfile(os.path.join(abi_build_dir, build_config, exe_name), target_exe_name)

        # we only need to define the header files path once
        if not header_files_path:
            header_files_path = os.path.join(abi_build_dir, build_config, "android", "headers")

    # The directory to publish final AAR
    aar_publish_dir = os.path.join(build_dir, "aar_out", build_config)
    os.makedirs(aar_publish_dir, exist_ok=True)

    gradle_path = os.path.join(JAVA_ROOT, "gradlew" if not is_windows() else "gradlew.bat")

    # get the common gradle command args
    gradle_command = [
        gradle_path,
        "--no-daemon",
        "-b=build-android.gradle",
        "-c=settings-android.gradle",
        "-DjniLibsDir=" + jnilibs_dir,
        "-DbuildDir=" + aar_dir,
        "-DheadersDir=" + header_files_path,
        "-DpublishDir=" + aar_publish_dir,
        "-DminSdkVer=" + str(build_settings["android_min_sdk_version"]),
        "-DtargetSdkVer=" + str(build_settings["android_target_sdk_version"]),
        "-DbuildVariant=" + str(build_settings["build_variant"]),
        "-DENABLE_TRAINING_APIS=1"
        if "--enable_training_apis" in build_settings["build_params"]
        else "-DENABLE_TRAINING_APIS=0",
    ]

    # clean, build, and publish to a local directory
    subprocess.run([*gradle_command, "clean"], env=temp_env, shell=False, check=True, cwd=JAVA_ROOT)
    subprocess.run([*gradle_command, "build"], env=temp_env, shell=False, check=True, cwd=JAVA_ROOT)
    subprocess.run([*gradle_command, "publish"], env=temp_env, shell=False, check=True, cwd=JAVA_ROOT)

def parse_args():
    parser = argparse.ArgumentParser(
        os.path.basename(__file__),
        description="""Create Android Archive (AAR) package for one or more Android ABI(s)
        and building properties specified in the given build config file, see
        tools/ci_build/github/android/default_mobile_aar_build_settings.json for details.
        The output of the final AAR package can be found under [build_dir]/aar_out
        """,
    )

    parser.add_argument(
        "--android_sdk_path", type=str, default=os.environ.get("ANDROID_HOME", ""), help="Path to the Android SDK"
    )

    parser.add_argument(
        "--android_ndk_path", type=str, default=os.environ.get("ANDROID_NDK_HOME", ""), help="Path to the Android NDK"
    )

    parser.add_argument(
        "--build_dir",
        type=str,
        default=os.path.join(REPO_DIR, "build/android_aar"),
        help="Provide the root directory for build output",
    )

    parser.add_argument(
        "--include_ops_by_config",
        type=str,
        help="Include ops from config file. See /docs/Reduced_Operator_Kernel_build.md for more information.",
    )

    parser.add_argument(
        "--config",
        type=str,
        default="Release",
        choices=["Debug", "MinSizeRel", "Release", "RelWithDebInfo"],
        help="Configuration to build.",
    )

    parser.add_argument(
        "build_settings_file", type=pathlib.Path, help="Provide the file contains settings for building AAR"
    )

    return parser.parse_args()

def main():
    args = parse_args()

    # Android SDK and NDK path are required
    if not args.android_sdk_path:
        raise ValueError("android_sdk_path is required")
    if not args.android_ndk_path:
        raise ValueError("android_ndk_path is required")

    _build_aar(args)

if __name__ == "__main__":
    main()


import random
import os

cases = 20
for i in range(cases):
    N = random.randint(1, 5)
    caseString = "%d\n" % N
    for j in range(N):
        T = random.randint(5, 15)
        arr = ""
        for k in range(T-1):
            arr += f"{random.randint(-100, 100)} "
        caseString += arr + "\n"

    caseName = 'g0.{}.in'.format(i)

    casePath = os.path.join('MiCompaElGymRat/cases', caseName)
    with open(casePath, 'w') as f:
        f.write(caseString.strip('\t\n\r'))


"""
Toy Indexer
===========

Toy indexing example for testing purposes.

:Authors: Krisztian Balog, Faegheh Hasibi
"""
from nordlys.core.retrieval.elastic import Elastic

def main():
    index_name = "toy_index"

    mappings = {
        "title": Elastic.analyzed_field(),
        "content": Elastic.analyzed_field(),
    }

    docs = {
        1: {"title": "Rap God",
            "content": "gonna, gonna, Look, I was gonna go easy on you and not to hurt your feelings"
            },
        2: {"title": "Lose Yourself",
            "content": "Yo, if you could just, for one minute Or one split second in time, forget everything Everything that bothers you, or your problems Everything, and follow me"
            },
        3: {"title": "Love The Way You Lie",
            "content": "Just gonna stand there and watch me burn But that's alright, because I like the way it hurts"
            },
        4: {"title": "The Monster",
            "content": ["gonna gonna I'm friends with the monster", "That's under my bed Get along with the voices inside of my head"]
            },
        5: {"title": "Beautiful",
            "content": "Lately I've been hard to reach I've been too long on my own Everybody has a private world Where they can be alone"
            }
    }

    elastic = Elastic(index_name)
    elastic.create_index(mappings, force=True)
    elastic.add_docs_bulk(docs)
    print("index has been built")

if __name__ == "__main__":
    main()


import hkvfewspy as hkv
import datetime

def test_runtask_params():
    pi = hkv.Pi(protocol="rest")
    pi.setUrl(
        "https://oms-ijmuiden.hkvservices.nl/FewsWebServices/rest/fewspiservice/v1/"
    )

    pi.runTask(
        startTime=datetime.date(2021, 10, 30),
        endTime=datetime.date(2021, 11, 1),
        workflowId="wf.sym.DatabaseMaintenance",
    )
    assert pi


#!python3

from threading import Thread, Event
import multiprocessing
import logging
import time
import datetime
from collections import deque

from ping_senders.pinger import Pinger

class SendAsyncStrategy(Thread):

  MAX_PINGS_TO_SEND = 100
  WAIT_BEFORE_RETRY = 10

  def __init__(self, server, chronoId):
    super(SendAsyncStrategy, self).__init__()  # super() will call Thread.__init__ for you
    self.logger = logging.getLogger('SendStrategy')
    self.pinger = Pinger(server, chronoId)
    self.lastFailure = 0
    self.q = deque()
    self.exit = Event()

  def append(self, toSend):
    self.q.append(toSend)

  def pop(self):
    fromQueue = None
    if len(self.q) > 0:
      fromQueue = self.q.popleft()
    return fromQueue

  def stop(self):
    self.logger.info('Stopping send thread')
    self.exit.set()

  def run(self):
    while not self.exit.is_set():
      self.exit.wait(1)
      toSend = []
      if self.lastFailure + self.WAIT_BEFORE_RETRY < datetime.datetime.now().timestamp():
        while len(toSend) < self.MAX_PINGS_TO_SEND and len(self.q) > 0:
          fromQueue = self.pop()
          if fromQueue:
            toSend.append(fromQueue)
      if toSend:
        self.sendAll(toSend)

  def sendAll(self, toSend):
    try:
      self.pinger.sendAll(toSend)
    except Exception as e:
      print(e)
      self.lastFailure = datetime.datetime.now().timestamp()
      failureMessage = 'Could not send for the moment Pings :'
      for oneToSend in toSend:
        self.append(oneToSend)
        failureMessage += ('\n\t' + str(oneToSend))
      self.logger.error(failureMessage)


import train_routines

quantity_trains_in_week = 3  #Количество тренировок в неделю(на данный момент работает только для 3 в неделю)
weeks_for_training = 24      #Количество недель для тренировок(от 3 до 24)
weekly_distance = 23         #Километраж прошлой недели
week_number = 24              #Номер недели(для тренировок в первой(базовой фазе работает некорректно))

train_phases = train_routines.calculate_train_phases(weeks_for_training)
weekly_plan = train_routines.create_week_plan(week_number,\
                                              weekly_distance,\
                                              quantity_trains_in_week,\
                                              train_phases)

#В выводе указываются кортежи формата: (дистанция в минутах, отдых в минутах, количество отрезков)
print(weekly_plan)