# ------------------------------------------------------------
# File to save events on date input by user into calendar.txt
# ------------------------------------------------------------

from __future__ import print_function

import datetime
import os.path
import numbers

import time

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 pathlib import Path

# If modifying these scopes, delete the file token.json.
SCOPES = ['https://www.googleapis.com/auth/gmail.modify','https://www.googleapis.com/auth/calendar']

# Month Constant
MONTHS_LENGTH = [31,28,31,30,31,30,31,31,30,31,30,31]
MONTHS_LENGTH_LEAP = [31,29,31,30,31,30,31,31,30,31,30,31]

def main():

    """Shows basic usage of the Google Calendar API.
    Prints the start and name of the next 10 events on the user's calendar.
    """
    os.chdir(str(Path.home()) + "/RustGoogleTUI/RustTUIOUSDC/src/")
    creds = None
    cont = True
    # The file token.json stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.json'):
        creds = Credentials.from_authorized_user_file('token.json', SCOPES)
    # If there are no (valid) credentials available, let the user log in.
    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(
                'client.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.json', 'w') as token:
            token.write(creds.to_json())

    try:
        service = build('calendar', 'v3', credentials=creds)
        output_events(service)

    except HttpError as error:
        print('An error occurred: %s' % error)

# Asks user to input data for a specific date. Will try again if
# input is invalid due to use of other symbols besides numbers or
# date specified is not valid according to the Gregorian Calendar.
# Is used by other functions.
def inputDate():
    fromDate = datetime.datetime.today().astimezone()
    fromDate.replace(hour=0,minute=0,second=0)
    toDate = datetime.datetime(int(fromDate.year),int(fromDate.month),int(fromDate.day),23,59,59).astimezone()

    return fromDate.isoformat(),toDate.isoformat()

# Displays all events that happened on a day as specified by the user.
# Uses function inputDate to get date.
def output_events(service):

    file = open("calendar.txt", "w")

    fromDate,toDate = inputDate()

    events_result = service.events().list(calendarId='primary', timeMin=fromDate,timeMax=toDate,
                                            singleEvents=True,orderBy='startTime').execute()
    events = events_result.get('items', [])

    if not events:
        file.write('|No upcoming events found.|\n')
        return

    # Prints the start and name of the next 10 events
    for event in events:
        start = event['start'].get('dateTime', event['start'].get('date'))
        file.write(event['summary'] + "|" + start + "|\n")

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

""" The basic plan:

1. Due to memory constraints, train up a model one day at a time.
2. Load up one day's data. Use online training with xgboost to update the model.
3. Validate using the final month's worth of data.

"""

import glob
import re

import matplotlib
matplotlib.use("agg")
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

import xgboost as xgb

# I am trying something weird with loss functions here as I am not sure
# how to do this! The idea is that I replace the +/- with a 1/0 loss function
# and then weight according to the weightings.
def load_day(day_number, filename_ds):
    """ Load up a CSV for a given day.

    Days run from 0.

    """

    example_filename = filename_ds.loc[filename_ds.date_number==day_number].filename.to_numpy()[0]
    this_ds = pd.read_csv(example_filename).sort_values(["date", "ts_id"])

    this_ds["good_trade"] = ((this_ds.resp * this_ds.weight) > 0.0).astype(np.int)
    this_ds["trade_weight"] = (this_ds.resp * this_ds.weight).abs()
    this_ds["trade_value"] = this_ds.resp * this_ds.weight

    return this_ds

# First up - data load.
# The files have been split into one day / file chunks.
day_files = [day_file for day_file in glob.glob("data/splitfiles/day*.csv")]
day_file_numbers = [(int(re.search("\d+", day_file).group(0)), day_file)
                    for day_file in day_files]
day_file_numbers.sort(key=lambda x: x[0])
day_file_numbers = pd.DataFrame(day_file_numbers, columns=["date_number", "filename"])

# Load the features and example testing data
features = pd.read_csv("data/features.csv")
example_test = pd.read_csv("data/example_test.csv")

# We'll do a 80% train/validation split
train_split = 400
day_file_numbers["train"] = day_file_numbers.date_number < train_split

# Do some data analysis, because this data is all pretty weird.
first_day = load_day(0, day_file_numbers)

# Look at histograms of weights and responses
_, ax = plt.subplots(figsize=(16, 9))
ax.hist(first_day.weight)
plt.savefig("weight_histogram.png")

_, ax = plt.subplots(figsize=(16, 9))
ax.hist(first_day.resp)
plt.savefig("response_histogram.png")

# Plan: train a model for the first day. Then, for every other day we just nudge it.
num_trees = 50
params = {"booster": "gbtree",
          "eta": 0.5,
          "gamma": 2.0,
          "max_depth": 6,
          "lambda": 1.1,
          "colsample_bytree": 0.75,
          "process_type": "default",
          "objective": "reg:squarederror"}

# Now, we begin a training loop. One day at a time.
# There are 130 feature columns
num_rounds = 250
early_stopping = 10
feature_cols = ["feature_{}".format(i) for i in range(130)]

# Maybe I want this multiple times?
first_day = True
for day_number in day_file_numbers.loc[day_file_numbers.train].date_number:
    print("processing day: {}".format(day_number+1))

    # Once we move to day 1, update rather than build new model.
    if not first_day:
        params["process_type"] = "update"
        params["updater"] = "refresh"
        params["refresh_leaf"] = 1
        params["eta"] = 0.1

    # Grab a random day to test against (this is going to get weird)
    test_day = day_file_numbers.loc[~day_file_numbers.train].date_number.sample()

    train_data = load_day(day_number, day_file_numbers)
    test_data = load_day(test_day.to_numpy()[0], day_file_numbers)

    dtrain = xgb.DMatrix(train_data[feature_cols],
                         label=train_data.trade_value)

    dvalid = xgb.DMatrix(test_data[feature_cols],
                         label=test_data.trade_value)

    evallist = [(dvalid, "eval"), (dtrain, "train")]

    if first_day:
        # TB NOTE: Don't do early stopping, I want all the trees.
        bst = xgb.train(params, dtrain, num_rounds, evallist)
    else:
        bst= xgb.train(params, dtrain, num_rounds, evallist,
                       xgb_model=bst, early_stopping_rounds=early_stopping)

    first_day = False

# Predict on the output
dtest = xgb.DMatrix(example_test[feature_cols])
example_test["results"] = bst.predict(dtest)

example_test["output"] = example_test.results > 0.0


import pygame
from pygame.draw import *
import colors as cl

pygame.init()
win = pygame.display.set_mode((500, 500))

x = 50
y = 50
width = 40
height = 60
speed = 5
isJump = False
Jumpcount = 10

run = True
while run:
    pygame.time.delay(50)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT] and x >= 5:
        x -= speed
    if keys[pygame.K_RIGHT] and x < 500 - width - 5:
        x += speed
    if keys[pygame.K_UP] and y >= 5:
        y -= speed
    if keys[pygame.K_DOWN] and y < 500 - height - 5:
        y += speed
    if keys[pygame.K_SPACE]:
        isJump is True

    win.fill(cl.black)
    rect(win, cl.blue, (x, y, width, height))
    pygame.display.update()

pygame.quit()


from django.core.cache import cache
from django.shortcuts import render, get_object_or_404
from django_redis import get_redis_connection

from .models import Image

# Create your views here.

con = get_redis_connection("default")

def index(request):
    query = Image.objects.all()
    images_seq = [
        {'id': data.id,
         'Url': data.url,
         'CreateDate': data.create_date}
        for data in query
    ]

    cache.get_or_set('click', 0, timeout=None)
    total_views = cache.incr('click')

    rank = con.zrevrange(name='images', start=0, end=9, withscores=True, score_cast_func=int)
    rank_seq = [
        {"url": str(r[0], 'utf-8'),
         "value": r[1]}
        for r in rank
    ]

    return render(request, 'images/index.html', {
        'images': images_seq,
        'total_views': total_views,
        'ranks': rank_seq,
    })

def detail(request, image_id):
    image = get_object_or_404(Image, id=image_id)
    total_views = con.zincrby(name='images', amount=1 ,value=image.url)
    return render(request,
                  'images/detail.html', {
                      'image': image,
                      'total_views': int(total_views)
                  })


import random

def loe_failist(fail:str)->list:

    f=open(fail,"r",encoding="utf-8-sig")
    jarjend=[]
    for rida in f:
        jarjend.append(rida.strip())
    f.close()
    return jarjend

def kirjuta_failist(fail:str,jarjend:list):
    f=open(fail,"w",encoding="utf-8-sig")
    for line in jarjend:
        f.write(line+"\n")
    f.close

def text_est_v_text_rus(text:str, text_est:list, text_rus:list):
    if text in text_est:
        ind=text_est.index(text)

    return text_rus[ind]

def rus_na_est(text:str, text_est:list,  text_rus:list ):
    if text in  text_rus:
        ind =  text_rus.index(text)

    return text_est[ind]

def text_ap(text:str, text_est:list, text_rus:list):

        if text not in  text_est:
            text_est.append(text)
            print()
        j=input("Обозначение этого слова на русском: ")
        text_rus.append(j)
        kirjuta_failist('est.txt', text_est)
        kirjuta_failist('rus.txt', text_rus)
        return  j

def correct_word(text:str,text_est:list,text_rus:list):

    if text in text_rus:
       index = text_rus.index(text)
       text = input("Введите слово для исправления: ")
       new_translation = input(f"Введите новое значение для слова '{text}': ")
       text_est[index] = new_translation
       print("Слово успешно исправлено!")

    elif text in text_est:
         index=text_est.index(text)
         text = input("Введите слово для исправления: ")
         new_translation = input(f"Введите новое значение для слова '{text}': ")
         text_rus[index] = new_translation
         print("Слово успешно исправлено!")

    else:
        print("Такого слова нету в словаре")

def teadmiste_kontroll(text_rus:list,text_est:list):

    p=0
    kokku=int(input("Mitu küsimust? "))
    for i in range(kokku):
        järjend=random.choice([text_rus,text_est])
        sõna=random.choice(järjend)
        print(f"{sõna} - ",end="")
        tõlke=input()
        if sõna in text_rus:
           i=text_rus.index(sõna)
           tõlke_kontroll=text_est[i]
        elif sõna in text_est:
            i=text_est.index(sõna)
            tõlke_kontroll=text_rus[i]
        if tõlke==tõlke_kontroll:
            p+=1
        if (p/kokku)*100>90:
            hinne=5
        elif (p/kokku)*100>75:
            hinne=4
        elif (p/kokku)*100>60:
            hinne=3
        else:
            hinne="Väga halb"
            print("Õige")
            return hinne
    else:
         print("Vale")
    if (p/kokku)*100>90:
        hinne=5
    elif (p/kokku)*100>75:
        hinne=4
    elif (p/kokku)*100>60:
        hinne=3
    else:
         hinne="Väga halb"
    return hinne

#def text_est_in_text_rus(text, te_est, te_rus):
#    if text in te_est:
#        index = te_est.index(text)
#        return te_rus[index]
#    else:
#        return None

#def loe_failist(fail:str)->list:
#    """
#    """
#    f=open(fail,"r",encoding="utf-8-sig")
#    jarjend=[]
#    for rida in f:
#        jarjend.append(rida.strip())
#    f.close()
#    return jarjend

#def kirjuta_failist(fail:str,jarjend:list):
#    f=open(fail,"w",encoding="utf-8-sig")
#    for line in jarjend:
#        f.write(line+"\n")
#    f.close

#from gtts import gTTS
#import os
#def Heli(tekst:str,keel:str):
#    obj=gTTS(text=tekst,lang=keel,slow=False).save("Heli.mp3")
#    os.system("Heli.mp3")

#def number(nimi:str):
#    tähestik = {
#        "а": 1, "б": 2, "в": 3, "г": 4, "д": 5, "е": 6, "ё": 7, "ж": 8, "з": 9,
#        "и": 1, "й": 2, "к": 3, "л": 4, "м": 5, "н": 6, "о": 7, "п": 8, "р": 9,
#        "с": 1, "т": 2, "у": 3, "ф": 4, "х": 5, "ц": 6, "ч": 7, "ш": 8, "щ": 9,
#        "ъ": 1, "ы": 2, "ь": 3, "э": 4, "ю": 5, "я": 6,

#        "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6, "g": 7, "h": 8, "i": 9,
#        "j": 1, "k": 2, "l": 3, "m": 4, "n": 5, "o": 6, "p": 7, "q": 8, "r": 9,
#        "s": 1, "t": 2, "u": 3, "v": 4, "w": 5, "x": 6, "y": 7, "z": 8 }

#    x = "ru"   # tähestiku määratlus
#    for f in nimi:
#        if f.isalpha():
#            if f.lower() in tähestik:
#                x = "ru"
#            elif f.lower() in tähestik.values():
#                x = "eng"
#            break

#    numder_nimi = 0  # nimenumbri arvutamine
#    for f in nimi:
#        if f.isalpha():
#            numder_nimi+=tähestik[f.lower()]

#    if  numder_nimi > 9:
#        numbrid = [int(numbri) for numbri in str(numder_nimi)] #teisendab numder_nimi numbrite loendiks.
#        numder_nimi = sum(numbrid)

#    return numder_nimi


from datetime import datetime

class Greeter:
  def __init__(self, name, store) -> None:
    self.name = name
    self.store = store

  def _day(self):
    return datetime.now().strftime('%A')

  def _part_of_day(self):
    hour = datetime.now().hour
    if (hour < 12):
      return 'Morning'
    elif (hour < 17):
      return 'Afternoon'
    else:
      return 'Evening'

  def greet(self):
    print(f'Hi, I am {self.name}, and welcome to {self.store}')
    print(f'How\'s your {self._day()} {self._part_of_day()} going?')
    print('Hope you are doing well!')

greeter = Greeter('Yen', 'Crab Soup')
greeter.greet()


home = False
try:
    import RPi.GPIO as GPIO
    home = True
except:
    home = False

if home:
    isikPin = 0
    kapiPin = 0
    pencerePin = 0
    klimaPin = 0

    GPIO.cleanup()  # Giriş çıkış pinlerinin verilerini sıfırladık
    GPIO.setmode(GPIO.BCM)  # BCM pin dizilimini seçtik

    GPIO.setup(isikPin, GPIO.OUT)  # Pini çıkış pini olarak tanımladık
    GPIO.setup(kapiPin, GPIO.OUT)
    GPIO.setup(pencerePin, GPIO.OUT)
    GPIO.setup(klimaPin, GPIO.OUT)

class Kontrol:

    @staticmethod
    def isikKontrol(durum: bool):
        # Pini HIGH veya LOW yani lojik 1 veya 0 olmasını amaçladık
        if home:
            GPIO.output(isikPin, durum)
        else:
            print("isik kontrol", durum)

    @staticmethod
    def kapiKontrol(durum: bool):
        if home:
            GPIO.output(kapiPin, durum)
        else:
            print("kapi kontrol", durum)

    @staticmethod
    def pencereKontrol(durum: bool):
        if home:
            GPIO.output(pencerePin, durum)
        else:
            print("pencere kontrol", durum)

    @staticmethod
    def klimaKontrol(durum: bool):
        if home:
            GPIO.output(klimaPin, durum)
        else:
            print("klima kontrol", durum)


# Operador AND en ( P  q ) si p es False entonces (p  q) es falso si o si
# Operador OR em ( p v q) si p es True entonces (p v q) es verdaddero si o si
# Operador NOT
# Ejercicio Condicional simple

nom = input("Nombre del empleado: ")
salario = int(input("Ingrese salario del empleado: "))

if salario <= 1_200_000:
    aux = 120_000
else:
    aux = 0

print("Nombre:", nom)
print(f"Salario:${salario:,.0f}")
print(f"Auxilio de transporte:${aux:,.0f}")


import ast
from dataclasses import dataclass
from pathlib import Path

from sphinx.application import Sphinx
from sphinx.util.logging import getLogger

logger = getLogger(__name__)

@dataclass
class Example:
    path: Path
    source_folder: Path
    name: str = ""
    reference: str = ""
    summary: str = ""
    category: str = ""

    def __post_init__(self) -> None:
        self.name = self.path.name
        has_subdir = len(self.path.relative_to(self.source_folder.parent).parts) > 2
        if has_subdir:
            self.reference = f"{self.path.parts[-2]}-{self.path.stem}"
            self.category = self.path.parts[-2]
        else:
            self.reference = self.path.stem

        self.reference = self.reference.replace("_", "-").replace(" ", "")

@dataclass
class PythonExample(Example):
    def __post_init__(self) -> None:
        super().__post_init__()

        mod = ast.parse(self.path.read_bytes())
        doc = ""
        for node in mod.body:
            if isinstance(node, ast.Expr) and isinstance(node.value, ast.Str):
                doc = node.value.s.strip().split("\n\n")[0].strip()
                if not doc.endswith("."):
                    doc += "."
                break
        self.summary = doc

def md_generator(extension: str, app: Sphinx, source_folder: Path) -> list[Example]:
    examples: list[Example] = []
    for ff in source_folder.rglob(extension):
        pth = ff.relative_to(app.srcdir)
        if " " in str(pth):
            logger.warning(
                f"The example '{pth!s}' has a space in the "
                "pathname which is not yet supported."
            )
            continue
        if ff.suffix == ".py":
            example = PythonExample(ff, source_folder)
        else:
            example = Example(ff, source_folder)  # type: ignore
        examples.append(example)
        # md_file = ff.with_suffix(".md")
        # md_file.write_text(
        #     dedent(
        #         f"""\
        #         ---
        #         orphan: true
        #         ---
        #         ({example.reference})=
        #         # {example.name}

        #         [**Source**]({ff.name})

        #         :::{{literalinclude}} {ff.name}
        #         :::
        #         """
        #     )
        # )
    return examples


"""
基本种类:
:: EVENT [WIDGET]      | 一般在文件开头

<<WIDGET_1>>ANY<</WIDGET_1>>   | 有闭合的
<<WIDGET_0>>                | 无闭合的
<<WIDGET "TAG">>            | 特殊名称
<<WIDGET COND>>             | 条件，如 if / link 等

特殊:
<<if>>ANY<<elseif>>ANY<<else>>ANY<</if>>

<<switch>>ANY<<case>>ANY<</switch>>

<<link [[TEXT]]>></link<>>
<<link [[TEXT|EVENT]]>></link<>>

<<set $VAR to KEYWORD>>
<<set $VAR to "VAR">>
<<set $VAR to "STRING">>

$VAR                | 变量
$VAR.FUNC(PARAM)    | 调用函数
$VAR.PROP           | 属性

STRING                  | 文本
<CHAR_1>ANY</CHAR_1>    | 有闭合的
<CHAR_0>                | 无闭合的

TEXT

//COMMENT       | 注释
/*COMMENT*/     | 注释(可跨行)
    /* COMMENT
     * COMMENT
     * COMMENT */
  | 注释(可跨行)

要翻译的：
TEXT, STRING
"""
import asyncio
import time

from src import (
    logger,
    Paratranz,
    ProjectDOL,
    PARATRANZ_TOKEN
)

async def main():
    start = time.time()
    # =====
    dol = ProjectDOL(type_="common")  # 改成 “dev” 则下载最新开发版分支的内容
    pt = Paratranz()
    if not PARATRANZ_TOKEN:
        logger.error("未填写 PARATRANZ_TOKEN, 汉化包下载可能失败，请前往 https://paratranz.cn/users/my 的设置栏中查看自己的 token, 并在 src/consts.py 中填写\n")
        return

    """ 删库跑路 """
    await dol.drop_all_dirs()

    """ 获取最新版本 """
    await dol.fetch_latest_version()

    """ 提取键值 """
    await dol.download_from_gitgud()
    await dol.create_dicts()

    """ 更新导出的字典 成品在 `raw_dicts` 文件夹里 """
    download_flag = await pt.download_from_paratranz()  # 如果下载，需要在 consts 里填上管理员的 token, 在网站个人设置里找
    if not download_flag:
        return
    await dol.update_dicts()

    """ 覆写汉化 用的是 `paratranz` 文件夹里的内容覆写 """
    await dol.apply_dicts()

    """ 编译成游戏 """
    dol.compile()
    dol.run()
    # =====
    end = time.time()
    return end-start

if __name__ == '__main__':
    last = asyncio.run(main())
    logger.info(f"===== 总耗时 {last or -1}s =====")


import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split

class Preprocessing:
    df = pd.read_csv('ce889_dataCollection.csv',header = None)
    # for dropping the duplicates
    df.drop_duplicates(inplace = True)
    # checking for null values
    print("Checking For Null values", df.isnull().sum())
    # Giving column names
    df.columns = ["X distance to target","Y distance to target","New Vel Y","New Vel X"]
    # normalization
    data_min = df.min()
    data_max = df.max()
    normalizeddata = (df - df.min()) / (df.max() - df.min())
    # spliting data
    training , testing= train_test_split(normalizeddata, test_size = 0.2)
    print("Shape of Training Data", training.shape)
    print("Shape of Testing Data", testing.shape)
    # Splitting inputs & outputs for training, validation & testing data
    x_train_input = np.array(training[["X distance to target","Y distance to target"]]).T
    y_train_output = np.array(training[["New Vel Y","New Vel X"]]).T

    x_testing_input = np.array(testing[["X distance to target","Y distance to target"]]).T
    y_testing_output = np.array(testing[["New Vel Y","New Vel X"]]).T

Rocket Landing Neural Netwotk/Neural Network Python Code/Data_Preprocessing.py


import ast
import importlib
import json

import databases
import tenacity

from _clients.participants import ledger
from _utils import db_utils, utils
import os
import signal

class Participant:
    """
    Participant is the interface layer between local resources and the Market
    """
    def __init__(self, sio_client, participant_id, market_id, db_path, trader_params, storage_params, **kwargs):
        # Initialize participant variables
        self.server_online = False
        self.run = True
        self.market_id = market_id
        self.market_connected = False
        self.participant_id = str(participant_id)
        self.__client = sio_client
        self.client = sio_client
        self.__profile = {
            'db_path': db_path
        }

        # Initialize market variables
        self.__ledger = ledger.Ledger(self.participant_id)
        self.__extra_transactions = {}
        self.__market_info = {}
        self.__meter = {}
        self.__timing = {}

        # Initialize trader variables and functions
        trader_params = json.loads(trader_params)
        trader_fns = {
            'id': self.participant_id,
            'timing': self.__timing,
            'ledger': self.__ledger,
            'extra_transactions': self.__extra_transactions,
            'market_info': self.__market_info,
            'read_profile': self.__read_profile,
            'get_profile_stats': self.__get_profile_stats,
            'meter': self.__meter
        }

        if storage_params:
            storage_params = json.loads(storage_params)
            storage_type = storage_params.pop('type', None)
            # self.storage_fns = {
            #     'id': self.participant_id,
            #     'timing': self.__timing
            # }
            self.storage = importlib.import_module('_devices.' + storage_type).Storage(**storage_params)
            self.storage.timing = self.__timing
            trader_fns['storage'] = {
                'info': self.storage.get_info,
                'check_schedule': self.storage.check_schedule,
                # 'schedule_energy': self.storage.schedule_energy
            }

        trader_type = trader_params.pop('type', None)
        if trader_type == 'remote_agent':
            trader_fns['emit'] = self.__client.emit
        Trader = importlib.import_module('_agent.traders.' + trader_type).Trader
        self.trader = Trader(trader_fns=trader_fns, **trader_params)

        self.__profile_params = {
            'generation_scale': kwargs['generation_scale'] if 'generation_scale' in kwargs else 1,
            'load_scale': kwargs['load_scale'] if 'load_scale' in kwargs else 1
        }
        synthetic_profile = trader_params.pop('use_synthetic_profile', None)
        if synthetic_profile:
            self.__profile_params['synthetic_profile'] = synthetic_profile

        # if 'market_ns' in kwargs:
        #     NSMarket = importlib.import_module(kwargs['market_ns']).NSMarket
            # self.__client.register_namespace(NSMarket(self))

    async def delay(self, s):
        await self.__client.sleep(s)

    # async def disconnect(self):
    #     '''
    #     This method disconnects the client from the server
    #     '''
    #     await self.__client.disconnect()

    async def open_db(self, db_path):
        """Opens connection to the database where load and generation profiles are stored.
        Also stores references to the database object and the table object

        Args:
            db_path ([type]): [description]
        """
        self.__profile['db_path'] = db_path
        self.__profile['db'] = databases.Database(db_path)
        profile_name = self.__profile_params['synthetic_profile'] if 'synthetic_profile' in self.__profile_params\
            else self.participant_id
        self.__profile['name'] = profile_name
        self.__profile['db_table'] = db_utils.get_table(db_path, profile_name)
        if 'db_table' in self.__profile or self.__profile['db_table'] is not None:
            await self.__profile['db'].connect()

    async def __get_profile_stats(self):
        """reads and returns pre-calculated profile statistics for calculating Z scores, if available.
        """
        db = self.__profile['db']
        table = db_utils.get_table(self.__profile['db_path'], "_statistics")
        query = table.select().where(table.c.name == self.__profile['name'])
        # async with db.transaction():
        row = await db.fetch_one(query)
        if row is not None:
            return dict(row)
        return None

    async def open_profile_db(self):
        await self.open_db(self.__profile['db_path'])
        # await self.get_profile_stats(self.__profile['db_path'])

    async def join_market(self):
        """Emits event to join a Market
        """
        client_data = {
            'type': ('participant', 'Residential'),
            'id': self.participant_id,
            'market_id': self.market_id
        }
        await self.__client.emit('join_market', client_data, callback=self.register_success)

    # Continuously attempt to join server
    async def register_success(self, success):
        if not success:
            # self.__profiles_available()
            await self.delay(3)
            await self.join_market()
        self.busy = False

    async def update_extra_transactions(self, message):
        time_delivery = tuple(message.pop('time_delivery'))
        self.__ledger.extra[time_delivery] = message
        self.__extra_transactions.clear()
        self.__extra_transactions.update(message)

    @tenacity.retry(wait=tenacity.wait_random(0, 3))
    async def bid(self, time_delivery=None, **kwargs):
        """Submit a bid

        Args:
            time_delivery ([type], optional): [description]. Defaults to None.
        """

        # quantity is energy in Wh
        # price is $/kWh
        if time_delivery is None:
            time_delivery = self.__timing['next_settle']

        bid_entry = {
            'participant_id': self.participant_id,
            'quantity': kwargs['quantity'],  # Wh
            'price': kwargs['price'],  # $/kWh
            'time_delivery': time_delivery
        }
        # print('bidding', self.trader.is_learner, self.__timing, bid_entry)
        await self.__client.emit('bid', bid_entry)

    @tenacity.retry(wait=tenacity.wait_random(0, 3))
    async def ask(self, time_delivery=None, **kwargs):
        """Submit an ask

        Args:
            time_delivery ([type], optional): [description]. Defaults to None.
        """
        # quantity is energy in Wh
        # price is $/kWh
        if time_delivery is None:
            time_delivery = self.__timing['next_settle']

        ask_entry = {
            'participant_id': self.participant_id,
            'quantity': kwargs['quantity'],  # Wh
            'price': kwargs['price'],  # $/kWh
            'source': kwargs['source'],
            'time_delivery': time_delivery
        }
        await self.__client.emit('ask', ask_entry)

    async def ask_success(self, message):
        await self.__ledger.ask_success(message)

    async def bid_success(self, message):
        await self.__ledger.bid_success(message)

    async def settle_success(self, message):
        await self.__ledger.settle_success(message)
        return message['commit_id']

    async def __update_time(self, message):
        # synchronizes time with market
        duration = message['duration']
        start_time = message['time']
        self.__timing.update({
            'timezone': message['timezone'],
            'duration': duration,
            'last_round': tuple(message['last_round']),
            'current_round': tuple(message['current_round']),
            'last_settle': tuple(message['last_settle']),
            'next_settle': tuple(message['next_settle']),
            'stale_round': (start_time - duration * 10, start_time - duration * 9)
        })

    async def start_round(self, message):
        """Sequence of actions during each round
        Currently only for simulation mode.
        Real time mode needs slight modifications.

        Args:
            message ([type]): [description]
        """
        # start of current time step
        await self.__update_time(message)
        self.__market_info.update(message['market_info'])
        await self.__ledger.clear_history(self.__timing['stale_round'])
        self.__market_info.pop(str(self.__timing['stale_round']), None)
        # print(self.__market_info)
        # agent_act tells what actions controller should perform
        # controller should perform those actions accordingly, but will have the option not to
        next_actions = await self.trader.step()
        # next_actions = await self.trader.act()
        await self.__take_actions(next_actions)
        # await self.trader.learn()
        if hasattr(self, 'storage'):
            await self.storage.step()

        # metering energy should happen right at the end of the current round for maximum accuracy
        # in real-time mode there would have to be a timeout function
        # this is currently OK for simulation mode
        await self.__meter_energy(self.__timing['current_round'])
        # await self.__client.emit('end_turn', namespace='/market')
        await self.__client.emit('end_turn')

    async def __read_profile(self, time_interval):
        """Fetches energy profile for one timestamp from database

        Args:
            time_interval ([type]): [description]

        Returns:
            [type]: [description]
        """
        db = self.__profile['db']
        table = self.__profile['db_table']
        # query = table.select().where(table.c.tstamp == time_interval[1])
        query = table.select().where(table.c.time == time_interval[1])
        async with db.transaction():
            row = await db.fetch_one(query)
        return utils.process_profile(row=row,
                                     gen_scale=self.__profile_params['generation_scale'],
                                     load_scale=self.__profile_params['load_scale'])

    # def __process_profile(self, row):
    #     """Processes raw readings fetches from database into generation and consumption in integer Wh.
    #
    #     Also scales if scaling is defined in configuration.
    #     Right now the format is for eGauge. Functionality will be expanded as more data sources are introduced.
    #
    #     Args:
    #         row ([type]): [description]
    #
    #     Returns:
    #         [type]: [description]
    #     """
    #
    #     if row is not None:
    #         consumption = int(round(self.__profile_params['load_scale'] * (row['grid'] + row['solar+']), 0))
    #         generation = int(round(self.__profile_params['generation_scale'] * row['solar+'], 0))
    #         return generation, consumption
    #     return 0, 0

    async def __meter_energy(self, time_interval):
        """Sends submetering data to the Market

        In simulation mode, the data is sent at the end of the current step
        In real-time mode, the data is sent at the beginning of the next step

        Args:
            time_interval ([type]): [description]

        Returns:
            [type]: [description]
        """

        if not self.server_online:
            return False

        if not self.market_connected:
            return False

        self.__meter = await self.__allocate_energy(time_interval)
        await self.__client.emit('meter_data', self.__meter)
        return True

    async def __allocate_energy(self, time_interval):
        """
        This function performs virtual sub metering.
        energy generated is allocated to sources by priority:
        1. settlements
        2. self consumption
        battery, then
        other loads
        3. grid
        """

        self.__timing['last_deliver'] = time_interval
        meter = {
            'time_interval': time_interval,

            # generation is NET from each source
            # self consumed energy are allocated to consumption
            # this makes market code more efficient
            'generation': {
                'solar': 0,
                'bess': 0
            },
            'consumption': {
                # consumption keeps track of self consumption by source
                # other denotes energy flowing in from the outside
                'bess': {
                    'solar': 0  # solar from self
                },
                'other': {
                    'solar': 0,  # solar from self
                    'bess': 0,  # bess from self
                    'external': 0
                }
            }
        }

        # step 1. gather settlements
        settled_solar = 0
        settled_bess = 0
        if time_interval in self.__ledger.settled:
            asks = self.__ledger.settled[time_interval]['asks']

            for ask in asks.values():
                if ask['source'] == 'solar':
                    settled_solar += ask['quantity']
                if ask['source'] == 'bess':
                    settled_bess += ask['quantity']

        # step 2. get battery activity
        bess_charge = 0
        bess_discharge = 0

        if hasattr(self, 'storage'):
            # bess_activity = self.storage.last_activity
            bess_activity = await self.storage.check_schedule(time_interval)
            bess_activity = bess_activity[time_interval]['energy_scheduled']
            bess_charge = bess_activity if bess_activity > 0 else 0
            bess_discharge = -bess_activity if bess_activity < 0 else 0

        # step 3. get readings from meter (profile)
        solar_generation, residual_consumption = await self.__read_profile(time_interval)

        # step 4. allocate energy
        # use solar for settlement
        residual_solar = max(0, solar_generation - settled_solar)
        if residual_solar == 0:
            meter['generation']['solar'] += solar_generation
        else:
            meter['generation']['solar'] += settled_solar

        # use residual solar to charge battery (if battery was charged)
        if residual_solar > 0 and bess_charge > 0:
            if residual_solar <= bess_charge:
                meter['consumption']['bess']['solar'] += residual_solar
                bess_charge -= residual_solar
                residual_solar -= residual_solar
            elif residual_solar > bess_charge:
                meter['consumption']['bess']['solar'] += bess_charge
                residual_solar -= bess_charge
                bess_charge -= bess_charge

        # use residual solar for other loads
        if residual_solar > 0:
            if residual_solar <= residual_consumption:
                meter['consumption']['other']['solar'] += residual_solar
                residual_consumption -= residual_solar
                residual_solar -= residual_solar
            elif residual_solar > residual_consumption:
                meter['consumption']['other']['solar'] += residual_consumption
                residual_solar -= residual_consumption
                residual_consumption -= residual_consumption

        # if battery was discharged
        if bess_discharge > 0:
            if bess_discharge <= residual_consumption:
                meter['consumption']['other']['bess'] += bess_discharge
                residual_consumption -= bess_discharge
                bess_discharge -= bess_discharge
            elif bess_discharge > residual_consumption:
                meter['consumption']['other']['bess'] += residual_consumption
                bess_discharge -= residual_consumption
                residual_consumption -= residual_consumption

        meter['generation']['solar'] += residual_solar
        meter['generation']['bess'] += bess_discharge
        meter['consumption']['other']['external'] += residual_consumption
        meter['consumption']['other']['external'] += bess_charge

        return meter

    async def __take_actions(self, actions):
        """Processes the actions given by the agent

        Args:
            actions ([type]): [description]
        """
        # actions must come in the following format:
        # actions = {
        #     'bess': {
        #         time_interval: scheduled_qty
        #     },
        #     'bids': {
        #         time_interval: {
        #             'quantity': qty,
        #             'price': dollar_per_kWh
        #         }
        #     },
        #     'asks' {
        #         source: {
        #             time_interval: {
        #                 'quantity': qty,
        #                 'price': dollar_per_kWh?
        #             }
        #         }
        #     }
        # }

        # Battery charging or discharging action
        if 'bess' in actions and hasattr(self, 'storage'):
            for time_interval in actions['bess']:
                await self.storage.schedule_energy(actions['bess'][time_interval], ast.literal_eval(time_interval))
        # Bid for energy
        if 'bids' in actions:
            for time_interval in actions['bids']:
                quantity = actions['bids'][time_interval]['quantity']
                price = round(actions['bids'][time_interval]['price'], 4)
                await self.bid(quantity=quantity,
                               price=price,
                               time_delivery=ast.literal_eval(time_interval))
        # Ask to sell energy
        if 'asks' in actions:
            for source in actions['asks']:
                for time_interval in actions['asks'][source]:
                    quantity = actions['asks'][source][time_interval]['quantity']
                    price = round(actions['asks'][source][time_interval]['price'], 4)
                    await self.ask(quantity=quantity,
                                   price=price,
                                   source=source,
                                   time_delivery=ast.literal_eval(time_interval))

    def reset(self):
        self.__ledger.reset()
        self.__extra_transactions.clear()
        self.__market_info.clear()
        self.__meter.clear()
        self.__timing.clear()

    # Keep participant connected to server
    async def ping(self):
        while self.run:
            await self.delay(10)
            if self.server_online:
                await self.__client.emit('ping')
            continue
        await self.__client.sleep(5)
        await self.__client.disconnect()
        os.kill(os.getpid(), signal.SIGINT)
        # raise SystemExit

# import socketio
# class NSMarket(socketio.AsyncClientNamespace):
#     def __init__(self, participant):
#         super().__init__(namespace='/market')
#         self.participant = participant
#
#     # async def on_connect(self):
#     #     await self.participant.join_market()
#
#     # async def on_disconnect(self):
#     #     pass
#
#     async def on_re_register_participant(self, message):
#         await self.participant.join_market()
#
#     async def on_update_market_info(self, market_id):
#         if market_id == self.participant.market_id:
#             self.participant.market_connected = True
#
#     async def on_start_round(self, message):
#         await self.participant.start_round(message)
#
#     async def on_ask_success(self, message):
#         await self.participant.ask_success(message)
#
#     async def on_bid_success(self, message):
#         await self.participant.bid_success(message)
#
#     async def on_settled(self, message):
#         return await self.participant.settle_success(message)
#
#     async def on_return_extra_transactions(self, message):
#         await self.participant.update_extra_transactions(message)
#
# if __name__ == '__main__':
#     pass


# Import numpy
import numpy as np

# Import matplotlib
import matplotlib.pylab as plt

# Configure
plt.rcParams['xtick.direction'] = 'out'
plt.rcParams['ytick.direction'] = 'out'

# Optionally set font to Computer Modern to avoid common missing font errors
params = {
  'axes.labelsize': 24,
  'legend.fontsize': 14,
  'xtick.labelsize': 24,
  'ytick.labelsize': 24,
  'text.usetex': True}
plt.rcParams.update(params)

# Latex math
plt.rcParams['text.latex.preamble'] = [r'\usepackage{sfmath}']
plt.rcParams['font.family'] = 'sans-serif'
# plt.rcParams['font.sans-serif'] = 'courier'
plt.rcParams['font.size'] = 18
plt.rcParams['font.weight'] = 'bold'
plt.rcParams['lines.linewidth'] = 4
plt.rcParams['lines.color'] = 'r'

# Make sure everything is within the frame
plt.rcParams.update({'figure.autolayout': True})

# Set marker size
markerSize = 11.0

# bar chart settings
alpha = 0.8

# These are the "Tableau 20" colors as RGB.
tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
             (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
             (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
             (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
             (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]

# Scale the RGB values to the [0, 1] range, which is the format matplotlib accepts.
for i in range(len(tableau20)):
    r, g, b = tableau20[i]
    tableau20[i] = (r / 255., g / 255., b / 255.)

mevery = 3

class PostOpt:
    """
    Class to handle plotting
    """
    @staticmethod
    def plot_solution(data1, data2, name):
        plt.figure()
        fig, ax = plt.subplots()

        # remove the upper and right borders
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)

        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')

        ax.plot(data1[:,0], data1[:,1], '-D', label='(a) cg',
                     ms=markerSize, mec='black', color=tableau20[0], markevery=mevery,
                     alpha=alpha)
        ax.plot(data1[:,0], data1[:,2], '-v', label='(a) pcg',
                     ms=markerSize, mec='black', color=tableau20[0], markevery=mevery,
                     alpha=alpha)
        ax.plot(data1[:,0], data1[:,3], '-*', label='(a) exact',
                     ms=markerSize, mec='black', color=tableau20[0], markevery=mevery,
                     alpha=alpha)

        ax.plot(data2[:,0], data2[:,1], '-D', label='(b) cg',
                     ms=markerSize, mec='black', color=tableau20[2], markevery=mevery,
                     alpha=alpha)
        ax.plot(data2[:,0], data2[:,2], '-v', label='(b) pcg',
                     ms=markerSize, mec='black', color=tableau20[2], markevery=mevery,
                     alpha=alpha)
        ax.plot(data2[:,0], data2[:,3], '-*', label='(b) exact',
                     ms=markerSize, mec='black', color=tableau20[2], markevery=mevery,
                     alpha=alpha)

        ax.set_ylabel('Solution u(x)')
        ax.set_xlabel('Domain x')
        #niters_labl = [1, 20, 40, 60, 80, 100]
        #ax.set_yticks(np.logspace(-5, 0, 6, endpoint=True))
        #ax.set_yticks(np.linspace(0, 1, 5, endpoint=True, dtype=np.int))
        ax.set_yticks(np.linspace(0, 1.5, 4, endpoint=True))
        ax.legend(loc='lower left', framealpha=0.0)

        plt.savefig(name, bbox_inches='tight', pad_inches=0.05)

        return

if __name__ == "__main__":

    inpFile = open("dirichlet.dat", "r")
    fdirichlet = list(inpFile.readlines())
    inpFile.close()

    inpFile = open("mixed.dat", "r")
    fmixed = list(inpFile.readlines())
    inpFile.close()

    soldirichlet = []
    for line in fdirichlet:
        entry = line.split()
        soldirichlet.append([float(entry[0]),
                             float(entry[1]),
                             float(entry[2]),
                             float(entry[3])])
    soldirichlet = np.array(soldirichlet)

    solmixed = []
    for line in fmixed:
        entry = line.split()
        solmixed.append([float(entry[0]), float(entry[1]), float(entry[2]), float(entry[3])])
    solmixed = np.array(solmixed)

    # Plot the solution in the profile
    PostOpt.plot_solution(soldirichlet, solmixed, "profile.pdf")


"""Copy all orginal screenings to a new directory."""

import re
import glob
import shutil
import numpy as np
from PIL import Image
from utils import colorize

import os
from joblib import Parallel, delayed
from settings import (
    ANONYMIZED_DATA_DIRECTORY, IMAGES_DIRECTORY)

def copy_image(origin_folder, target_folder):
    """
    Find original screening in origin_folder and copy it to target_folder.
    """

    # Define path to all png files in the folder
    path = origin_folder + "/*.png"

    # Create list with addresses of all files in the folder
    addrs = sorted(glob.glob(path))

    # Get screenings path
    all_images = re.compile(".*_[0-9].png")
    image_list = list(filter(all_images.match, addrs))
    number_of_images = len(image_list)

    # If no images
    if number_of_images == 0:
        all_images = re.compile(".*_[0-9][0-9].png")
        image_list = list(filter(all_images.match, addrs))

    # Copy to new folder
    for image in image_list:

        # Check if image is RGB or 8bit
        img = np.array(Image.open(image))

        if len(img.shape) != 2:
            print(img.shape)
            print(colorize("{}".format(origin_folder), "red"))

        shutil.copy(image, target_folder)

if __name__ == "__main__":

    if not os.path.isdir(IMAGES_DIRECTORY):
        os.mkdir(IMAGES_DIRECTORY)
    list_of_patient_dirs = glob.glob(os.path.join(ANONYMIZED_DATA_DIRECTORY, "*"))
    Parallel(n_jobs=-1, verbose=1)(
        delayed(copy_image)(
            origin_folder=patient_dir,
            target_folder=IMAGES_DIRECTORY,
            )
        for patient_dir in sorted(list_of_patient_dirs))


def isPalindrome(x):
    x_str = str(x)
    x_len = len(x_str)
    if x_len % 2 == 0:
        return x_str[:x_len//2] == x_str[x_len//2:][::-1]
    else:
        return x_str[:x_len//2 + 1] == x_str[x_len//2::][::-1]
print(isPalindrome(11))

def isPalindrome_2(x):
    str_number = str(x)
    rev_number = str_number[::-1]
    return str_number == rev_number

print(isPalindrome_2(121))


import dbus
import dbus.service

import gpodder
from gpodder import util

def safe_str(txt):
    if txt:
        return txt.encode()
    else:
        return ''

def safe_first_line(txt):
    txt = safe_str(txt)
    lines = util.remove_html_tags(txt).strip().splitlines()
    if not lines or lines[0] == '':
        return ''
    else:
        return lines[0]

class DBusPodcastsProxy(dbus.service.Object):
    """ Implements API accessible through D-Bus

    Methods on DBusPodcastsProxy can be called by D-Bus clients. They implement
    safe-guards to work safely over D-Bus while having type signatures applied
    for parameter and return values.
    """

    # DBusPodcastsProxy(lambda: self.channels, self.on_itemUpdate_activate(), self.playback_episodes, self.download_episode_list, bus_name)
    def __init__(self, get_podcast_list,
            check_for_updates, playback_episodes,
            download_episodes, episode_from_uri,
            bus_name):
        self._get_podcasts = get_podcast_list
        self._on_check_for_updates = check_for_updates
        self._playback_episodes = playback_episodes
        self._download_episodes = download_episodes
        self._episode_from_uri = episode_from_uri
        dbus.service.Object.__init__(self,
                object_path=gpodder.dbus_podcasts_object_path,
                bus_name=bus_name)

    def _get_episode_refs(self, urls):
        """Get Episode instances associated with URLs"""
        episodes = []
        for p in self._get_podcasts():
            for e in p.get_all_episodes():
                if e.url in urls:
                    episodes.append(e)
        return episodes

    @dbus.service.method(dbus_interface=gpodder.dbus_podcasts, in_signature='', out_signature='a(ssss)')
    def get_podcasts(self):
        """Get all podcasts in gPodder's subscription list"""
        def podcast_to_tuple(podcast):
            title = safe_str(podcast.title)
            url = safe_str(podcast.url)
            description = safe_first_line(podcast.description)
            cover_file = ''

            return (title, url, description, cover_file)

        return [podcast_to_tuple(p) for p in self._get_podcasts()]

    @dbus.service.method(dbus_interface=gpodder.dbus_podcasts, in_signature='s', out_signature='ss')
    def get_episode_title(self, url):
        episode = self._episode_from_uri(url)

        if episode is not None:
            return episode.title, episode.channel.title

        return ('', '')

    @dbus.service.method(dbus_interface=gpodder.dbus_podcasts, in_signature='s', out_signature='a(sssssbbb)')
    def get_episodes(self, url):
        """Return all episodes of the podcast with the given URL"""
        podcast = None
        for channel in self._get_podcasts():
            if channel.url == url:
                podcast = channel
                break

        if podcast is None:
            return []

        def episode_to_tuple(episode):
            title = safe_str(episode.title)
            url = safe_str(episode.url)
            description = safe_first_line(episode._text_description)
            filename = safe_str(episode.download_filename)
            file_type = safe_str(episode.file_type())
            is_new = (episode.state == gpodder.STATE_NORMAL and episode.is_new)
            is_downloaded = episode.was_downloaded(and_exists=True)
            is_deleted = (episode.state == gpodder.STATE_DELETED)

            return (title, url, description, filename, file_type, is_new, is_downloaded, is_deleted)

        return [episode_to_tuple(e) for e in podcast.get_all_episodes()]

    @dbus.service.method(dbus_interface=gpodder.dbus_podcasts, in_signature='as', out_signature='(bs)')
    def play_or_download_episode(self, urls):
        """Play (or download) a list of episodes given by URL"""
        episodes = self._get_episode_refs(urls)
        if not episodes:
            return (0, 'No episodes found')

        to_playback = [e for e in episodes if e.was_downloaded(and_exists=True)]
        to_download = [e for e in episodes if e not in to_playback]

        if to_playback:
            self._playback_episodes(to_playback)

        if to_download:
            self._download_episodes(to_download)

        return (1, 'Success')

    @dbus.service.method(dbus_interface=gpodder.dbus_podcasts, in_signature='', out_signature='')
    def check_for_updates(self):
        """Check for new episodes or offer subscriptions"""
        self._on_check_for_updates()


import polygongrid as pg

# desired bounds
bounds = (-180, 180, -90, 90)

# accepts input of either step sizes (resolution) or dimension sizes (number of items in each dimension)
# if both provided, they must agree
step_size = (10, 10)
dim_size = (36, 18)

my_grid = pg.PolygonGrid(bounds, step_size=step_size, dim_size=dim_size, properties="grid")

my_grid.build_grid()

my_grid.output_to_geojson("examples/example.geojson")

# Run time: 0.0295 seconds


import os
from pathlib import Path

from .utils import CREDENTIALS_FILE
from .path_resolver import resolve_cwd

def get_credentials(root_path: Path):
    if os.getenv("ABSTRA_API_TOKEN"):
        return os.getenv("ABSTRA_API_TOKEN")

    credentials_path = Path(root_path, CREDENTIALS_FILE)
    if not credentials_path.exists():
        return None

    return credentials_path.read_text(encoding="utf-8").strip()

def delete_credentials(root_path: Path):
    credentials_path = Path(root_path, CREDENTIALS_FILE)

    if credentials_path.exists():
        credentials_path.unlink()

def set_credentials(root_path: Path, token: str):
    credentials_path = Path(root_path, CREDENTIALS_FILE)
    credentials_path.parent.mkdir(exist_ok=True)

    credentials_path.write_text(token, encoding="utf-8")

def resolve_headers(root: Path = Path(".")):
    root_path = resolve_cwd(root)
    credentials = get_credentials(root_path)

    if not credentials:
        return None

    return {"Api-Authorization": f"Bearer {credentials}"}


"""

Text Classification For Dialog Recognition on English and American Corpora

Author: Colby Beach, James Gaskell, Kevin Welch and Kristina Streignitz

We affirm that we have carried out my academic endeavors with full
academic honesty. Colby Beach, James Gaskell, Kevin Welch

"""

# Splits a .txt file into a new file that creates a
# new line for every new sentence.

def split_sentence(readFile, writeFile):
    with open(writeFile,'w') as w:
        with open(readFile,'r') as f:
            for line in f:
                for word in line.split("."):
                    w.write(word.strip().replace('\n', ' ').replace('\r', '') + "\n")

if __name__ == "__main__":
    # Example:
    split_sentence("rawData/American/sorcerer-stone.txt", "sentenceTrain/America/sorcerer-stone.txt")


import json
import os
import sys
import asyncio
import pathlib
import websockets
import logging

from vosk import BatchModel, BatchRecognizer, GpuInit

async def recognize(websocket, path):
    global args
    global pool
    global model

    rec = None
    sample_rate = args.sample_rate

    logging.info(f'Connection from {websocket.remote_address}');

    while True:

        message = await websocket.recv()

        # Load configuration if provided
        if isinstance(message, str) and 'config' in message:
            jobj = json.loads(message)['config']
            logging.info("Config %s", jobj)
            if 'sample_rate' in jobj:
                sample_rate = float(jobj['sample_rate'])
            continue

        # Create the recognizer, word list is temporary disabled since not every model supports it
        if not rec:
            rec = BatchRecognizer(model, sample_rate)

        if message == '{"eof" : 1}':
            rec.FinishStream()
            break

        if isinstance(message, str) and 'config' in message:
            continue

        rec.AcceptWaveform(message)

        while rec.GetPendingChunks() > 0:
            await asyncio.sleep(0.1)

        res = rec.Result()
        if len(res) == 0:
            await websocket.send('{ "partial" : "" }')
        else:
            await websocket.send(res)

    while rec.GetPendingChunks() > 0:
        await asyncio.sleep(0.1)

    res = rec.Result()
    await websocket.send(res)

async def start():

    global model
    global args

    # Enable loging if needed
    #
    # logger = logging.getLogger('websockets')
    # logger.setLevel(logging.INFO)
    # logger.addHandler(logging.StreamHandler())
    logging.basicConfig(level=logging.INFO)

    args = type('', (), {})()

    args.interface = os.environ.get('VOSK_SERVER_INTERFACE', '0.0.0.0')
    args.port = int(os.environ.get('VOSK_SERVER_PORT', 2700))
    args.sample_rate = float(os.environ.get('VOSK_SAMPLE_RATE', 8000))

    GpuInit()

    model = BatchModel()

    async with websockets.serve(recognize, args.interface, args.port):
        await asyncio.Future()

if __name__ == '__main__':
    asyncio.run(start())


import numpy as np
import pandas as pd
import torch
import torch.nn as nn

# read csv file
df = pd.read_csv('housing.csv')
print(df.head())

df.columns = np.array(range(0, len(df.columns)))
print(df.head())

# Train data

x_train = df.iloc[:, range(0, 3)]
x_train = torch.FloatTensor(x_train.values)
print(x_train)

y_train = df.iloc[:, 3]
y_train = torch.FloatTensor(y_train.values)
y_train = y_train.view(y_train.size(0), 1)
print(y_train)

# Normalization

x_mean = torch.mean(x_train)
x_std = torch.std(x_train)
x_train -= x_mean
x_train /= x_std
print(x_train)

y_mean = torch.mean(y_train)
y_std = torch.std(y_train)
y_train -= y_mean
y_train /= y_std
print(y_train)

# Model

class Model(nn.Module):
    def __init__(self):
        super().__init__()
        self.input = nn.Linear(3, 128)
        self.layer1 = nn.Sequential(
            nn.Linear(128, 128),
            nn.ReLU()
        )
        self.layer2 = nn.Sequential(
            nn.Linear(128, 64),
            nn.ReLU()
        )
        self.layer3 = nn.Sequential(
            nn.Linear(64, 32),
            nn.ReLU()
        )
        self.output = nn.Linear(32, 1)

    def forward(self, x):
        out = self.input(x)
        out = self.layer1(out)
        out = self.layer2(out)
        out = self.layer3(out)
        out = self.output(out)
        return out

model = Model()
criterion = nn.MSELoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)

# Training

for epoch in range(1000):
    prediction = model(x_train)
    cost = criterion(prediction, y_train)

    optimizer.zero_grad()
    cost.backward()
    optimizer.step()

    if epoch % 10 == 0:
        print('Epoch : {}, cost : {:.6f}'.format(epoch, cost.item()))

# Prediction

new_var = torch.FloatTensor([[-0.8156, -1.2938,  0.7935]])
print(model(new_var))


from __future__ import print_function

import sys
import time
from pyspark.sql import SparkSession

if __name__ == "__main__":
    """
        Usage: long_running [partitions] [run_time_sec]
    """
    partitions = int(sys.argv[1]) if len(sys.argv) > 1 else 5
    run_time_sec = int(sys.argv[2]) if len(sys.argv) > 2 else 600

    spark = SparkSession \
        .builder \
        .appName("Long-Running Spark Job") \
        .getOrCreate()

    n = 100000 * partitions
    data = spark.sparkContext.parallelize(range(1, n + 1), partitions)

    def processPartition(partition):
        """Sleep for run_time_sec"""
        print('Start processing partition')
        time.sleep(run_time_sec)
        print('Done processing partition')

    data.foreachPartition(processPartition)
    print('Job completed successfully')

    spark.stop()


import timeit
from copy import copy

import Algorithms.point_cloud_generator as pcg
import Algorithms.alphacomplexwrapper as acw
import Algorithms.random_discrete_morse as rdm
import Algorithms.column_algo.column_algorithm as ca
import Examples.rand_k_n_p as rnp
import Examples.davides_eight_point_delaunay as dd

from MorseAndFiltrations.DMF_to_filtration import DMF_to_filtration
from MorseAndFiltrations.filtration_to_DMF import filtration_to_DMF

import scipy.stats as scs
import numpy as np
import matplotlib.pyplot as plt
import tikzplotlib

def uniform_comparison(n,dim, console_outs = False):
    # points = pcg.generate_n_points(n,dim)

    #
    # if(dim == 2):
    #     points = pcg.multivariate_gaussian(n,[0,0],
    #                                         [[1,0],[0,1]])
    # else:
    #     points = pcg.multivariate_gaussian(n, [0, 0, 0],
    #                                         [[1, 0, 0], [0, 1, 0], [0 ,0 ,1]])
    #

    if(dim == 2):
        points = pcg.gaussian_mixture_model(n,[[0,0],[1,1],[0,3]],
                                            [[[1,0],[0,1]],[[1,0],[0,1]],[[1,0],[0,1]]])
    else:
        points = pcg.gaussian_mixture_model(n, [[0, 0, 0], [1, 1, 1], [0, 3, 0.5]],
                                            [[[1, 0, 0], [0, 1, 0], [0 ,0 ,1]],
                                             [[1, 0, 0], [0, 1, 0], [0 ,0 ,1]],
                                             [[1, 0, 0], [0, 1, 0], [0 ,0 ,1]]])

    alpha = acw.AlphaComplexWrapper(points, False)
    filtration = [elem[0] for elem in alpha.filtration]

    start = timeit.default_timer()
    mat1 = ca.build_boundary_matrix_from_filtration(filtration)
    steps_without,_,_ = ca.column_algorithm(mat1)
    stop = timeit.default_timer()
    without_clearing_time = stop-start
    if(console_outs):
        print("WITHOUT CLEARING TIME: ", stop - start)
        print("WITHOUT CLEARING ADDITIONS: ", steps_without)

        print("--------------------")
        print("LENGTH OF FILTRATION: ", len(filtration))

    start = timeit.default_timer()
    crit, pairs, clear = filtration_to_DMF(filtration)
    if (console_outs):
        print("ELEMENTS IN PAIRS: ", len(pairs) * 2)
        print("--------------------")

    mat2 = ca.build_boundary_matrix_from_filtration_and_clear(filtration,clear)
    steps_apparent,_,_ = ca.column_algorithm(mat2)
    stop = timeit.default_timer()
    apparent_clearing_time = stop-start

    if (console_outs):
        print("APPARENT CLEARING TIME: ", stop - start)
        print("APPARENT CLEARING ADDITIONS: ", steps_apparent)

    s = without_clearing_time/ apparent_clearing_time
    a = 100-(100/steps_without[0] * steps_apparent[0])

    if (console_outs):
        print("Speedupfactor by apparents: ", s)
        print("Additions cleared via apparents : ", a)

    return s,a,len(pairs)*200/len(filtration)

def get_average_speedup_factor(n,runs):
    speed2 = []
    speed3 = []
    speed4 = []

    additions2 = []
    additions3 = []
    additions4 = []

    percentage2 = []
    percentage3 = []
    percentage4 = []

    estimated_time_till_finish = [0]

    for i in range(runs):
        if(i > 0):
            print("Step: ", i, "Estimated time till finish: ", (sum(estimated_time_till_finish)/i)*(runs-i))
        start = timeit.default_timer()
        s2,a2,p2 = uniform_comparison(n,2)
        speed2.append(s2)
        additions2.append(a2)
        percentage2.append(p2)

        s3,a3,p3 = uniform_comparison(n,3)
        speed3.append(s3)
        additions3.append(a3)
        percentage3.append(p3)
        stop = timeit.default_timer()

        estimated_time_till_finish.append(stop-start)

        # s4,a4 = uniform_comparison(n,4)
        # speed4.append(s4)
        # additions4.append(a4)

    fit_data(speed2,"s2")
    fit_data(speed3,"s3")
    # fit_data(speed4,4)

    fit_data(additions2, "a2")
    fit_data(additions3, "a3")

    fit_data(percentage2, "p2")
    fit_data(percentage3, "p3")

def fit_data(data,id):
    mu, std = scs.norm.fit(data)

    # Plot the histogram.
    plt.hist(data, bins=100, alpha=0.6, histtype='bar', density=True)
    # Plot the PDF.
    xmin, xmax = plt.xlim()
    x = np.linspace(xmin, xmax, 1000)
    #p = scs.norm.pdf(x, mu, std)
    #plt.plot(x, p, 'k', linewidth=2)
    title = id + "_mean = " + str(mu)
    plt.title(title)
    tikzplotlib.save("apparent_gains_gaussian_mixture_300_points_value_" + str(id) + "_runs_" + str(len(data)) + ".tex")
    plt.show()

def analyse_gap(n, iterations):
    big_elements = []
    big_percentage = []
    big_steps = []

    small_elements = []
    small_percentage = []
    small_steps = []

    saved_additions = []

    for i in range(iterations):
        print(i)
        points = pcg.multivariate_gaussian(n, [0, 0, 0], [[1, 0, 0], [0, 1, 0], [0 ,0 ,1]])

        alpha = acw.AlphaComplexWrapper(points, False)
        filtration = [elem[0] for elem in alpha.filtration]

        mat1 = ca.build_boundary_matrix_from_filtration(filtration)
        steps_without,_,_ = ca.column_algorithm(mat1)
        crit, pairs, clear = filtration_to_DMF(filtration)

        mat2 = ca.build_boundary_matrix_from_filtration_and_clear(filtration,clear)
        steps_apparent,_,_ = ca.column_algorithm(mat2)

        a = 100-(100/steps_without[0] * steps_apparent[0])
        saved_additions.append(a)

        if(a < 50):
            small_elements.append(len(filtration))
            small_percentage.append((100 * len(pairs)*2)/len(filtration))
            small_steps.append(steps_without[0])
        else:
            big_elements.append(len(filtration))
            big_percentage.append((100 * len(pairs)*2)/len(filtration))
            big_steps.append(steps_without[0])

    print("SMALL_ELEMENTS_MEAN", sum(small_elements)/len(small_elements))
    print("SMALL_PERCENTAGE_MEAN", sum(small_percentage)/len(small_percentage))
    print("SMALL_STEPS_MEAN", sum(small_steps)/len(small_steps))

    print("###############")

    print("BIG_ELEMENTS_MEAN", sum(big_elements) / len(big_elements))
    print("BIG_PERCENTAGE_MEAN", sum(big_percentage) / len(big_percentage))
    print("BIG_STEPS_MEAN", sum(big_steps) / len(big_steps))

    fit_data(saved_additions,"_")

get_average_speedup_factor(300,100)
# analyse_gap(30,100)


from qbstyles import mpl_style

def _style_ticks(axis, color):
    """ Enable minor ticks, and color major + minor ticks"""
    axis.minorticks_on()
    ticks = (
        axis.get_xticklines()
        + axis.xaxis.get_minorticklines()
        + axis.get_yticklines()
        + axis.yaxis.get_minorticklines()
    )

    for tick in ticks:
        tick.set_color("#" + color + "3D")

def _monkey_patch_subplot(color, subplot):
    """ Style all axes of a figure containing subplots, just after the
    figure is created. """

    def _patch(*args, **kwargs):
        fig, axes = subplot(*args, **kwargs)
        axes_list = [axes] if isinstance(axes, matplotlib.axes.Axes) else axes
        for ax in axes_list:
            if isinstance(ax, matplotlib.axes.Axes):
                _style_ticks(ax, color)
            else:
                for each in ax:
                    _style_ticks(each, color)
        return fig, axes

    return _patch

def plot(dark):
    mpl_style(dark, minor_ticks=False)
    plt.subplots = _monkey_patch_subplot("FFFFFF", plt.subplots)
    fig, axes = plt.subplots(2, 2, figsize=(15, 10))

    for pos in range(len(Epochs)):
        axes[0, 0].plot(Epochs[pos][1:], LossTr[pos][1:], label=f"Model {(pos+1)*100000}")
        axes[0, 0].scatter(Epochs[pos][1:], LossTr[pos][1:])

        axes[0, 1].plot(Epochs[pos], LossVa[pos], label=f"Model {(pos+1)*100000}")
        axes[0, 1].scatter(Epochs[pos], LossVa[pos])

        axes[1, 0].plot(Epochs[pos], AccuTr[pos], label=f"Model {(pos+1)*100000}")
        axes[1, 0].scatter(Epochs[pos], AccuTr[pos])

        axes[1, 1].plot(Epochs[pos], AccuVa[pos], label=f"Model {(pos+1)*100000}")
        axes[1, 1].scatter(Epochs[pos], AccuVa[pos])

    axes[0, 0].legend()
    axes[0, 1].legend()
    axes[1, 0].legend()
    axes[1, 1].legend()
    axes[0, 0].set_title('Training Loss Plots')
    axes[0, 1].set_title('Validation Loss Plots')
    axes[1, 0].set_title('Training Accuracy Plots')
    axes[1, 1].set_title('Validation Accuracy Plots')
    fig.suptitle('Exercise 4 Empirical Overfitting Plots', fontsize=16)
    plt.savefig('plots.png')


from typing import List

class Solution:
    def findMaximizedCapital(self, k: int, w: int, profits: List[int], capital: List[int]) -> int:
        """
        This will TLE
        32 / 35 testcases passed
        """
        project_used = set()
        while k:
            temp_p = 0
            temp_i = -1
            for i, (p, c) in enumerate(zip(profits, capital)):
                if i in project_used:
                    continue
                if c <= w and p > temp_p:
                    temp_p = p
                    temp_i = i
            project_used.add(temp_i)
            w += temp_p
            k -= 1

        return w


import asyncio
import pandas as pd
import aiohttp
import matplotlib.pyplot as plt
from io import BytesIO
from openpyxl import Workbook
from openpyxl.utils.dataframe import dataframe_to_rows
from openpyxl.drawing.image import Image

async def is_url_accessible(session, url):
    try:
        async with session.get(url) as response:
            return response.status == 200
    except aiohttp.ClientError:
        return False

async def process_csv(input_csv, output_xlsx):
    async with aiohttp.ClientSession() as session:
        data = pd.read_csv(input_csv, header=None, names=['URL'])
        tasks = []

        for url in data['URL']:
            task = is_url_accessible(session, url)
            tasks.append(task)

        results = await asyncio.gather(*tasks)

        data['IsAccessible'] = results

        # Generate the pie chart
        pie_chart = generate_pie_chart(data['IsAccessible'])

        # Create a BytesIO object to save the Excel file
        output = BytesIO()

        # Save the data to a sheet
        data.to_excel(output, sheet_name='Results',
                      index=False, engine='openpyxl')

        # Create a new sheet for the pie chart
        pie_chart.to_excel(output, sheet_name='PieChart',
                           index=False, engine='openpyxl')

        # Save the BytesIO object to a file
        with open(output_xlsx, 'wb') as f:
            f.write(output.getvalue())

        print(f"Results and pie chart saved to {output_xlsx}")

def generate_pie_chart(accessibility_series):
    accessible_count = accessibility_series.value_counts().get(True, 0)
    not_accessible_count = accessibility_series.value_counts().get(False, 0)
    labels = ['Accessible', 'Not Accessible']
    sizes = [accessible_count, not_accessible_count]

    colors = ['#66b3ff', '#ff9999']
    # Create a pie chart using matplotlib
    plt.pie(sizes, labels=labels, colors=colors,
            autopct='%1.1f%%', startangle=90)
    plt.axis('equal')
    plt.title('Accessibility Statistics')
    plt.savefig('pie_chart.png')

    return pd.DataFrame({'Category': labels, 'Count': sizes})

if __name__ == "__main__":
    input_csv_file = "furniture_stores_pages.csv"
    output_xlsx_file = "result_with_pie_chart.xlsx"

    asyncio.run(process_csv(input_csv_file, output_xlsx_file))


# External imports
import datetime
import pandas as pd
import pytz
import requests
import sys
import yaml

# Internal imports
sys.path.insert(0, '../')
from game import GameState

class LineGenerator:
    default_params = {
                      'SPORT': 'baseball_mlb',
                      'REGIONS': 'us',                 # uk | us | eu | au.
                      'MARKETS': 'h2h,spreads,totals', # h2h | spreads | totals
                      'ODDS_FORMAT': 'decimal',        # decimal | american
                      'DATE_FORMAT': 'iso'             # iso | unix
                     }

    def __init__(self, keyfile, id_prefix_func, params=default_params):
        with open(keyfile, 'r') as yamlfile:
            self.key = yaml.load(yamlfile, Loader=yaml.FullLoader)['api-key']
        self.params = params
        self.remaining, self.used = -1, -1   # unkown at initialization time
        self.get_id_prefix = id_prefix_func

    tchar = lambda name, teams: 'A' if name == teams[0] else 'H'
    ochar = lambda name: 'O' if name == 'over' else 'U'

    to_eastern = lambda time: datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%SZ'
                                          ).replace(tzinfo=pytz.utc
                                          ).astimezone(pytz.timezone('US/Eastern'))

    def process_moneyline(prefix, market, teams):
        assert(market['key'] == 'h2h')
        assert(len(market['outcomes']) == 2)
        lines = {}
        for outcome in market['outcomes']:
            assert(outcome['name'] in teams)
            lines[prefix+LineGenerator.tchar(outcome['name'], teams)+'_price'] = outcome['price']
        return lines

    def process_spread(prefix, market, teams):
        assert(market['key'] == 'spreads')
        assert(len(market['outcomes']) == 2)
        lines = {}
        for outcome in market['outcomes']:
            assert(outcome['name'] in teams)
            lines[prefix+LineGenerator.tchar(outcome['name'], teams)+'_price'] = outcome['price']
            lines[prefix+LineGenerator.tchar(outcome['name'], teams)+'_point'] = outcome['point']
        return lines

    def process_total(prefix, market):
        assert(market['key'] == 'totals')
        assert(len(market['outcomes']) == 2)
        lines = {}
        for outcome in market['outcomes']:
            assert(outcome['name'] in ('Over', 'Under'))
            lines[prefix+LineGenerator.ochar(outcome['name'])+'_price'] = outcome['price']
            lines[prefix+LineGenerator.ochar(outcome['name'])+'_point'] = outcome['point']
        return lines

    # Sends get request to the api
    # Returns raw response, unformatted.
    def query(self):
        # Send request to the api and get back a response
        response = requests.get(
                       f"https://api.the-odds-api.com/v4/sports/{self.params['SPORT']}/odds",
                       params={
                           'api_key': self.key,
                           'regions': self.params['REGIONS'],
                           'markets': self.params['MARKETS'],
                           'oddsFormat': self.params['ODDS_FORMAT'],
                           'dateFormat': self.params['DATE_FORMAT']
                       })
        # Update usage stats
        self.update_usage(response.headers['x-requests-remaining'],
                          response.headers['x-requests-used'])
        # Return raw response
        return response.json()

    # Takes raw response from the api and formats it.
    def format_response(self, response):
        games = {}
        for game in response:
            start = LineGenerator.to_eastern(game['commence_time'])
            teams = (game['away_team'], game['home_team'])
            id_prefix = self.get_id_prefix(teams[1], strt_time=start)
            line_info = {}
            for book in game['bookmakers']:
                bpre = book['key']+'_'
                line_info[bpre+'last'] = LineGenerator.to_eastern(book['last_update'])
                for market in book['markets']:
                    mpre = bpre + market['key']+'_'
                    line_info[mpre+'last'] = LineGenerator.to_eastern(market['last_update'])
                    if market['key'] == 'h2h':
                        line_info.update(LineGenerator.process_moneyline(mpre, market, teams))
                    if market['key'] == 'spreads':
                        line_info.update(LineGenerator.process_spread(mpre, market, teams))
                    if market['key'] == 'totals':
                        line_info.update(LineGenerator.process_total(mpre, market))
            games[id_prefix] = (start, pd.Series(line_info))
        return games

    # Queries the api and returns the formatted response
    # Returns a dictionary game_id_prefix -> (commence_time, pd.series of line info)
    def get_lines(self):
        return self.format_response(self.query())

    # Returns usage stats
    def usage(self):
        return self.remaining, self.used

    # Updates usage stats
    def update_usage(self, remaining, used):
        self.remaining = int(remaining)
        self.used = int(used)


import os, re, time, sqlite3, json, logging

logger = logging.getLogger(__name__)

# Regexp implementation for sqlite
# Example code from https://stackoverflow.com/questions/5365451/problem-with-regexp-python-and-sqlite
def regexp(expr, item):
  if item:
    reg = re.compile(expr)
    if reg.search(item):
      return True
  return False

def bssid2int(bssid):
  if not bssid:
    return None
  return int(bssid.translate(str.maketrans('', '', ":.-, ")), 16)

class CredentialsStore():
  __instance = None
  credentialsStoreDB = None

  @staticmethod
  def getStore():
    if not CredentialsStore.__instance:
      CredentialsStore()
    return CredentialsStore.__instance

  def __init__(self):
    if CredentialsStore.__instance != None:
      raise Exception("This class is a singleton!")
    else:
      CredentialsStore.__instance = self

    logger.info("Starting Credentials Store")

    credentialsStoreDBFile = "/etc/WLANderlust/WLANderlust.credentials.db"

    if not os.path.isfile(credentialsStoreDBFile):
      logger.info("Creating Credentials Store database %s" % credentialsStoreDBFile)
    logger.info("Opening Credentials Store database %s" % credentialsStoreDBFile)

    try:
      self.credentialsStoreDB = sqlite3.connect(credentialsStoreDBFile, check_same_thread=False)
      self.credentialsStoreDB.create_function("REGEXP", 2, regexp)
      self.credentialsStoreDB.execute("CREATE TABLE IF NOT EXISTS credentialsStore (bssid INTEGER, ssid TEXT, domain TEXT, timestamp INTEGER NOT NULL, share BOOLEAN NOT NULL, credentials TEXT NOT NULL)")
      self.credentialsStoreDB.execute("CREATE UNIQUE INDEX IF NOT EXISTS bssid ON credentialsStore(bssid)")
      self.credentialsStoreDB.execute("CREATE UNIQUE INDEX IF NOT EXISTS ssid_domain ON credentialsStore(ifnull(ssid, 0), domain)")

      if logger.isEnabledFor(logging.DEBUG):
        cur = self.credentialsStoreDB.cursor()
        cur.execute("SELECT count(*) FROM credentialsStore")
        n = cur.fetchone()
        logger.debug("Nr of Credentials stored: %s" % n)
    except sqlite3.Error as e:
      logger.error(e)

    logger.info("Started Credentials Store")

  def __del__(self):
    logger.info("Stopping Credentials Store")

    if self.credentialsStoreDB:
      try:
        if logger.isEnabledFor(logging.DEBUG):
          cur = self.credentialsStoreDB.cursor()
          cur.execute("SELECT count(*) FROM credentialsStore")
          n = cur.fetchone()
          logger.debug("Nr of Credentials stored: %s" % n)

        logger.info("Closing Credentials Store database")
        self.credentialsStoreDB.close()
      except sqlite3.Error as e:
        logger.error(e)

    logger.info("Stopped Credentials Store")

  def stop(self):
    ''' '''

  def getCredentials(self, bssid, ssid, domain):
    credentials = None

    if not self.credentialsStoreDB:
      logger.error("Credentials Store not available")
      return None
    if not bssid and not ssid and not domain:
      logger.error("At least one of BSSID, SSID or domain needs to be given")
      return None
    if bssid and (ssid or domain):
      logger.error("if BSSID is given no SSID or domain can be given")
      return None

    logger.debug("Getting credentials for ('%s', '%s', '%s')" % (bssid, ssid, domain))

    if bssid:
      try:
        cur = self.credentialsStoreDB.cursor()
        cur.execute("SELECT credentials FROM credentialsStore WHERE bssid = ? AND ssid IS NULL AND domain IS NULL ORDER BY timestamp", (bssid2int(bssid),))
        credentials = cur.fetchone()
        logger.debug("Found credentials: %s" % credentials)
      except sqlite3.Error as e:
        logger.error(e)

    if ssid or domain:
      try:
        cur = self.credentialsStoreDB.cursor()
        cur.execute("SELECT credentials FROM credentialsStore WHERE bssid IS NULL AND (ssid = ? OR domain = ?) ORDER BY timestamp", (ssid, domain))
        credentials = cur.fetchone()
        logger.debug("Found credentials: %s" % credentials)
      except sqlite3.Error as e:
        logger.error(e)

    if not credentials:
      logger.info("No credentials found")
      return None

    credentials = json.loads(credentials[0])
    logger.debug("Found credentials: %s" % credentials)

    return credentials

  def setCredentials(self, bssid, ssid, domain, share, credentials):
    if not credentials:
      logger.error("No credentials given")
      return False

    if not self.credentialsStoreDB:
      logger.error("Credentials Store not available")
      return False
    if not bssid and not ssid and not domain:
      logger.error("At least one of BSSID, SSID or domain needs to be given")
      return False
    if bssid and (ssid or domain):
      logger.error("If BSSID is given no SSID or domain can be given")
      return False

    logger.debug("Adding credentials for ('%s', '%s', '%s')" % (bssid, ssid, domain))
    logger.debug("Credentials: '%s'" % credentials)
    logger.debug("Share: '%s'" % share)

    try:
      cur = self.credentialsStoreDB.cursor()
      cur.execute("REPLACE INTO credentialsStore(bssid, ssid, domain, timestamp, share, credentials) values(?, ?, ?, ?, ?, ?)",
        (bssid2int(bssid), ssid, domain, time.time(), share, json.dumps(credentials)))
      self.credentialsStoreDB.commit()
      logger.debug("Credentials added")
    except sqlite3.Error as e:
      logger.error(e)

  def deleteCredentials(self, bssid, ssid, domain):
    if not self.credentialsStoreDB:
      logger.error("Credentials Store not available")
      return False
    if not bssid and not ssid and not domain:
      logger.error("At least one of BSSID, SSID or domain needs to be given")
      return False
    if bssid and (ssid or domain):
      logger.error("if BSSID is given no SSID or domain can be given")
      return False

    logger.debug("Deleting credentials for ('%s', '%s', '%s')" % (bssid, ssid, domain))

    try:
      cur = self.credentialsStoreDB.cursor()
      cur.execute("DELETE FROM credentialsStore WHERE bssid IS ? AND ssid IS ? AND domain IS ?", (bssid2int(bssid), ssid, domain))
      self.credentialsStoreDB.commit()
      logger.debug("Credentials deleted")
    except sqlite3.Error as e:
      logger.error(e)


import datetime
import time
import cv2
import numpy as np
import threading

# initialize the video stream and allow the cammera sensor to warmup
vs = cv2.VideoCapture(0)
time.sleep(2.0)
avg=[0,0]
count=0
x = []
y = []

def imageStream():
    # loop over the frames from the video stream
    while True:
        (grabbed, frame) = vs.read()

        # draw the timestamp on the frame
        timestamp = datetime.datetime.now()
        ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
        cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX,0.90, (255, 255, 255), 1)
        cv2.circle(frame,(320,240),25,(0,255,),3)
        # show the frame
        cv2.imshow("Nozzle", frame)
        key = cv2.waitKey(10)

def userInterface():
    print("")
    tc=input("Press enter to close the window when done. \n")

#######################
# Main Code Starts Here
#######################
th = threading.Thread(target=imageStream)
th.daemon = True # Thread will be killed when main exits.
th.start()

userInterface()


from ._interface import IStorage

class DefaultStorage(IStorage):

    _cache: dict

    def __init__(self):
        self._cache = {}

    async def set_item(self, key: str, value: str):
        self._cache[key] = value

    async def get_item(self, key: str, default_value: str = None):
        if key not in self._cache:
            return default_value
        return self._cache[key]

    async def remove_item(self, key: str):
        if key in self._cache:
            del self._cache[key]


# 我的方法
def my_max(max_, arr=[]):
    if arr == []:
        return max_
    elif max_ < arr[0]:
        max_ = arr[0]
        return my_max(max_, arr[1:])
    else:
        return my_max(max_, arr[1:])

# 书上方法

def my_max_2(arr=[]):
    if len(arr) == 2:
        return arr[0] if arr[0] > arr[1] else arr[1]
    else:
        sub_max = my_max_2(arr[1:])
        return arr[0] if arr[0] > sub_max else sub_max

print(my_max(-float('inf'), [1, 2, 3, 4]))
print(my_max_2([1, 2, 3, 4, 3]))


import csv

f = open('blkjckhands.csv')
csv_f = csv.reader(f)
wincount = 0
pushcount = 0

#Loop over each Row
for row in csv_f:
    rowstring = ''.join(row[15])
    #count wins
    if rowstring == "Win":
        wincount = wincount + 1
    #count losses
    if rowstring == "Push":
        pushcount = pushcount + 1

#Print Wins, Losses, and Pushes
print("Total Wins: ", wincount)
print("Total Losses: ", 900000-(wincount+pushcount))
print("Total Pushes: ", pushcount)

#Print Win Rate, Loss Rate, Push Rate
print("Total Win Rate: ", wincount/900000)
print("Total Loss Rate: ", (900000-(wincount+pushcount)) / 900000)
print("Total Push Rate: ", pushcount/900000)


import pandas
from pandas import DataFrame

def load_data(filename: str) -> DataFrame:
    df = pandas.read_csv(filename)
    df = df[["Date", "Close"]]
    df.columns = ["ds", "y"]

    return df[df["y"].notnull()]


import time
from tkinter import *
from pygame import mixer
import requests
from tkinter import font
from PIL import Image, ImageTk
from tkvideo import tkvideo
from DetectorClass import DetectorClass
from FollowClass import FollowDetector
import BodyControlClass

class Circo(Frame):
    def __init__(self, parent=None):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        self.make_widgets()

    def make_widgets(self):
        # don't assume that self.parent is a root window.
        # instead, call `winfo_toplevel to get the root window
        self.winfo_toplevel().title("Circo de drones")

mixer.init()
mixer.music.load('assets/circo.mp3')
mixer.music.play(10)

root = Tk()
circo = Circo(root)
root.geometry("770x525")

image = Image.open("assets/entrada.png")
image = image.resize((770, 525), Image.ANTIALIAS)

bg = ImageTk.PhotoImage(image)
canvas1 = Canvas(root, width=770, height=525)
canvas1.pack(fill="both", expand=True)
canvas1.create_image(0, 0, image=bg, anchor="nw")

myFont = font.Font(family='Bernard MT Condensed', size=22, weight='bold')

def follow():
    mixer.music.stop()
    mixer.music.load('assets/aplausos.mp3')
    mixer.music.play(10)
    time.sleep(5)
    mixer.music.stop()

    newWindow = Toplevel(root)
    newWindow.title("Sígueme")
    newWindow.geometry("450x650")
    # Presentation mode
    BodyControlClass.main()
    # detector = FollowDetector()
    # frame = detector.buildFrame(newWindow)
    # frame.pack(fill="both", expand="yes", padx=10, pady=10)
    newWindow.mainloop()

def fingers():
    mixer.music.stop()
    mixer.music.load('assets/aplausos.mp3')
    mixer.music.play(10)
    time.sleep(5)
    mixer.music.stop()

    newWindow = Toplevel(root)
    newWindow.title("Dedos")
    newWindow.geometry("450x650")
    detector = DetectorClass()
    frame = detector.buildFrame(newWindow, 'fingers')
    frame.pack(fill="both", expand="yes", padx=10, pady=10)
    newWindow.mainloop()

def pose():
    mixer.music.stop()
    mixer.music.load('assets/aplausos.mp3')
    mixer.music.play(10)
    time.sleep(5)
    mixer.music.stop()

    newWindow = Toplevel(root)
    newWindow.title("Pose")
    newWindow.geometry("450x650")
    detector = DetectorClass()
    frame = detector.buildFrame(newWindow, 'pose')
    frame.pack(fill="both", expand="yes", padx=10, pady=10)
    newWindow.mainloop()

def faces():
    mixer.music.stop()
    mixer.music.load('assets/aplausos.mp3')
    mixer.music.play(10)
    time.sleep(5)
    mixer.music.stop()

    newWindow = Toplevel(root)
    newWindow.title("Pose")
    newWindow.geometry("450x650")
    detector = DetectorClass()
    frame = detector.buildFrame(newWindow, 'face')
    frame.pack(fill="both", expand="yes", padx=10, pady=10)
    newWindow.mainloop()

def bye():
    root.destroy()
    bye = Tk()
    circo1 = Circo(bye)
    bye.geometry("770x525")

    image = Image.open("assets/bye.png")
    image = image.resize((770, 525), Image.ANTIALIAS)
    bg = ImageTk.PhotoImage(image)
    canvas1 = Canvas(bye, width=770, height=525)
    canvas1.pack(fill="both", expand=True)

    canvas1.create_image(0, 0, image=bg, anchor="nw")

    bye.mainloop()

def enter():
    mixer.music.stop()
    mixer.music.load('assets/redoble.mp3')  # Loading Music File
    mixer.music.play(10)
    newWindow = Toplevel(root)
    newWindow.title("Selecciona un acto")
    newWindow.geometry("800x600")
    newWindow.columnconfigure(0, weight=1)
    newWindow.columnconfigure(1, weight=1)
    newWindow.columnconfigure(2, weight=1)
    newWindow.columnconfigure(3, weight=1)
    newWindow.rowconfigure(0, weight=1)
    newWindow.rowconfigure(1, weight=1)

    image2 = Image.open("assets/gallery.png")
    image2 = image2.resize((800, 520), Image.ANTIALIAS)
    bg2 = ImageTk.PhotoImage(image2)
    canvas2 = Canvas(newWindow, width=800, height=520)
    canvas2.grid(row=0, column=0, columnspan=4, padx=5, pady=5, sticky=N + S + E + W)
    canvas2.create_image(0, 0, image=bg2, anchor="nw")

    colorsButton = Button(newWindow, text="Follow Me", height=1, bg='#367E18', fg='#FFE9A0', width=12, command=follow)
    colorsButton.grid(row=0, column=0, padx=5, pady=5)
    colorsButton['font'] = myFont
    poseButton = Button(newWindow, text="Control Poses", height=1, bg='#367E18', fg='#FFE9A0', width=12, command=pose)
    poseButton.grid(row=0, column=1, padx=5, pady=5)
    poseButton['font'] = myFont
    fingersButton = Button(newWindow, text="Control Dedos", height=1, bg='#367E18', fg='#FFE9A0', width=12,
                           command=fingers)
    fingersButton.grid(row=0, column=2, padx=5, pady=5)
    fingersButton['font'] = myFont
    facesButton = Button(newWindow, text="Control Caras", height=1, bg='#367E18', fg='#FFE9A0', width=12, command=faces)
    facesButton.grid(row=0, column=3, padx=5, pady=5)
    facesButton['font'] = myFont

    byeButton = Button(newWindow, text="Salir", height=1, bg='#FFE9A0', fg='#367E18', command=bye)
    byeButton.grid(row=1, column=0, columnspan=4, padx=5, pady=5, sticky=N + S + E + W)
    byeButton['font'] = myFont
    newWindow.mainloop()

enterButton = Button(root, text="Pasen y vean", height=1, bg='#367E18', fg='#FFE9A0', width=12, command=enter)
enterButton['font'] = myFont
enterButton_canvas = canvas1.create_window(770 / 2, 525 / 2 + 50, window=enterButton)

# Execute tkinter
root.mainloop()


from pymongo import MongoClient
from creds import db_string
import certifi
import sys

ca = certifi.where()

try:

    db_client = MongoClient(db_string, tlsCAFile=ca)
    db = db_client.test
    # print("Connection successful")

except Exception as e:
    print(str(e))
    print("<< Probably bad Internet or IP is not allowed to connect >>")
    sys.exit()

try:
    current_db = db_client["vuln"]
    scan_collection = current_db["scan"]
    lut_collection = current_db["lut"]

except Exception as e:
    print(str(e))
    sys.exit()


import urllib.request,json
from .models import Quote

api = None

def configure_request(app):
    global api
    api = app.config['API']

def get_quotes():
    '''
    Function that gets the json response to our url request
    '''
    with urllib.request.urlopen(api) as url:
        get_quote = url.read()
        get_quote_response = json.loads(get_quote)

        quote_results = []

        author = get_quote_response.get('author')
        quote = get_quote_response.get('quote')

        if author and quote:
            quote_object = Quote(author,quote)
            quote_results.append(quote_object)

    return quote_results


from math import pi

number = int(input('Enter a number between 1-17\n'))
if number < 1 or number > 17:
    print('You must input a number between 1 and 17')
else:
    pi = str(pi)
    number_str = str(number)
    print('The value of pi is ' + pi)
    if number == 2:
        print('That\'s a decimal point!')
    else:
        print('Digit ' + number_str + ' in pi is ' + pi[number - 1])


"""
QLearning algorithm for reinforcement learning
"""
import math
# import time

import numpy as np

BOARD_SIZE = 3
LEARNING_RATE = 0.2
DISCOUNT = 0.9
INIT_EPS = 0.8
MIN_EPS = 0

class QLearning:  # pylint: disable=too-few-public-methods
    """
    QLearning algorithm for reinforcement learning
    """

    def __init__(self, env, output_connector, seed=None):
        self.env = env
        self.output_connector = output_connector

        # Set the random seed for reproducibility if desired
        if seed is not None:
            np.random.seed(seed)

        # Discretize the space (see q_learning_example for better example)
        # Number of states is observation state size: 3 states * number of cells
        # TODO derive this from env.observation_space
        num_states = np.array([3] * BOARD_SIZE * BOARD_SIZE)

        # Initialize Q table
        q_states_list = list(num_states)
        # Add a columns for listing actions
        # TODO derive this from env.action_space
        q_states_list.append(BOARD_SIZE * BOARD_SIZE)
        self.output_connector.debug('q_states_dims {}'.format(q_states_list))
        self.q_table = np.random.uniform(low=-1,
                                         high=1,
                                         size=tuple(q_states_list))

    def train(self, episodes):
        """
        Run training episodes
        """
        # Calculate episodic reduction in epsilon
        reduction = (INIT_EPS - MIN_EPS) / episodes
        epsilon = INIT_EPS

        # Run Q learning algorithm
        for episode_iteration in range(episodes):

            # Initialize parameters
            is_done = False
            tot_reward, reward = 0, 0
            state = self.env.reset()

            # Discretize state (see q_learning_example for better example)
            state_adj = (state - self.env.observation_space.low)

            self.output_connector.begin_episode(episode_iteration, state)
            step_iteration = 0
            while not is_done:
                step_iteration += 1
                reward, state2_adj, is_done = self._learning_step(
                    state_adj, step_iteration, epsilon)

                # Update variables
                tot_reward += reward
                state_adj = state2_adj

            # Decay epsilon
            if epsilon > MIN_EPS:
                epsilon -= reduction

            # Track rewards
            self.output_connector.end_episode(tot_reward)

        self.env.close()

    def _learning_step(self, state_adj, step_iteration, epsilon):
        """
        Define a single learning step
        """
        # Render environment for last 20 episodes and every 1000 episondes
        # if (episode_iteration >= (episodes - 20) or
        #         episode_iteration % 1000 == 0) and reward != 0.3:
        #     time.sleep(.002)
        #     self.env.render()

        # Determine next action - epsilon greedy strategy
        if np.random.random() < 1 - epsilon:
            state_adj_tuple = tuple(np.ndarray.flatten(state_adj))
            flat_action = np.argmax(self.q_table[state_adj_tuple]).item()
            action = (math.floor(flat_action / BOARD_SIZE),
                      flat_action % BOARD_SIZE)
        else:
            action = self.env.action_space.sample()
            flat_action = action[0] * BOARD_SIZE + action[1]

        # Get next state and reward
        state2, reward, is_done, info = self.env.step(action)
        self.output_connector.take_step(step_iteration, action, state2, reward,
                                        is_done, info)

        # Discretize state2
        state2_adj = (state2 - self.env.observation_space.low)
        state2_index = tuple(list(np.ndarray.flatten(state2_adj)))
        transition_index = list(np.ndarray.flatten(state_adj))
        transition_index.append(flat_action)
        transition_index = tuple(transition_index)

        # Allow for terminal states
        if is_done:
            self.q_table[transition_index] = reward

        # Adjust Q value for current state
        else:
            delta = LEARNING_RATE * (
                reward + DISCOUNT * np.max(self.q_table[state2_index]) -
                self.q_table[transition_index])
            self.q_table[transition_index] += delta

        return reward, state2_adj, is_done