"""
Module containing methods for reading from financial data database
"""
import pandas as pd
import sqlite3
from decimal import Decimal

class FdRead:
    def __init__(self, db_address):
        self.db_address = db_address

    def read_asset_values(self, asset_tickers, startDate=None, endDate=None):
        """Get all values of list of assets in date range

        Args:
        assetTickers: List[String] | Names of asset tickers
        startDate: datetime.Date | lower bound on date
        endDate: datetime.Date | upper bound on date

        Return:
        Pandas dataframe of format:
        {Columns: [AOpen<Decimal.decimal>, AClose<Decimal.decimal>,
                   AHigh<Decimal.decimal>, ALow<Decimal.decimal>]
         Index: [AssetTicker<String>, ADate <datetime.date>]}
        containing AssetValues with date between start and end date and assetTicker
        in assetTickers
        """
        # cast asset_tickers to list ensure appending works
        asset_tickers = list(asset_tickers)
        # Optionally move name to seperate config file later
        conn = sqlite3.connect(self.db_address)
        # generate parameter list for subsitution
        generated_params = "(" + ",".join(["?"] * len(asset_tickers)) + ")"

        # construct query
        query = (
            "SELECT * \
                 FROM AssetValue \
                 WHERE AssetValue.AssetTicker IN "
            + generated_params
            + " "
        )
        if startDate is not None:
            query += "AND (AssetValue.ADate >= ?) "
            asset_tickers.append(str(startDate))
        if endDate is not None:
            query += "AND (AssetValue.ADate <= ?) "
            asset_tickers.append(str(endDate))
        # read data into df
        df0 = pd.read_sql(query + ";", conn, params=asset_tickers)
        conn.close()
        # fix types
        df0["AOpen"] = df0["AOpen"].map(Decimal)
        df0["AClose"] = df0["AClose"].map(Decimal)
        df0["AHigh"] = df0["AHigh"].map(Decimal)
        df0["ALow"] = df0["ALow"].map(Decimal)
        df0["ADate"] = pd.to_datetime(df0["ADate"], format="%Y-%m-%d %H:%M:%S")
        df0.set_index(["AssetTicker", "ADate"], inplace=True)
        return df0

    def read_assets(self):
        """Get records of all financial assets stored in db that have associated asset values

        Args:
        None

        Return:
        Pandas dataframe of format
        {Columns: [Name<String>, AssetClassName<String>]
                   Index: [AssetTicker<String>]}
        each row containing details of an asset
        currently saved in db

        Notes:
        Will only return assets that have associated asset values stored in AssetValues table
        If nothing stored will return empty dataframe of same format
        """
        # Optionally move name to seperate config file later
        conn = sqlite3.connect(self.db_address)
        # read data in df
        df0 = pd.read_sql(
            "SELECT * \
         FROM Asset WHERE Asset.AssetTicker IN (SELECT AssetTicker FROM AssetValue)",
            conn,
        )
        conn.close()
        # adjust index if neccesary
        df0.set_index("AssetTicker", inplace=True)
        return df0

    def read_assets_in_class(self, asset_class):
        """Get records of all assets in an asset class with values in AssetValues

        Args:
        assetClass: string | Name of asset class

        Return:
        Pandas dataframe of format
        {Columns: [Name<String>, AssetClassName<@assetClass>]
                   Index: [AssetTicker<String>]}
        each row containing details of an asset
        currently saved in db with asset class equal to assetClass

        Notes:
        - Will only return assets that have asset values stored in AssetValues table

        - If assetClass not in database, return empty dataframe in format

        - Will return AssetClass row in dataframe despite all values being equal
        (this is so dataframe can be used with fdWrite library methods as-is)

        - Implements seperate query to getAssetClasses due to performance
        considerations (Large number of assets should not be in working memory
        unless needed)
        """
        # Optionally move name to seperate config file later
        conn = sqlite3.connect(self.db_address)
        # read data in df
        df0 = pd.read_sql(
            "SELECT * \
         FROM Asset \
         WHERE Asset.AssetClassName = $className AND Asset.AssetTicker IN (SELECT AssetTicker FROM AssetValue);",
            conn,
            params={"className": asset_class},  # use params dict to sanitize input
        )
        conn.close()
        # adjust index if neccesary
        df0.set_index("AssetTicker", inplace=True)
        return df0

    def read_assets_div_payout(self, asset_tickers):
        """Get record of all divident payouts for specific asset

        Args:
        asset_tickers: list of strings of asset tickers | asset ticker

        Return:
        Pandas dataframe of format
        {Columns: [Payout<decima.Decimal>]
                   Index: [AssetTicker<String>, PDate<datetime.date>]}

        Notes:
        - If assetTicker not in database, return empty dataframe in format

        - Will return AssetTicker row in dataframe despite all values being equal
        (this is so dataframe can be used with fdWrite library methods as-is)
        """
        # Optionally move name to seperate config file later
        conn = sqlite3.connect(self.db_address)
        generated_params = "(" + ",".join(["?"] * len(asset_tickers)) + ")"

        # construct query
        query = (
            "SELECT * \
                 FROM DividendPayout \
                 WHERE DividendPayout.AssetTicker IN "
            + generated_params
            + " "
        )
        # read data into df
        df0 = pd.read_sql(query + ";", conn, params=asset_tickers)
        conn.close()

        df0["Payout"] = df0["Payout"].map(Decimal)
        df0["PDate"] = pd.to_datetime(df0["PDate"], format="%Y-%m-%d %H:%M:%S")

        df0.set_index(["AssetTicker", "PDate"], inplace=True)
        return df0

    def read_asset_classes(self):
        """Get records of all asset classes stored in fin database

        Args:
        None

        Return:
        Pandas dataframe of format
        {Columns: [] Index: [AssetClassName<String>]}
        each row containing details of an assetClass
        currently stored in db

        Notes:
        If nothing stored will return empty dataframe of same format
        """
        # Optionally move name to seperate config file later
        conn = sqlite3.connect(self.db_address)
        # read data in df
        df0 = pd.read_sql(
            "SELECT * \
         FROM AssetClass",
            conn,
        )
        conn.close()
        # adjust index if neccesary
        df0.set_index("AssetClassName", inplace=True)
        return df0


import tkinter as tk
from tkinter import ttk

from src.python.yahtzee.src.logic.game import Game
from src.python.yahtzee.src.logic.player import Player
from src.python.yahtzee.src.logic.table import ScoreType

class PossibleMovesGui:
    """
    GUI for the possible moves.
    """

    def __init__(self, frame: ttk.Frame, player: Player, game: Game, parent_gui):
        self.frame = frame
        self.player = player
        self.game = game
        self.parent_gui = parent_gui
        self.draw()

    def draw(self) -> None:
        """
        Draws all the widgets.
        """
        # remove every child of self.frame
        for child in self.frame.winfo_children():
            child.destroy()

        # if it's not players turn don't draw anything
        if self.game.current_player != self.player:
            return

        # draw each possible move as a button
        i = -1
        for i, score_type in enumerate(self.player.valid_rules()):
            button = ttk.Button(self.frame, text=score_type.name)
            button.grid(row=i, column=0, pady=10)
            button.config(
                command=lambda score_type=score_type: self.update_table(score_type)
            )

        roll_button = ttk.Button(self.frame, text="Roll dice")
        roll_button.config(command=self.parent_gui.roll_dice)
        roll_button.grid(row=i + 1, column=0, pady=10)

    def update_table(self, score_type: ScoreType) -> None:
        """
        Updates the table with the score_type.

        :param score_type: score_type to update the table with
        """
        self.game.update_current_player_table(score_type)
        self.parent_gui.draw()


import json
import urllib.request, urllib.parse, urllib.error

from django.shortcuts import render
from django.http import HttpResponse
from stats import models
from django.shortcuts import redirect
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
from django import forms

# Create your views here.

@cache_page(0)
def index(request):
    channelNameHash = 'web'
    channelName = '#' + 'web'
    # fullUserCount = models.getFullUserCount(channelName)
    mostFullTime = __getMostFullTime(channelName)
    topic = models.getChannelTopic(channelName)
    fiddles = models.getLatestFiddles(channelName)
    totalMessagesFromChannel = '{0:,}'.format(models.getTotalMessagesFromChannel(channelName))
    current_user = request.user
    is_authenticated = request.user.is_authenticated()
    is_op = request.user.groups.filter(name='ops').exists()
    return render(request, 'stats/index.html', locals())

@cache_page(0)
def getUserInfo(request, username):
    current_user = request.user
    is_authenticated = request.user.is_authenticated()
    channelName = '#' + 'web'
    # This user does not exist in the database
    if (models.hasUserSpoken(username) == False):
        #render a 'cannot find user' page
        return render(request, 'stats/nouser.html', locals())

    username = models.getNormalizedUserName(username)
    mostFullTime = __getMostFullTime(channelName)
    firstAndLastSeenConvo = models.getFirstAndLastSeen(channelName, username)
    firstSeen = firstAndLastSeenConvo[0]
    lastSeen = firstAndLastSeenConvo[1]
    isUserOnline = models.isUserOnline(username)
    userMessageCountOverall = '{0:,}'.format(models.userMessageCountOverall(channelName, username))
    fiddles = models.getLatestFiddles(channelName, username)

    # Get the last time the user was seen
    notSeenFor = {}
    notSeenFor['days'] = models.lastSeenDelta(channelName, username).days
    notSeenFor['seconds'] = models.lastSeenDelta(channelName, username).seconds
    notSeenFor['hours'] = notSeenFor['seconds'] // 3600
    notSeenFor['seconds'] = notSeenFor['seconds'] - (notSeenFor['hours'] * 3600)
    notSeenFor['minutes'] = notSeenFor['seconds'] // 60
    notSeenFor['seconds'] = (notSeenFor['minutes'] * 60)

    avgPostsPerDay = round(models.avgPerDay('#web', username), 2)
    return render(request, 'stats/userinfo.html', locals())

def search(request):
    current_user = request.user
    is_authenticated = request.user.is_authenticated()
    if request.method == 'GET':
        q = request.GET.get('q', None)
        if q:
            results = models.search('web', q)

    return render(request, 'stats/searchLanding.html', locals())

def getConvoPartial(request, id):
    current_user = request.user
    is_authenticated = request.user.is_authenticated()
    id = int(id)
    id = id - 10;
    results = models.getConvoPartialFromID('#web', id, 100)
    id = id + 10;
    return render(request, 'stats/log_convo.html', locals())

    # ----- Open API stuff ------

def userInfo(request, userName):
    data = {}
    if models.getNormalizedUserName(userName):
        data['username'] = userName = models.getNormalizedUserName(userName)
        data['isUserOnline'] = models.isUserOnline(userName)
        data['karma'] = models.getKarma(userName)['karma__sum']
        # Get the last time the user was seen
        notSeenFor = {}
        notSeenFor['days'] = models.lastSeenDelta('#web', userName).days
        notSeenFor['seconds'] = models.lastSeenDelta('#web', userName).seconds
        notSeenFor['hours'] = notSeenFor['seconds'] // 3600
        notSeenFor['seconds'] = notSeenFor['seconds'] - (notSeenFor['hours'] * 3600)
        notSeenFor['minutes'] = notSeenFor['seconds'] // 60
        notSeenFor['seconds'] = (notSeenFor['minutes'] * 60)
        data['userNotSeenFor'] = notSeenFor

        #  get JS fiddles if user has any
        data['fiddles'] = models.getLatestFiddles('#web', userName)
        if (data['fiddles']):
            for fiddle in data['fiddles']:
                fiddle['timestamp'] = str(fiddle['timestamp'])
                del fiddle['user']

        #  Get last seen and first seem
        lastSeen = models.getUserLastSeen('#web', userName)
        data['lastSeen'] = {}
        data['lastSeen']['message'] = lastSeen.content
        data['lastSeen']['timeStamp'] = str(lastSeen.timestamp)
        data['lastSeen']['messageID'] = lastSeen.id

        firstSeen = models.getUserFirstSeen('#web', userName)
        data['firstSeen'] = {}
        data['firstSeen']['message'] = firstSeen.content
        data['firstSeen']['timestamp'] = str(firstSeen.timestamp)
        data['firstSeen']['messageID'] = firstSeen.id

        # Message count
        data['messageCount'] = models.userMessageCountOverall('#web', userName)
        data['avgPostsPerDay'] = models.avgPerDay('#web', userName)

        return HttpResponse(json.dumps(data), content_type="application/json")

    else:
        return HttpResponse(json.dumps({'statusCode': '404', 'response':'Sorry no available user: ' + userName}), status=404)

@csrf_exempt
def addKarma(request, userName):
    userName = models.getNormalizedUserName(userName)
    if userName:
        if request.method == 'POST':
            points = int(request.POST['points'])
            models.addKarma(userName, points)
            return HttpResponse(json.dumps({'statusCode': '200', 'response':'karma updated for ' + userName}), status=200)
        else:
            return HttpResponse(json.dumps({'statusCode': '405', 'response':'Sorry this api is only for POST'}), status=405)
    else:
        return HttpResponse(json.dumps({'statusCode': '404', 'response':'Sorry no available user'}), status=404)

    # ------Private API stuff -----

def getFullUserCount(request):
    channelName = '#' + 'web'
    fullUserCount = models.getFullUserCount(channelName)
    return HttpResponse(json.dumps(fullUserCount), content_type="application/json")

def getFullUserCountToday(request):
    channelName = '#' + 'web'
    fullUserCount = models.getFullUserCountToday(channelName)
    return HttpResponse(json.dumps(fullUserCount), content_type="application/json")

def getFullUserCountWeek(request):
    channelName = '#' + 'web'
    fullUserCount = models.getFullUserCountWeek(channelName)
    return HttpResponse(json.dumps(fullUserCount), content_type="application/json")

def getKarmaUsers(request):
    channelName = '#' + 'web'
    karmaUsers = models.getKarmaUsers(channelName)
    return HttpResponse(json.dumps(karmaUsers), content_type="application/json")

def getChattyUsers(request):
    channelName = '#' + 'web'
    chattyUsers = models.getChattyUsers(channelName)
    return HttpResponse(json.dumps(chattyUsers), content_type="application/json")

def __getMostFullTime(channelName):
    mostFullTime = models.getMostFullTime(channelName)
    return mostFullTime

def getUserTimeOnline(request, userName):
    channelName = '#' + 'web'
    userName = urllib.parse.unquote(userName)
    return HttpResponse(json.dumps(models.getUserTimeOnline(channelName, userName)), content_type="application/json")

    # ----- Bans -------
@cache_page(0)
def showBansPage(request):
    current_user = request.user
    is_authenticated = request.user.is_authenticated()
    is_op = request.user.groups.filter(name='ops').exists()
    if not is_op:
        return redirect('stats_home')
    bansList = models.get_list_of_bans()
    return render(request, 'stats/bans.html', locals())

@csrf_exempt
def reIndexBans(request):
    models.process_bans_table()
    return HttpResponse(json.dumps({"message": "Table Updated"}), content_type="application/json")

def adjustBan(request, ID):
    if (request.method == "POST"):
        requestObj = json.loads(request.body.decode('utf-8'))
        requestObj['last_modified'] = request.user.__str__()

        if models.update_ban_obj(ID, requestObj):
            return HttpResponse(json.dumps({"message": "Added!"}), content_type="application/json", status=201)
        else:
            return HttpResponse(status=400)
    else:
        return HttpResponse(status=405)
    #   req = request.POST
    #   banInput = {}

    #   if 'reminderTime' in req:
    #       banInput['reminderTime'] = req.get('reminderTime')

    #   if 'reason' in req:
    #       banInput['reason'] = req.get('reason')

    #   if models.update_ban_obj(ID, banInput) == False:
    #       return HttpResponse(json.dumps({"message": "Unable to find that ID or Wrong input"}), content_type="application/json")
    #   else:
    #       return HttpResponse(json.dumps({"message": "Added!"}), content_type="application/json")
    # else:
    #   return redirect('stats.views.showBansPage')

def apiBansIndex(request):
    bansList = models.get_list_of_bans()
    viewList = []
    for ban in bansList:
        banObject = {}
        banObject['user'] = ban.user_name
        banObject['banmask'] = ban.banmask
        banObject['banned_by'] = ban.banned_by
        banObject['timestamp'] = ban.timestamp.__str__()
        banObject['ban_length'] = ban.ban_length
        banObject['last_modified'] = ban.last_modified
        # print(ban.ban_length is None)
        if ban.unban_date is None:
            banObject['unban_date'] = None
        else:
            banObject['unban_date'] = ban.unban_date.strftime("%Y-%m-%d")
        banObject['id'] = ban.id
        banObject['reason'] = ban.reason
        viewList.append(banObject)

    return HttpResponse(json.dumps(viewList), content_type="application/json")


#!/user/bin/env python3

# Cuyamaca College CS-119
# Christian Luciano
# Lab 8 exercise 2 Player Class Implementation

from Employee import Employee
from Student import Student

name = input('Enter name: ')
age = int(input('Enter age:'))
major = input('Enter major: ')
units = input('Enter units: ')
years_worked = input("Enter years worked: ")
job_skills = input("Enter job skills: ")

student = Student(name, age, major, units)
employee = Employee(name, age, job_skills, years_worked )

print(student.to_string())
print(employee.to_string())


# 保存模型/加载模型
from keras.models import load_model
import matplotlib.pyplot as plt

# model.save('model_p01')  # creates a HDF5 file 'dl_T.h5'
# del model  # 删除现有模型
# # 加载已保存模型
model = load_model('model_p01')
acc = h.history['accuracy']
val_acc = h.history['val_accuracy']
loss = h.history['loss']
val_loss = h.history['val_loss']
epochs = range(len(acc))

plt.plot(epochs,acc, 'b', label='Training accuracy')
plt.plot(epochs, val_acc, 'r', label='validation accuracy')
plt.title('Training and validation accuracy')
plt.legend(loc='lower right')
plt.figure()

plt.plot(epochs, loss, 'r', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()


def jumlah(*bilangan):
    total = 0
    for angka in bilangan:
        total = total + angka

    rataRata = total / len(bilangan)
    return total, rataRata

inputBilangan = input("Masukkan angka, pisahkan dengan tanda koma: ")
bilangan = list(map(int, inputBilangan.split(",")))

hasil_total, hasil_rata_rata = jumlah(*bilangan)

formatted_bilangan = ' + '.join(map(str, bilangan))

print(f"Total = {formatted_bilangan} = {hasil_total}")
print(f"Rata-Rata = {hasil_total}/{len(bilangan)} = {hasil_rata_rata}")


import argparse

def parse_command_line_arguments():
    parser = argparse.ArgumentParser(description="Speech Recorder")
    parser.add_argument(
        "-r", "--rate", type=int, default=16000, help="Sampling rate (default: 16000)"
    )
    parser.add_argument(
        "-k",
        "--keyboard-key",
        type=str,
        default="caps lock",
        help="Keyboard key to start/stop recording (default: 'caps lock')",
    )
    parser.add_argument(
        "-l",
        "--language",
        type=str,
        default=None,
        help="Language code (default: None)",
    )
    parser.add_argument(
        "-s",
        "--save",
        type=bool,
        default=False,
        help="Save recorded audio (default: False)",
    )
    parser.add_argument(
        "-t",
        "--translate",
        type=bool,
        default=False,
        help="Translate text (default: False)",
    )
    parser.add_argument(
        "-m",
        "--model-name",
        type=str,
        default="large-v2",
        help="Model name (default: 'large-v2') (tiny, tiny.en, base, base.en, small,\
              small.en, medium, medium.en, large-v1, or large-v2)",
    )
    parser.add_argument(
        "-d",
        "--model-dir",
        type=str,
        default=None,
        help="Model dir (default: '~/.cache/huggingface')",
    )

    return parser.parse_args()


'''10. Write a Python program to print every integer between 1 and n divisible by m. Also
report whether the number that is divisible by m is even or odd.'''

# solution
n=int(input("Enter the limit : "))
m=int(input("Enter the number : "))
for i in range(1,n+1):
  if i%m == 0:
    if i%2==0:
      print(f"{i} is even")
    else:
      print(f"{i} is odd")


# autobyteus/source_code_tree/file_explorer/traversal_ignore_strategy/git_ignore_strategy.py

import os
import fnmatch
import pathlib

from autobyteus.source_code_tree.file_explorer.traversal_ignore_strategy.traversal_ignore_strategy import TraversalIgnoreStrategy

class GitIgnoreStrategy(TraversalIgnoreStrategy):
    """
    A strategy to ignore files and folders specified in a .gitignore file.
    """

    def __init__(self, root_path: str):
        """
        Initialize GitIgnoreStrategy.

        Args:
            root_path (str): The root path of the workspace.
        """
        self.root_path = pathlib.Path(root_path)  # Store the root path as a Path object
        self.ignore_patterns = []
        gitignore_path = os.path.join(root_path, '.gitignore')
        if os.path.exists(gitignore_path):
            with open(gitignore_path, 'r') as gitignore_file:
                self.ignore_patterns = gitignore_file.read().splitlines()

    def should_ignore(self, path: str) -> bool:
        """
        Determines if a file or folder should be ignored based on patterns specified in a .gitignore file.

        The method iterates over all the ignore patterns. For each pattern, if it's a directory pattern
        (ending with '/'), it removes the trailing slash and appends one to the path (if it's not already there)
        before performing the match. For file patterns, it performs the match directly.

        Args:
            path (str): The path of the file or folder.

        Returns:
            bool: True if the file or folder matches a pattern in the .gitignore file and should be ignored,
                  False otherwise.
        """
        relative_path = pathlib.Path(path).relative_to(self.root_path)  # Compute the relative path
        for pattern in self.ignore_patterns:
            if pattern.endswith('/'):  # The pattern is for a directory
                if fnmatch.fnmatch(os.path.join(relative_path, ''), pattern):
                    return True
            else:  # The pattern is for a file
                if fnmatch.fnmatch(relative_path, pattern):
                    return True
        return False


from pypegase.pypegase import *
import pandas as pd
import argparse
import multiprocessing
from tqdm import tqdm
import numpy as np

def parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-z','--z',help='Redshift',default=0.0,type=str)
    parser.add_argument('-ne','--neb',action='store_true')
    parser.add_argument('-tr','--time_res',help='Time resolution',default=5,type=int)
    parser.add_argument('-s','--savename',help='Save name',default='new')
    args = parser.parse_args()
    return args

def generate_scenario(age,args):
    s = Scenario(binaries_fraction=0.04, metallicity_ism_0=0, infall=True,
             sfr=SFR(SFR.FILE_SFR, p1=1000, p2=1,
                     filename='/media/data3/wiseman/des/AURA/PEGASE/SFHs/sfh_%i.dat' % age),
             metallicity_evolution=True, substellar_fraction=0, neb_emission=args.neb,
             extinction=Extinction.NO_EXTINCTION)
    return s

def main(args):
    store = pd.HDFStore('/media/data3/wiseman/des/desdtd/SFHs/SFHs_alt_0.5_Qerf_1.1.h5', 'r')
    ordered_keys = np.sort([int(x.strip('/')) for x in store.keys()])
    scenario_list = [generate_scenario(a,args) for a in ordered_keys[::-1][np.arange(0,len(ordered_keys),args.time_res)]]
    peg = PEGASE(args.savename, ssps=SSP(IMF(IMF.IMF_Kroupa), ejecta=SNII_ejecta.MODEL_B, galactic_winds=True),
                 scenarios=scenario_list)
    peg.generate()
    counter=1
    for tf in tqdm(ordered_keys[::-1][np.arange(0,len(ordered_keys),args.time_res)]):

        spec = peg.spectra(scenario=counter)
        counter+=1
        templates = spec.to_pandas()
        templates.to_hdf('/media/data3/wiseman/des/AURA/PEGASE/templates_analytic_%s_%i.h5'%(args.savename,tf), key='main')

    return

if __name__=="__main__":
    args = parser()
    main(args)


import numpy as np
import torch
import librosa
import librosa.display
import pandas as pd
from IPython.display import Audio
import seaborn as sns
import os
import librosa
import librosa.display

from scipy.signal import convolve, fftconvolve

from collections import defaultdict

import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import label_ranking_average_precision_score
from sklearn.model_selection import train_test_split

min_db = -100
PREEMPHASIS = 0.97
ref_db = 20

# алгоритм Гриффин-Лим

def griffin_lim(S, num_iter=20):
    np.random.seed(42)
    # реализуйте алгоритм для добавления к вещественной матрице S фазы
    # на выходе нужно вернуть комплексную матрицу
    # ...

    phi = 2 * np.pi * np.random.rand()
    H = istft(S * np.exp(1j * phi))

    for iteration in range(num_iter):
        phi = np.angle(stft(H))
        H = istft(S * np.exp(1j * phi))

    return stft(H)
#     return H

def load(config, path):
    signal, _ = librosa.load(path, sr=config.sampling_rate)
    return signal

def show(audio):
    return Audio(audio, rate=sample_rate)

def mel_to_linear(M):
    return np.dot(inv_mel_basis, M)

def inv_normalize(S):
    return S * -min_db + min_db

def db_to_amp(x):
    return 10**(x/20)

def de_emphasis(x):
    # Это эквивалентно scipy.signal.lfilter([1], [1, PREEMPHASIS], x)
    return scipy.signal.lfilter([1, PREEMPHASIS], [1, 0, -PREEMPHASIS**2], x)# ...

def inv_melspectrogram(M):
    M = inv_normalize(M)
    M = mel_to_linear(db_to_amp(M + ref_db))
    M = istft(griffin_lim(M))
    x = de_emphasis(M)
    return x

def read_audio(conf, pathname, trim_long_data):
    y, sr = librosa.load(pathname, sr=conf.sampling_rate)
    # trim silence
    if 0 < len(y): # workaround: 0 length causes error
        y, _ = librosa.effects.trim(y) # trim, top_db=default(60)

    # return y
    # make it unified length to conf.samples
    if len(y) > conf.samples: # long enough
        if trim_long_data:
#             y = y[0:0+123121523]
            # print(conf.samples, len(y))
            y = y[0:0+conf.samples]
    else: # pad blank
        padding = conf.samples - len(y)    # add padding at both ends
        offset = padding // 2
        y = np.pad(y, (offset, conf.samples - len(y) - offset), 'constant')
    return y

def trim_and_mel(conf, audio):
    if len(audio) > conf.samples:
        audio = audio[:conf.samples]

    result = audio_to_melspectrogram(conf, audio)
    return result

def audio_to_melspectrogram(conf, audio):
    spectrogram = librosa.feature.melspectrogram(audio,
                                                 sr=conf.sampling_rate,
                                                 n_mels=conf.n_mels,
                                                 hop_length=conf.hop_length,
                                                 n_fft=conf.n_fft,
                                                 fmin=conf.fmin,
                                                 fmax=conf.fmax)
    spectrogram = librosa.power_to_db(spectrogram)
    spectrogram = spectrogram.astype(np.float32)
    return spectrogram

def show_melspectrogram(conf, mels, title='Log-frequency power spectrogram'):
    librosa.display.specshow(mels, x_axis='time', y_axis='mel',
                             sr=conf.sampling_rate, hop_length=conf.hop_length,
                            fmin=conf.fmin, fmax=conf.fmax)
    plt.colorbar(format='%+2.0f dB')
    plt.title(title)
    plt.show()

def read_as_melspectrogram(conf, pathname, trim_long_data, debug_display=False):
    x = read_audio(conf, pathname, trim_long_data)
    mels = audio_to_melspectrogram(conf, x)
    if debug_display:
        IPython.display.display(IPython.display.Audio(x, rate=conf.sampling_rate))
        show_melspectrogram(conf, mels)
    return mels

def read_columns():
    columns = pd.read_csv("./data/sample_submission.csv").columns[1:]
    column_encoder = {c:id for id, c in enumerate(columns)}

    return columns, column_encoder

def read_dataset(path, config, transform):
    meta = pd.read_csv(path + ".csv")
    all_data = []
    all_labels = []

    max_len = 0

    for id, (f, label) in tqdm.tqdm(enumerate(zip(meta.fname, meta.labels)), total=len(meta)):
        all_labels.append(label)
        all_data.append(transform(read_audio(config, os.path.join(path, f), trim_long_data=config.trim_long_data)))
        max_len = max(all_data[-1].shape[-1], max_len)

    y = np.zeros((len(all_data), len(config.columns)))
    for id, label in enumerate(all_labels):
        labels = label.split(",")
        for l in labels:
            y[id, config.column_encoder[l]] = 1.0

    return all_data, y, max_len

def read_dataset_split(metapath, path, config, transform):
    labels = pd.read_csv(metapath)
    labels = labels.set_index("fname")
    meta = list(os.listdir(path))
    meta.sort()
    all_data = []
    all_labels = []

    max_len = 0

    for id, f in tqdm.tqdm(enumerate(meta), total=len(meta)):
        label = labels.loc[f]['labels']
        all_labels.append(label)
        all_data.append(transform(read_audio(config, os.path.join(path, f), trim_long_data=config.trim_long_data)))
        max_len = max(all_data[-1].shape[-1], max_len)

    y = np.zeros((len(all_data), len(config.columns)))
    for id, label in enumerate(all_labels):
        labels = label.split(",")
        for l in labels:
            y[id, config.column_encoder[l]] = 1.0

    return all_data, y, max_len

def read_test(path, config, transform):
    all_data = []
    max_len = 0
    meta = list(os.listdir(path))
    meta.sort()

    for id, f in tqdm.tqdm(enumerate(meta), total=len(meta)):
        all_data.append(transform(read_audio(config, os.path.join(path, f), trim_long_data=config.trim_long_data)))
        max_len = max(all_data[-1].shape[-1], max_len)

    y = np.zeros((len(all_data), len(columns)))

    return meta, all_data, y, max_len

def read_filters(path, config, transform):
    all_data = []
    max_len = 0
    meta = list(os.listdir(path))
    meta.sort()

    for id, f in tqdm.tqdm(enumerate(meta), total=len(meta)):
        pathname = os.path.join(path, f)
        audio, sr = librosa.load(pathname, sr=config.sampling_rate)
        all_data.append(transform(audio))

    return meta, all_data

def apply_filter(sound, filter):
    modified_sound = fftconvolve(in2=filter, in1=sound) #/ np.linalg.norm(sound)
    return modified_sound

def predict(trainer, meta, loader):
    prediction = trainer.predict(loader)
    result = {col:prediction[:, id] for id, col in enumerate(columns)}
    result['fname'] = meta
    result = pd.DataFrame(result)
    result = result.set_index('fname').reset_index()

    return result

sampling_rate = 44100 # от оргов контеста
duration = 2 # сколько секунд от записи хотим взять
n_samples = sampling_rate * duration
n_mels=128 # дефолтный параметр в самой либросе

def audio2mel(audio):
    #audio, _ = librosa.effects.trim(audio) # убирает участки тишины из audio, почти не влияет, да и хз, может вредит
    melspectr = librosa.feature.melspectrogram(
        y=audio,
        sr=sampling_rate,
        n_mels=n_mels, # количество мел-признаков, дефолтное значение для librosa
        n_fft=n_mels * 20, # не знаю, почему так, но это ширина окна для FFT (размер базиса, получается?)
        hop_length=346 * duration, # длина фрейма, n_samples // 128, чтобы получить 128 фреймов (или что-то такое)
        # ось времени таки есть!
        fmax=sampling_rate // 2, # максимальная частота сигнала, дефолтное значение для librosa,
        fmin = 0., # дефолтная наименьшая частота сигнала
    )
    melspectr = librosa.power_to_db(melspectr).astype(np.float32) # перевод в дб
    return melspectr

def read_dataset_kirill(path, config, transform):
    meta = pd.read_csv(path + ".csv")
    all_data = []
    all_labels = []

    max_len = 0

    for id, (f, label) in tqdm.tqdm(enumerate(zip(meta.fname, meta.labels)), total=len(meta)):
        all_labels.append(label)
        fp = os.path.join(path, f)
        y, _ = librosa.load(fp, sr=sampling_rate) # загрузка аудиофайла
        # в кернелах они делают паддинг нулями с двух сторон, я делаю паддинг нулями в начале записи
        y = np.concatenate([[0] * (n_samples - len(y)), y[:n_samples]]) # паддинг
        mel = audio2mel(y)
        all_data.append(mel)
        max_len = max(all_data[-1].shape[-1], max_len)

    y = np.zeros((len(all_data), len(config.columns)))
    for id, label in enumerate(all_labels):
        labels = label.split(",")
        for l in labels:
            y[id, config.column_encoder[l]] = 1.0

    return all_data, y, max_len

def read_dataset_kirill_split(metapath, path, config, transform):
    labels = pd.read_csv(metapath)
    labels = labels.set_index("fname")
    meta = list(os.listdir(path))
    meta.sort()
    all_data = []
    all_labels = []

    max_len = 0

    for id, f in tqdm.tqdm(enumerate(meta), total=len(meta)):
        label = labels.loc[f]['labels']
        all_labels.append(label)
        fp = os.path.join(path, f)
        y, _ = librosa.load(fp, sr=sampling_rate) # загрузка аудиофайла
        # в кернелах они делают паддинг нулями с двух сторон, я делаю паддинг нулями в начале записи
        y = np.concatenate([[0] * (n_samples - len(y)), y[:n_samples]]) # паддинг
        mel = audio2mel(y)
        all_data.append(mel)
        max_len = max(all_data[-1].shape[-1], max_len)

    y = np.zeros((len(all_data), len(config.columns)))
    for id, label in enumerate(all_labels):
        labels = label.split(",")
        for l in labels:
            y[id, config.column_encoder[l]] = 1.0

    return all_data, y, max_len


# coding=utf-8
# Create your views here.
from django.template import Context, loader
from django.http import HttpResponse
from django.shortcuts import render_to_response
#use to make json
from django.core import serializers
from familytree.models import *
#import simplejson,json

#use local() return all agruments
def index(request):
    return render_to_response('index.html')

def ft(request):
    #member = Member.objects.get(pk=1)
    return render_to_response('action.html')

def setname(mj):
    """
    """
    for m in mj:
        namestr = ""
        if m['fields']['mentee'] != "":
            youngerlist = m['fields']['mentee'].split(',')
            for younger in youngerlist:
                member = Member.objects.get(pk = younger)
                namestr = namestr + member.__unicode__() + ","
        m['fields']['menteename'] = namestr
        if m['fields']['mentor'] != "":
            member = Member.objects.get(pk = m['fields']['mentor'])
            m['fields']['mentorname'] = member.__unicode__()
        namestr = ""
        if m['fields']['sementor'] != "":
            selist = m['fields']['sementor'].split(',')
            for se in selist:
                member = Member.objects.get(pk = se)
                namestr = namestr + member.__unicode__() + ","
        m['fields']['sementorname'] = namestr
    return mj

def Give_branch(request):
    mydata = request.GET["mydata"]
    mimeformat = 'json'
    mimetype = 'application/javascript'
    #serialize中只能用.objects.all()  不能用.objects.get(...)吗??
    #member = data = serializers.serialize(mimeformat,Member.objects.all())
    #return HttpResponse(member,mimetype)
    try:
        member = Member.objects.get(pk=mydata)
    except Member.DoesNotExist:
        return HttpResponse('')
    s = member.mentee
    sementorlist = member.sementor.split(',')
    if (s=='' or s=="0") and (member.sementor == '' or member.sementor=="0"):
        return HttpResponse("none")
    youngerlist = s.split(',')
    ks = []
    for younger in youngerlist:
        try:
            if younger != "":
                member = Member.objects.get(pk=younger)
                ks.append(member)
        except Member.DoesNotExist:
            continue
        #return HttpResponse(member.younger)
            #raise Http404
    for se in sementorlist:
        try:
            if se != "":
                member = Member.objects.get(pk=se)
                ks.append(member)
        except Member.DoesNotExist:
            continue
    haha = serializers.serialize('json',ks)
    myjson = simplejson.loads(haha)
    da = myjson[0]['fields']['mentee']
    setname(myjson)
    return HttpResponse(json.dumps(myjson))#haha)

def alldata(request):
    #mimeformat = 'json'
    #mimetype = 'application/javascript'
    #serialize中只能用.objects.all()  不能用.objects.get(...)吗??
    #member = data = serializers.serialize(mimeformat,Member.objects.all())
    #return HttpResponse(member,mimetype)
    member = Member.objects.get(name="UniqueStudio")
    head = 0
    tail = 1
    ks = []
    ks.append(member)
    record = []
    record.append(-1)

    num = []
    count = -1

    while tail != head:
        array = ks[head].younger.split(",")
        num.append(0)
        count += 1
        for arr in array:
            try:
                member = Member.objects.get(name=arr)
                ks.append(member)
                record.append(head)
                tail += 1
                num[count] += 1
            except Member.DoesNotExist:
                continue
        head += 1

    haha = serializers.serialize('json',ks)
    data = []
    data.append(haha)
    data.append(record)

    new_num = [1]
    what = 1
    pos = 1
    new_num.append(0)
    for n in num:
        if what == 0:
            new_num.append(n)
            what = new_num[pos]-1
            pos += 1
        else:
            what -= 1
            new_num[pos] += n

    #data.append(num)
    data.append(new_num)
    return HttpResponse(data)

def getmentor(request):
     #mimeformat = 'json'
    #mimetype = 'application/javascript'
    #serialize中只能用.objects.all()  不能用.objects.get(...)吗??
    #member = data = serializers.serialize(mimeformat,Member.objects.all())
    #return HttpResponse(member,mimetype)
    member = Member.objects.get(name="UniqueStudio")
    head = 0
    tail = 1
    ks = []
    ks.append(member)
    record = []
    record.append(-1)

    num = []
    count = -1

    while tail != head:
        array = ks[head].younger.split(",")
        num.append(0)
        count += 1
        for arr in array:
            try:
                member = Member.objects.get(name=arr)
                ks.append(member)
                record.append(head)
                tail += 1
                num[count] += 1
            except Member.DoesNotExist:
                continue
        head += 1

    haha = serializers.serialize('json',ks)
    data = []
    #data.append(haha)
    #data.append(record)

    new_num = [1]
    what = 1
    pos = 1
    new_num.append(0)
    for n in num:
        if what == 0:
            new_num.append(n)
            what = new_num[pos]-1
            pos += 1
        else:
            what -= 1
            new_num[pos] += n

    #data.append(num)
    data.append(new_num)
    return HttpResponse(data)

def normal(request):
    member = Member.objects.all().order_by('-highest_degree_year')
    grade = []
    count = -1
    num = []
    for m in member:
        if len(grade)==0 or grade[count]!=m.highest_degree_year:
            num.append(1)
            grade.append(m.highest_degree_year)
            count += 1
        else:
            num[count] += 1
    width_array = []
    for n in num:
        width_array.append((n-0.5)*133)

    height = len(grade)*143

    return render_to_response('normal.html',{'member':member,'grade':grade,'num':num,'width_array':width_array,'height':height})

def search(request):
    mydata = request.GET["mydata"]
    try:
        member = Member.objects.get(user_name=mydata)
    except Member.DoesNotExist:
        return HttpResponse("none")
    all_member = Member.objects.all()#.order_by("-grade")                mydata = m.name
    s = ""
    mentor_number = member.cur_mentor
    while 1:
        member = Member.objects.get(pk=int(mentor_number))
        mentor_number = member.cur_mentor
        if member.pk == 1:
            s += member.user_name
            break
        s += member.user_name+","
    return HttpResponse(s)

def new_normal(request):
    member = Member.objects.all().order_by("highest_degree_year")
    grade = []
    count = -1
    for m in member:
        if count == -1 or grade[count]!=m.highest_degree_year:
            if m.highest_degree_year == '0':
                continue
            grade.append(m.highest_degree_year)
            count += 1
    return render_to_response("normal.html",{"grade":grade})

def data_by_grade(request):
    mydata = request.GET["mydata"]
    member = Member.objects.all()
    data = []
    for m in member:
        if m.highest_degree_year == mydata:
            data.append(m)
    haha = serializers.serialize('json',data)
    return HttpResponse(haha)

def normal_search(request):
    mydata = request.GET["mydata"]
    try:
        member = Member.objects.get(name=mydata)
    except Member.DoesNotExist:
        return HttpResponse("none")
    return HttpResponse(member.grade)

def change_team(request):
    org = request.GET["org"].lower()
    new = request.GET["new"]
    if org != new.lower():
        return HttpResponse("error")
    member = Member.objects.all()
    count = 0
    test = 0
    for m in member:
        if m.team.lower() == org:
            test = m.team.lower()
            m.team = new
            m.save()
            count += 1
    return HttpResponse(count)

def about(request):
    return render_to_response("about.html")

def update(request):
    data = request.GET["value"]
    my_id = request.GET["id"]
    try:
        member = Member.objects.get(pk=my_id)
    except Member.DoesNotExist:
        return HttpResponse("error")
    value = data.split(",")
    change = 0
    if member.name_first != value[0]:
        member.name_first = value[0]
        change = 1
    if member.name_middle != value[1]:
        member.name_middle = value[1]
        change = 1
    if member.name_last != value[2]:
        member.name_last = value[2]
        change = 1
    if member.imgurl != value[3]:
        member.imgurl = value[3]
        change = 1
    if member.homepage != value[4]:
        member.homepage = value[4]
        change = 1
    if member.highest_degree_name != value[5]:
        member.highest_degree_name = value[5]
        change = 1
    if member.highest_degree_insti != value[6]:
        member.highest_degree_insti = value[6]
        change = 1
    if member.highest_degree_year != value[7]:
        if value[7] != "N/A":
            member.highest_degree_year = value[7]
            change = 1
    if member.highest_degree_depart != value[8]:
        member.highest_degree_depart = value[8]
        change = 1
    if member.cur_title != value[9]:
        member.cur_title = value[9]
        change = 1
    if member.keywords != value[10]:
        member.keywords = value[10]
        change = 1
    if member.other_info != value[11]:
        member.other_info = value[11]
        change = 1
    if member.mentor != value[12]:
        member.mentor = value[12]
        change = 1
    if member.mentee != value[13]:
        member.mentee = value[13]
        change = 1
    if member.collaborators != value[14]:
        member.collaborators = value[14]
        change = 1
    if member.organization_info != value[15]:
        member.organization_info = value[15]
        change = 1
    member.save()
    if change == 1:
        return HttpResponse("success")
    else:
        return HttpResponse("none")

def add(request):
    f_id = request.GET["f_id"]
    name = request.GET["name"]
    mytype = request.GET["type"]
    name_arr = name.split(",")
    if mytype == "3" or mytype == 3:
        m = Member(name_first=name_arr[0],name_middle=name_arr[1],name_last=name_arr[2],is_people=2)
        m.save()
        mentor = Member.objects.get(pk=int(f_id))
        if mentor.sementor=="0" or mentor.sementor=="":
            mentor.sementor = str(m.pk)
        else:
            mentor.sementor += ","+str(m.pk)
        mentor.save()
        ks = []
        ks.append(m)
        haha = serializers.serialize('json',ks)
        return HttpResponse(haha)

    m = Member(name_first=name_arr[0],name_middle=name_arr[1],name_last=name_arr[2],is_people=mytype)
    m.save()
    mentor = Member.objects.get(pk=int(f_id))
    if mentor.mentee=="0" or mentor.mentee=="":
        mentor.mentee = str(m.pk)
    else:
        mentor.mentee += ","+str(m.pk)
    mentor.save()
    m.mentor = mentor.pk
    m.save()
    ks = []
    ks.append(m)
    haha = serializers.serialize('json',ks)
    return HttpResponse(haha)

def searchinfo(request):
    mytype = request.GET["type"]
    value = request.GET["value"]
    data = []
    if mytype == "1":
        try:
            member = Member.objects.all()
        except Member.DoesNotExist:
            return HttpResponse("error")
        name1 = value.split(" ")
        name = (''.join(name1)).lower()
        for m in member:
            m_name = (m.name_first+m.name_middle+m.name_last).lower()
            pos = m_name.find(name)
            if pos != -1:
                data.append(m)
        haha = serializers.serialize('json',data)
        return HttpResponse(haha)
    elif mytype == "2":
        try:
            member = Member.objects.all()
        except Member.DoesNotExist:
            return HttpResponse("error")
        data = []
        name1 = value.split(" ")
        name = ''.join(name1)
        for m in member:
            m_name = m.name_first+m.name_middle+m.name_last
            pos = m_name.find(name)
            if pos != -1 and m.is_people=="2":
                youngerlist = m.mentee.split(',')
                for younger in youngerlist:
                    try:
                        member = Member.objects.get(pk=younger)
                        data.append(member)
                    except Member.DoesNotExist:
                        continue
                break
        haha = serializers.serialize('json',data)
        return HttpResponse(haha)
    elif mytype == "3":
        try:
            member = Member.objects.filter(location=value)
        except Member.DoesNotExist:
            return HttpResponse("error")
    elif mytype == "4":
        try:
            member = Member.objects.filter(department=value)
        except Member.DoesNotExist:
            return HttpResponse("error")
    else:
        return HttpResponse("error")
    haha = serializers.serialize('json',member)
    return HttpResponse(haha)

def del_child(member):
    s = member.mentee
    if s != "":
        mentee_str = s.split(',')
        for  m_str in mentee_str:
            if m_str != "":
                try:
                    m = Member.objects.get(pk=m_str)
                    del_child(m)
                except Member.DoesNotExist:
                    v = 1
    member.delete()
    return 1

def delete(request):
    f_id = request.GET["f_id"]
    mytype = request.GET["type"]
    member = Member.objects.get(pk=f_id)
    if mytype == "1":
        del_child(member)
    elif mytype == "2":
        s = member.mentee
        string = s.split(',')
        for s1 in string:
            m = Member.objects.get(pk=s1)
            m.mentor = member.mentor
            m.save()
    mentor = Member.objects.get(pk=member.mentor)
    s = mentor.mentee
    men = s.split(',')
    new_mentee = ""
    for m in men:
        if m != f_id and m!="":
            new_mentee += m+","
    mentor.mentee = new_mentee
    if mytype == "2":
        mentor.mentee = mentor.mentee + member.mentee
        member.delete()
    mentor.save()
    return HttpResponse("1")

def con(request):
    f_id = request.GET["f_id"]
    c_id = request.GET["c_id"]
    try:
        c_node = Member.objects.get(pk=int(c_id))
    except Member.DoesNotExist:
        return HttpResponse("error")
    try:
        f_node = Member.objects.get(pk=int(f_id))
    except Member.DoesNotExist:
        return HttpResponse("error")
    c_node_father = Member.objects.get(pk = int(c_node.mentor))
    m_arr = c_node_father.mentee.split(",")
    m_str = ""
    for m in m_arr:
        if m == c_id or m =="":
            continue
        m_str += m+","
    c_node_father.mentee = m_str[0:-1]
    c_node_father.save()

    c_node.mentor = f_id
    c_node.save()

    if f_node.mentee == "":
        f_node.mentee = c_id
    else:
        f_node.mentee+=","+c_id
    f_node.save();
    return HttpResponse("success")


'''
New Update 28-10-2019 Time 7:16 PM
'''

import sys
import json
import os
import webbrowser

import winsound

from PyQt5.QtWidgets import *

from  Creat_New_Task import AddTaskWindow

from PyQt5.QtGui import QIcon

from PyQt5.QtCore import Qt

from PyQt5.QtCore import QTimer

from PyQt5.QtGui import QFont

from PyQt5.QtCore import QDate

import time

from datetime import datetime

from PyQt5.QtCore import QTime

class window(QMainWindow):

    def __init__(self):

        super(window,self).__init__()

        self.show_AddTaskWindow = AddTaskWindow()

        self.UI()

        self.center()

        self.update_list_task()

        self.show()

    def update_list_task(self):

        self.Task_List.clear()

        try:
            task_data_file = open("task_data.txt","r")

            self.data = json.load(task_data_file)

            for task in self.data:

                global task_list_item

                task_list_item = QListWidgetItem()

                task_list_item.setText(task)

                task_list_item.setFlags(task_list_item.flags() | Qt.ItemIsUserCheckable)

                for i in self.data[task]:

                    self.Task_List.addItem(task_list_item)

                    task_list_item.setCheckState(i["Done"])

                    if i["Done"] == 0:

                        task_list_item.setFont(self.font_StrikeOut)
                    elif i["Done"]==2:
                        task_list_item.setFont(self.font_UnStrikeOut)

            return task_list_item

        except:

            pass

    def UI(self):

        self.font_StrikeOut = QFont()
        self.font_StrikeOut.setStrikeOut(True)

        self.font_UnStrikeOut = QFont()

        self.font_UnStrikeOut.setStrikeOut(False)

        #=========================== Main Window Setup
        self.setWindowTitle("My Tasks Today")
        self.setGeometry(500,50,290,800)
        self.setWindowIcon((QIcon("../images/images.png")))
        self.setMaximumHeight(800)
        self.setMaximumWidth(290)
        self.widget = QWidget(self)
        self.setCentralWidget(self.widget)
        #========================== Layout Setup
        self.Vertical_Layout = QVBoxLayout()
        self.Horizontal_Layout = QHBoxLayout()
        self.Horizontal_Layout02 = QHBoxLayout()
        self.Horizontal_Layout03 = QHBoxLayout()
        #========================== Widgets Setup
        self.Button_Add = QPushButton("Add")
        self.Button_Add.clicked.connect(self.add_task)

        self.Button_Remove = QPushButton("Remove")
        self.Button_Remove.clicked.connect(self.remove_task)

        self.Button_refresh = QPushButton("Refresh")
        self.Button_refresh.clicked.connect(self.refresh)

        self.timer = QTimer(self)
        self.alarm_timer = QTimer(self)
        self.alarm_timer.setInterval(50)
        self.alarm_timer.timeout.connect(self.alarm)
        self.alarm_timer.start()
        self.timer.setInterval(50)
        self.timer.stop()
        self.timer.timeout.connect(self.show_me)

        self.tool_bar = QToolBar("Tool Bar")
        self.new_Tool = QAction(QIcon("../images/document_add_100293.png"),"NewTask")
        self.tool_bar.addAction(self.new_Tool)
        self.edit_Tool = QAction(QIcon("../images/misc_edit_98007.jpg"),"EditTask")
        self.tool_bar.addAction(self.edit_Tool)
        self.delete_Tool = QAction(QIcon("../images/document_delete_100294.png"),"DeleteTask")
        self.tool_bar.addAction(self.delete_Tool)
        self.show_AddTaskWindow.save_button.clicked.connect(lambda: self.save_task(2))

        self.show_AddTaskWindow.cancel_button.clicked.connect(self.close_window)

        self.refresh_Tool = QAction(QIcon("../images/rounded_blue_refresh_button_4808.png"),"RefreshTasks")
        self.tool_bar.addAction(self.refresh_Tool)

        self.new_Tool.triggered.connect(self.add_task)
        self.delete_Tool.triggered.connect(self.remove_task)
        self.refresh_Tool.triggered.connect(self.refresh)
        self.edit_Tool.triggered.connect(self.edit_task)
        self.tool_bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)

        self.Task_List = QListWidget()
        self.Task_List.itemClicked.connect(self.task_one_click)

        #self.Task_List.doubleClicked.connect(self.run_task)
        self.data_table = QTableWidget()
        self.data_table.setMaximumHeight(200)
        self.data_table.setRowCount(5)
        self.data_table.setColumnCount(1)
        self.data_table.setColumnWidth(0,self.maximumWidth()-40)
        self.data_table.setVerticalHeaderItem(0, QTableWidgetItem("Name"))
        self.data_table.setVerticalHeaderItem(1, QTableWidgetItem("Link"))
        self.data_table.setVerticalHeaderItem(2, QTableWidgetItem("End By"))
        self.data_table.setVerticalHeaderItem(3, QTableWidgetItem("Status"))
        self.data_table.setVerticalHeaderItem(4, QTableWidgetItem("Notes"))
        self.data_table.setRowHeight(4,70)
        self.data_table.horizontalHeader().hide()
        self.data_table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.data_table.cellDoubleClicked.connect(self.run_task)

        #=========================== Add Widget to Layout
        self.Vertical_Layout.addWidget(self.tool_bar)
        #self.Horizontal_Layout.addWidget(self.Button_Add)

        #self.Horizontal_Layout.addWidget(self.Button_Remove)
        self.Horizontal_Layout02.addWidget(self.Task_List)

        #self.Horizontal_Layout03.addWidget(self.Button_refresh)

        #================================================
        self.Vertical_Layout.addLayout(self.Horizontal_Layout03)
        self.Vertical_Layout.addLayout(self.Horizontal_Layout)
        self.Vertical_Layout.addLayout(self.Horizontal_Layout02)
        self.Vertical_Layout.addWidget(self.data_table)
        self.show_AddTaskWindow.update_button.clicked.connect(self.update_task)
        self.widget.setLayout(self.Vertical_Layout)

        #============================================ Build Actions

    def add_task(self):

        now = datetime.now()

        self.show_AddTaskWindow.show()

        self.show_AddTaskWindow.setWindowTitle("Add New Task")

        self.show_AddTaskWindow.save_button.setHidden(False)

        self.show_AddTaskWindow.update_button.setHidden(True)

        self.show_AddTaskWindow.date.setTime(QTime(datetime.now().time().hour,datetime.now().time().minute,datetime.now().time().second))

        self.show_AddTaskWindow.date.setDate(QDate(datetime.now().date()))

        self.timer.start()

        self.update_list_task()

    def table_data_build(self,item_name,link,dead_line,status,note):

        try:

            self.data_table.setItem(0,0,QTableWidgetItem(item_name))

            self.data_table.setItem(1, 0, QTableWidgetItem(link))

            self.data_table.setItem(2, 0, QTableWidgetItem(dead_line))

            if status == 0:

                status_ = "Done"

            elif status == 2:

                status_ = "In Progress"

            else:

                status_ = "None"

            self.data_table.setItem(3, 0, QTableWidgetItem(status_))

            self.data_table.setItem(4, 0, QTableWidgetItem(note))

        except:

            print ("Error To Apply")

    def remove_task(self):

        try:
            self.message = QMessageBox.question(self,"Confirm",'Are You Sure! You Need To Delete "%s""'%self.Task_List.currentItem().text(),QMessageBox.Yes,QMessageBox.No)

            if self.message == QMessageBox.Yes:

                del self.data[self.Task_List.currentItem().text()]

                outfile = open("task_data.txt","w")

                json.dump(self.data, outfile,indent=4)

                self.Task_List.takeItem(self.Task_List.row(self.Task_List.selectedItems()[0]))
        except:

            self.message = QMessageBox.information(self, "Hold","Nothing to Remove", QMessageBox.Ok)

    def refresh(self):

        python = sys.executable

        os.execl(python, python, *sys.argv)

    def run_task(self):

        for i in self.data[self.Task_List.currentItem().text()]:

            webbrowser.open_new(i['website'])

    def task_one_click(self,item):

        try:
            check_state = item.checkState()

            task_data_file = open("task_data.txt", "r")

            data = json.load(task_data_file)

            self.update_done_startus(item,item.text(),check_state)

            for data_ in data[item.text()]:

                self.table_data_build(item.text(),data_["website"],data_["Dead_Line"],data_["Done"],data_['Note'])
        except:
            print("Error")

    def edit_task(self):

        try:

            self.timer.start()

            self.show_AddTaskWindow.task_name.setText(self.Task_List.currentItem().text())

            self.show_AddTaskWindow.task_link.setText(self.data[self.Task_List.currentItem().text()][0]['website'])

            self.show_AddTaskWindow.task_notes.setText(self.data[self.Task_List.currentItem().text()][0]['Note'])

            dead_line_date = self.data[self.Task_List.currentItem().text()][0]['Dead_Line'].split(" || ")

            self.show_AddTaskWindow.date.setDate(QDate(datetime.strptime(dead_line_date[0], '%a %b %d %Y')))

            dead_line_time = dead_line_date[1].split(":")

            self.show_AddTaskWindow.date.setTime(QTime(int(dead_line_time[0]), int(dead_line_time[1]), int(dead_line_time[2]) ))

            self.show_AddTaskWindow.save_button.setHidden(True)

            self.show_AddTaskWindow.update_button.setHidden(False)

            self.show_AddTaskWindow.setWindowTitle("Edit %s" % self.Task_List.currentItem().text())

            self.show_AddTaskWindow.show()
        except:
            self.message_err = QMessageBox.information(self, "Hold", "Select Item From The List", QMessageBox.Ok)

    def show_me(self):

        if self.show_AddTaskWindow.isVisible():

            self.setDisabled(True)

        else:

            self.setDisabled(False)

            self.update_list_task()

            self.timer.stop()

    def update_task(self):

        self.delete_old_task()

        self.save_task(2)

        self.update_list_task()

    def delete_old_task(self):

        global current_task

        current_task = self.Task_List.currentItem().text()

        self.data.pop(current_task, None)

        outfile = open("task_data.txt", "w")

        json.dump(self.data, outfile, indent=4)

    def save_task(self,Done=2):

        task_name_var = self.show_AddTaskWindow.task_name.toPlainText()

        task_link_var = self.show_AddTaskWindow.task_link.toPlainText()

        task_note_var = self.show_AddTaskWindow.task_notes.toPlainText()

        try:
            task_data_file = open("task_data.txt", "r")

            data = json.load(task_data_file)

        except:

            data = {}
        outfile = open("task_data.txt", "w")

        data['%s'%task_name_var] = []

        data['%s'%task_name_var].append({'name': task_name_var,'website': task_link_var, "Done": Done,

        "Dead_Line" : "%s || %s" %(self.show_AddTaskWindow.date.date().toString() , self.show_AddTaskWindow.date.time().toString()) ,

        "Date" : self.show_AddTaskWindow.date.date().toString(), "Status": "False","Note":task_note_var,
        })

        outfile.seek(0)

        json.dump(data, outfile,indent=4)

        self.show_AddTaskWindow.close()

    def alarm(self):
        now = datetime.now()

        try:
            try:
                task_data_file = open("task_data.txt", "r")

                data = json.load(task_data_file)

            except:

                data = {}

            for task in data:

                for data_ in data[task]:

                    data_date = data_["Dead_Line"].split(" || ")

                    if data_date[1][:-3] == now.time().strftime("%H:%M") and QDate(datetime.strptime(data_date[0], '%a %b %d %Y')) == now.date():

                        if data_["Status"] == "False":

                            task_data_file = self.update_list_task()

                            task_data_file.setCheckState(0)

                            task_data_file.setFont(self.font_StrikeOut)

                            outfile = open("task_data.txt", "w")

                            print(data_["name"],data_["Status"])

                            del data_["Status"]

                            del data_["Done"]

                            data_["Done"] = 0

                            data_["Status"] = "True"

                            #
                            outfile.seek(0)
                            #
                            json.dump(data, outfile, indent=4)
                            #self.setWindowFlag(Qt.WindowStaysOnTopHint)
                            winsound.PlaySound("ALERT.wav", winsound.SND_FILENAME )
                            message = QMessageBox.information(self,"Time's Gone!" ,"%s | Task Hase Ended "%data_["name"],QMessageBox.Ok)
                            if message == QMessageBox.Ok:
                                task_data_file.setSelected(1)

                                self.setWindowFlag(Qt.StrongFocus)

                            break

        except:
            pass

    def update_done_startus(self,item,task_name_var,Done=2):

        try:
            task_data_file = open("task_data.txt", "r")

            data = json.load(task_data_file)

        except:

            data = {}

        outfile = open("task_data.txt", "w")

        for don in data['%s'%task_name_var]:

            del don["Done"]

            don["Done"]= Done

        if Done == 0:

            item.setFont(self.font_StrikeOut)
        elif Done == 2:

            item.setFont(self.font_UnStrikeOut)

        print(item.checkState())

        outfile.seek(0)

        json.dump(data, outfile,indent=4)

    def close_window(self):

        self.show_AddTaskWindow.close()

    def center(self):
        frameGm = self.frameGeometry()

        screen = QApplication.desktop().screenNumber(QApplication.desktop().cursor().pos())

        centerPoint =QApplication.desktop().screenGeometry(screen).center()

        frameGm.moveCenter(centerPoint)

        self.move(frameGm.topLeft())

if __name__ == "__main__":
    app = QApplication(sys.argv)
    import qdarkstyle

    app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
    window = window()

    sys.exit(app.exec_())


from typing import Tuple

def chinese_remainder_gaussian(a, mod_prod, n):
    result = 0
    for i in range(len(n)):
        result += a[i] * mod_prod // n[i] * inverse_mod((mod_prod // n[i]), n[i])
    return result % mod_prod

def inverse_mod(a: int, b: int) -> Tuple[int, int, int]:
    d = b
    x0, x1, y0, y1 = 0, 1, 1, 0
    while a != 0:
        (q, a), b = divmod(b, a), a
        y0, y1 = y1, y0 - q * y1
        x0, x1 = x1, x0 - q * x1
    return x0 % d

def main(filename: str) -> None:
    with open(filename) as file:
        departure = int(file.readline().strip())
        buses = [int(x) for x in file.readline().split(',') if x != 'x']
    next_bus_time = [bus + departure - (departure % bus) for bus in buses]
    next_bus = next_bus_time.index(min(next_bus_time))
    print(f"Part 1: {buses[next_bus] * (next_bus_time[next_bus] - departure)}")

if __name__ == "__main__":
    main("input.txt")


import tkinter as tk
import time
import weather
from PIL import Image,ImageTk

def tick():
    time_string = time.strftime("%H:%M:%S")
    clock.config(text=time_string)
    clock.after(200, tick)

def display_weather(current_info):
    if current_info < len(weather_info):
        weather_condition_label.config(text=weather_info[current_info][0])
        if weather_info[current_info][0] != "Pogoda":
            weather_condition_info.config(image='')
            weather_condition_info.config(text=weather_info[current_info][1])
        else:
            im = Image.open('icon/' + weather_info[current_info][1] + '.png')
            im = im.resize((20, 20), Image.ANTIALIAS)
            ph = ImageTk.PhotoImage(im)
            weather_condition_info.config(image=ph)
            weather_condition_info.image = ph

        weather_condition_label.after(2000, display_weather,current_info+1)
    else:
        current_info = 0
        weather_condition_label.config(text=weather_info[current_info][0])
        weather_condition_info.config(text=weather_info[current_info][1])
        weather_condition_label.after(2000, display_weather,current_info+1)

def update_weather():

    current_w = weather.get_current_weather('a874452b76f1cc6022316d344c4ac034','Poznan')
    weather_info = weather.dict_to_string_tuple(current_w)
    weather_condition_info.after(1800000)
root = tk.Tk()
root.wm_attributes('-type', 'splash') #to dodalem zeby usunelo gorny pasek z minimlaizacja itp
root.geometry("100x100")
root.resizable(0, 0) #Don't allow resizing in the x or y direction
root.geometry("+0+800")

frame = tk.Frame(root, width=150, height=150) #size of the info square
frame.pack()

current_w = weather.get_current_weather('a874452b76f1cc6022316d344c4ac034','Poznan')
weather_info = weather.dict_to_string_tuple(current_w)
current_info = 0

weather_condition_label = tk.Label(frame, text="Cloudiness:",font=("Calibri",10))
weather_condition_label.pack()

weather_condition_info = tk.Label(frame, text="55%",font=("Calibri",10))
weather_condition_info.pack()
display_weather(current_info)

line_break = tk.Label(frame, text="",font=("Calibri",10))
line_break.pack()

clock = tk.Label(frame, text="00:00:00",font=("Calibri",13,"bold"))
clock.pack()
tick()

root.attributes('-topmost', True)

root.mainloop()


import os
import requests
from flight_data import FlightData

TEQUILA_ENDPOINT = "https://api.tequila.kiwi.com"
TEQUILA_API_KEY = os.environ("TEQUILA_API_KEY")

class FlightSearch:
    #This class is responsible for talking to the Flight Search API.
    def get_destination_codes(self, city_name):
        """return IATA Code to the spreadsheet"""
        # code = "TESTING"
        # return code
        headers = {
            "apikey": TEQUILA_API_KEY
        }

        query = {
            "term": city_name,
            "location_types": "city"
        }

        response = requests.get(
            url=f"{TEQUILA_ENDPOINT}/locations/query",
            headers=headers,
            params=query
        )
        result = response.json()['locations']
        code = result[0]['code']
        return code

    def check_flight(self, origin_city, destination_city, from_date, to_date):
        """return destination and price"""
        headers = {
            "apikey": TEQUILA_API_KEY
        }

        query = {
            "fly_from": origin_city,
            "fly_to": destination_city,
            "date_from": from_date.strftime("%d/%m/%Y"),
            "date_to": to_date.strftime("%d/%m/%Y"),
            "nights_in_dst_from": "7",
            "nights_in_dst_to": "28",
            "flight_type": "round",
            "one_for_city": 1,
            "max_stopovers": 0,
            "curr": "GBP"
        }

        response = requests.get(
            url=f"{TEQUILA_ENDPOINT}/v2/search",
            headers=headers,
            params=query
        )

        try:
            data = response.json()['data'][0]
        except IndexError:
            print(f"No flight found for {flight_data.destination_city}.")
            return None

        flight_data = FlightData(
            price=data['price'],
            origin_airport=data['route'][0]["flyFrom"],
            origin_city=data['route'][0]["cityFrom"],
            destination_airport=data['route'][0]["flyTo"],
            destination_city=data['route'][0]["cityTo"],
            out_date=data['route'][0]['local_departure'].split("T")[0],
            return_date=data['route'][1]['local_departure'].split("T")[0]
        )

        print(f"{flight_data.destination_city}: £{flight_data.price}")

        return flight_data


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This script calculates the coordination number of a set of oxygen atoms
in a molecular dynamics simulation using the MDAnalysis library.
"""

import MDAnalysis as mda
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

def cn_atom(file, r_cut_lo, r_cut_hi):
    """
    Calculates the coordination number of a set of oxygen atoms.

    Parameters
    ----------
    file : str
        Path to the simulation file.
    r_cut_lo : float
        Lower cutoff radius to search for oxygen atoms.
    r_cut_hi : float
        Upper cutoff radius to search for oxygen atoms.

    Returns
    -------
    float
        The average coordination number of the set of oxygen atoms.

    """
    # Load the trajectory and topology
    u = mda.Universe(file)

    # Select only the oxygen atoms
    oxygen = u.select_atoms("prop 30 < z and prop z < 60 and name O1 and around {} name O1 and not around {} name O1".format(r_cut_hi, r_cut_lo))

    coord = [len(u.select_atoms("name O1 and around 3.25 index {}".format(atom.index)))
         for ts in u.trajectory
         if ts.frame == 0
         for atom in oxygen]

    return np.mean(coord)

def graf_cn(X, Y):
    """
    Plots the coordination number as a function of radius.

    Parameters
    ----------
    X : array-like
        Array with the radii.
    Y : array-like
        Array with the corresponding coordination numbers.

    Returns
    -------
    None.

    """
    plt.plot(X, Y, color='black', linestyle='dashed', linewidth=2, label="12")

    plt.title('Coordination number/water', fontsize=18)

    # Add labels to the axes
    plt.xlabel('Radius (Å)', fontsize=16)
    plt.ylabel('Coordination Number (CN)', fontsize=16)

    plt.legend(fontsize=12)

    # Show the plot
    plt.show()

def processing(olig):
    """
    Processes the simulation to calculate the average coordination number
    of a set of oxygen atoms.

    Parameters
    ----------
    olig : int
        Oligomer number to process.

    Returns
    -------
    None.

    """
    # Define the simulation file path
    file = "~/{}_cn.xyz".format(olig)

    # Create an empty DataFrame to store the results
    df = pd.DataFrame(columns=["R", "CN"])

    # Define parameters for coordination number calculation
    radius_p = 20
    step = 5
    final = radius_p + step

    # Iterates over the r_cut values to calculate the coordination number
    for i in np.arange(step, final, step):
        # Calculate the value of r_cut
        r_cut_lo = (final) - i
        r_cut_hi = radius_p - i

        # Calculate the coordination number
        CN = cn_atom(file, r_cut_hi, r_cut_lo)

        # Add a row to the DataFrame with the r_cut values and the current coordination number
        df = df.append({"R": r_cut_lo, "CN": CN}, ignore_index=True)

    # Plot the results
    graf_cn(df.R, df.CN)

if __name__ == '__main__':
    for olig in [4, 8, 12, 24, 36]:
        processing(olig)


import torch.cuda
import yaml
import torch
import numpy as np
import random

def seed_all(seed):
    if not seed:
        seed = 17

    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    torch.cuda.manual_seed(seed)
    np.random.seed(seed)
    random.seed(seed)
    torch.backends.cudnn.deterministic = False
    torch.backends.cudnn.benchmark = False

def get_config(path):
    with open(path, 'r') as f:
        conf = yaml.safe_load(f)

    return conf

def get_device():
    return 'cuda:0' if torch.cuda.is_available() else 'cpu'


import sys
import os
import time
import atexit
import signal
import logging

class Daemon:
    EXIT_OK = 0
    EXIT_OTHER_ERROR = 1
    EXIT_PARAM_ERROR = 2

    def __init__(self, pidfile):
        self.pidfile = pidfile

    def daemonize(self):
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(self.EXIT_OK)
        except OSError as err:
            logging.error('fork #1 failed: {0}'.format(err))
            sys.exit(self.EXIT_OTHER_ERROR)

        os.chdir('/')
        os.setsid()
        os.umask(0)

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(self.EXIT_OK)
        except OSError as err:
            logging.error('fork #2 failed: {0}'.format(err))
            sys.exit(self.EXIT_OTHER_ERROR)

        sys.stdout.flush()
        sys.stderr.flush()
        si = open(os.devnull, 'r')
        so = open(os.devnull, 'a+')
        se = open(os.devnull, 'a+')

        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        atexit.register(self.delpid)

        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as f:
            f.write(pid + '\n')

    def delpid(self):
        os.remove(self.pidfile)

    def start(self):
        try:
            with open(self.pidfile, 'r') as pf:

                pid = int(pf.read().strip())
        except IOError:
            pid = None

        if pid:
            logging.warning("pidfile {0} already exist. Daemon already running?".format(self.pidfile))
            sys.exit(self.EXIT_OTHER_ERROR)

        self.daemonize()
        self.run()

    def stop(self):
        try:
            with open(self.pidfile, 'r') as pf:
                pid = int(pf.read().strip())
        except IOError:
            pid = None

        if not pid:
            logging.warning("pidfile {0} does not exist. Daemon not running?".format(self.pidfile))
            return

        try:
            while 1:
                os.kill(pid, signal.SIGTERM)
                time.sleep(0.1)
        except OSError as err:
            e = str(err.args)
            if e.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                logging.error(str(err.args))
                sys.exit(self.EXIT_OTHER_ERROR)

    def restart(self):
        self.stop()
        self.start()

    def status(self):
        try:
            with open(self.pidfile, 'r') as pf:
                pid = int(pf.read().strip())
        except IOError:
            pid = None

        if not pid:
            logging.error("Service not running".format(self.pidfile))
            sys.exit(self.EXIT_OTHER_ERROR)

        try:
            os.kill(pid, 0)
        except OSError as err:
            logging.error("Service not running".format(self.pidfile))
            sys.exit(self.EXIT_OTHER_ERROR)

        logging.info("Service running".format(self.pidfile))
        sys.exit(self.EXIT_OTHER_ERROR)

    def run(self):
        pass


from Film import Film
import pickle
from random import randint

#search_text = ""
class Arama():
    film_list = []

    def __init__(self):
        with open('imdb.pkl','rb') as input:
            self.film_list = pickle.load(input)

    def searchParametresiz(self):
        """
            Butun filmler arasindan random bir film secilir...
        """
        rnd = randint(0,len(self.film_list)-1)
        return self.film_list[rnd]

    def search(self,search_text):
        """
            Parametre olarak String alir.
            Aranan film ismi filmler listesinde aynen varsa(tami tamina ayni olmali) aranan filmi obje olarak returnler.
            Aranan film ismi filmler listesinde yoksa 'False' returnler.
        """
        search_text = search_text.lower()
        for film in self.film_list:
            if search_text in film.name.lower():
                return film
        return False

    def searchGenre(self,genre):
        film_list = []
        for film in self.film_list:
            if genre in film.genre.lower():
                film_list.append(film)

        rnd = randint(0,len(film_list)-1)
        return film_list[rnd]

    def oneri(self,searched_film):
        """
            Parametre olarak bir adet film nesnesi alir.
            Aranan filmle ayni veya benzer kategoride film varsa bu filmlerden bir tanesini rastgele secer ve film objesi olarak returnler.
            Aranan filmle ayni veya benzer kategoride film yoksa 'False' returnler.
        """
        if searched_film == False:
            return False

        searched_film_genres = searched_film.genre.replace(' ','').split(',')
        film_list = []
        film_list_same_genre = []
        for film in self.film_list:
            #ayni filmi onerme
            if film.name != searched_film.name:
                if film.genre == searched_film.genre:
                    film_list_same_genre.append(film)
                else:
                    film_genres = film.genre.replace(' ','').split(',')
                    for genre in film_genres:
                        if genre in searched_film_genres:
                            film_list.append(film)

        if len(film_list_same_genre) > 0:
            rnd = randint(0,len(film_list_same_genre)-1)
            return film_list_same_genre[rnd]
        elif len(film_list) > 0:
            rnd = randint(0,len(film_list)-1)
            return film_list[rnd]
        else:
            return False


"""empty message

Revision ID: 39ba72132c24
Revises:
Create Date: 2017-07-30 10:33:51.261042

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '39ba72132c24'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('first_name', sa.String(length=20), nullable=False),
    sa.Column('last_name', sa.String(length=20), nullable=False),
    sa.Column('email', sa.String(length=20), nullable=False),
    sa.Column('password', sa.LargeBinary(), nullable=False),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('email')
    )
    op.create_table('bucketlists',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=20), nullable=False),
    sa.Column('description', sa.String(length=150), nullable=True),
    sa.Column('user', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['user'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('items',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=20), nullable=False),
    sa.Column('date_added', sa.DateTime(), nullable=True),
    sa.Column('date_completed', sa.DateTime(), nullable=True),
    sa.Column('complete_status', sa.Boolean(), nullable=True),
    sa.Column('bucketlist', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['bucketlist'], ['bucketlists.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('items')
    op.drop_table('bucketlists')
    op.drop_table('users')
    # ### end Alembic commands ###


def hamming(s1: str, s2: str) -> int:

    c = 0
    for a, b in zip(s1, s2):
        if a != b:
            c += 1

    return c

if __name__ == '__main__':
    print(hamming('abc', 'bbc'))


lista = []
listaPar = []
listaImpar = []
cont = 0
verify = 'S'
while verify.upper() == 'S':
    num = int(input("Digite um número:"))
    lista.append(num)
    cont += 1
    verify = str(input("Deseja Continuar ? [S]:"))
for i in lista:
    if i % 2 == 0:
        listaPar.append(i)
    else:
        listaImpar.append(i)
print(f'Lista completa: {lista}')
print(f'Lista dos pares: {listaPar}')
print(f'Lista dos impares: {listaImpar}')


import os
import errno
import re

PACKAGE_REGEXP = r"^(.*?\/)?([a-z0-9_-]+\/[a-z0-9_-]+)([:@][a-z0-9._-]+|@sha256:[a-z0-9]+)?$"
# r"^(.*?)?\/?([a-z0-9_-]+\/[a-z0-9_-]+?)([:@].*)?$"

def get_media_type(mediatype):
    if mediatype:
        match = re.match(r"application/vnd\.cnr\.[a-z_-]+\.(.+?)\.(.+).(.+)", mediatype)
        if match:
            mediatype = match.group(1)
    return mediatype

def package_filename(name, version, media_type):
    return "%s_%s_%s" % (name.replace("/", "_"), version, media_type)

def parse_version(version):
    if version is None or version == "default":
        return {'key': "version", "value": "default"}
    elif str.startswith(version, "@sha256:"):
        return {'key': 'digest',
                'value': version.split("@sha256:")[1]}
    elif version[0] == "@":
        return {'key': 'version',
                'value': version[1:]}
    elif version[0] == ":":
        return {'key': 'channel',
                'value': version[1:]}
    else:
        return {'key': 'unknown', 'value': version}

def split_package_name(name):
    sp = name.split("/")
    package_parts = {"host": None,
                     "namespace": None,
                     "package": None,
                     "version": None}

    if len(sp) >= 1:
        package_parts["host"] = sp[0]
    if len(sp) >= 2:
        package_parts["namespace"] = sp[1]
    if len(sp) >= 3:
        match = re.match(r"^([a-z0-9_-]+?)([:@].*)?$", sp[2])
        package, version = match.groups()
        package_parts['package'] = package
        package_parts['version'] = version
    return package_parts

def parse_package_name(name, regexp=PACKAGE_REGEXP):
    package_regexp = regexp
    match = re.match(package_regexp, name)
    if match is None:
        raise ValueError("Package '%s' does not match format '[registry/]namespace/name[@version|:channel]'" % (name))
    host, package, version = match.groups()
    if not version:
        version = 'default'
    if not host:
        host = None
    else:
        host = host[:-1]
    namespace, package = package.split("/")
    return {'host': host,
            'namespace': namespace,
            'package': package,
            'version': version}

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise


class GS_Graph_Puml:
    edges    : list
    nodes    : list
    node_type: dict

    def __init__(self,graph):
        self.graph        = graph
        self.puml_options = graph.puml_options
        self.issues       = graph.issues
        self.nodes        = graph.nodes
        self.edges        = graph.edges
        self.notes        = graph.notes
        self.node_type    = graph.node_type
        self.puml         = graph.puml
        self.skin_params  = graph.skin_params

    def render_puml(self, using_jira_nodes=True, reload_issues=False):
        node_text_value = self.puml_options['node-text-value' ]

        if self.puml_options['left-to-right']: self.puml.add_line('left to right direction')
        if self.puml_options['width'        ]: self.puml.add_line('scale {0} width '.format(self.puml_options['width' ]))
        if self.puml_options['height'       ]: self.puml.add_line('scale {0} height'.format(self.puml_options['height']))

        for skin_param in self.skin_params:
            line = "skinparam {0} {1}".format(skin_param[0], skin_param[1])
            self.puml.add_line(line)
        self.puml.add_line('')

        if using_jira_nodes is False:
            self.issues = {}
        else:
            if self.issues is None or reload_issues is True:            # only reload if the issue object is not set or reload_issues is set to True
                self.issues =  self.graph.get_nodes_issues()

        for key in self.nodes:
            if node_text_value is None:
                self.puml.add_card(key, key)
            else:
                issue = self.issues.get(key)
                if issue and type(issue) is dict:
                    key_text = issue.get(node_text_value)
                    if self.puml_options['show-key-in-text']:
                        line = f"={key_text}\\n<color:grey><size:10><i>{key}</i></size></color>"        # note: if getting weird formating errors take a look at Puml.max_title
                        if self.node_type.get(key):
                            self.puml.add_node(self.node_type.get(key),line, key)
                        else:
                            self.puml.add_card(line, key)
                    else:
                        line = '{0}'.format(key_text)
                        if self.node_type.get(key):
                            self.puml.add_node(self.node_type.get(key), line, key)
                        else:
                            self.puml.add_card(line, key)
                else:
                    self.puml.add_card(key, key)

        for edge in self.edges:
            from_key  = edge[0]
            link_type = edge[1]
            to_key    = edge[2]
            if self.puml_options['show-edge-labels'] is False:
                link_type = ""
            self.puml.add_edge(from_key, to_key, 'down', link_type)

        for note in self.notes:
            position = note[0]
            key      = self.puml.fix_id(note[1])
            text     = note[2]
            if key:
                line     = f'\n\n\t note {position} of "{key}" \n {text} \n end note'
                self.puml.add_line(line)

        self.puml.enduml()
        self.graph.puml = self.puml
        return self.puml


"""

.. function:: pipe(query:None[,lines:t])

Executes *query* as a shell command and returns the standard output lines as rows of one column table. Setting *lines* parameter to *f* the command output will be returned in one table row.

:Returned table schema:
    - *output* text
        Output of shell command execution

Examples::

.. doctest::

    >>> sql("pipe wc ./testing/colpref.csv")
    C1
    ---------------------------------
     19  20 463 ./testing/colpref.csv
    <BLANKLINE>

.. doctest::
    :hide:

    >>> sql("pipe wc nonexistingfile") #doctest:+ELLIPSIS +NORMALIZE_WHITESPACE
    Traceback (most recent call last):
    ...
    OperatorError: Madis SQLError:
    Operator PIPE: Command 'wc nonexistingfile' failed to execute because:
    wc: nonexistingfile: No such file or directory
"""

import setpath
import functions
from vtiterable import SourceVT

import subprocess

registered=True

class PipeCursor:
    def __init__(self,command,lines):
        child=subprocess.Popen(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        output, error = child.communicate()
        if child.returncode!=0:
            raise functions.OperatorError(__name__.rsplit('.')[-1],"Command '%s' failed to execute because:\n%s" %(command,error.rstrip('\n\t ')))
        output=unicode(output,'utf-8')
        if not lines:
            self.it=iter([[output]])
        else:
            self.it=iter([[i] for i in output.split("\n")])
    def __iter__(self):
        return self
    def next(self):
        return self.it.next()
    def close(self):
        pass

class PipeVT:
    def __init__(self,envdict,largs,dictargs): #DO NOT DO ANYTHING HEAVY
        self.largs=largs
        self.envdict=envdict
        self.dictargs=dictargs
        self.names=['C1']
        self.linesplit=True
        if 'query' not in dictargs:
            raise functions.OperatorError(__name__.rsplit('.')[-1]," needs command argument ")
        self.query=dictargs['query']
        del dictargs['query']
        if 'lines' in dictargs and not dictargs['lines']:
            self.linesplit=False
    def getdescription(self):
        if not self.names:
            raise functions.OperatorError(__name__.rsplit('.')[-1],"VTable getdescription called before initiliazation")
        return [(i,) for i in self.names]
    def open(self):
        return PipeCursor(self.query,self.linesplit)
    def destroy(self):
        pass

boolargs=['lines']

def Source():
    return SourceVT(PipeVT,boolargs=boolargs,staticschema=True)

if not ('.' in __name__):
    """
    This is needed to be able to test the function, put it at the end of every
    new function you create
    """
    import sys
    import setpath
    from functions import *
    testfunction()
    if __name__ == "__main__":
        reload(sys)
        sys.setdefaultencoding('utf-8')
        import doctest
        doctest.testmod()


import configparser
import collections

import re
import env
from file_handler.struct_ini import StructINIConfig

#from plc DataType to opcua DataType
#datatypes identifiers
#https://python-opcua.readthedocs.io/en/latest/opcua.ua.html#opcua.ua.object_ids.ObjectIds.Float
plc2ua = {
    'int'  : 'Int16'   , #datatype=4
    'word' : 'Int16'   , #datatype=4
    'uint' : 'UInt16'  , #datatype=5
    'dint' : 'Int32'   , #datatype=6
    'udint': 'UInt32'  , #datatype=7
    'usint': 'UInt32'  , #datatype=7
    'real' : 'Float'   , #datatype=10
    'bool' : 'Boolean' , #datatype=1
    'dtl'  : 'DateTime', #datatype=13
    'dword': 'Int32'   , #datatype=6
    'lreal': 'Double'  , #datatype=11
}

namespace_info = {
   #index : uri/name
    'PNR OPC UA Server'   : '2'
}

def convert_type_plc_to_opcua(config):
    for key, value in config.items():
        ua_type = ''
        value = value.lower()

        ua_type = plc2ua[ value ]

        config[ key ] = ua_type

class HandlerININodes():

    def __init__(self, config_path, log_info):
        self.log_info    = log_info
        self.config_path = config_path
        self.logger      = log_info.init_class_logger( self.__class__.__name__ )
        self.sections    = collections.OrderedDict()

        fh = configparser.ConfigParser()
        fh.optionxform = str #set 'key' (node id's string identifier ) case sensitive
        fh.read( config_path )

        for section_name in fh:
            if section_name == 'DEFAULT':
                continue
            ini_nodes = StructINIConfig( self.config_path, self.log_info )
            for key, value in fh[section_name].items():
                ini_nodes.set_field(key, value)
            self.sections[ section_name ] = ini_nodes

    def init_section(self, section_name, config, namespace_uri, namespace_id, db_format):
        if isinstance( config, collections.OrderedDict ):

            ini_nodes = StructINIConfig( self.config_path, self.log_info )
            self.sections[ section_name ] = ini_nodes

            convert_type_plc_to_opcua( config )
            ini_nodes.set_field('db_format', db_format )

            for key, value in config.items():
                ini_nodes.set_field( key, value )

            ini_nodes.save_to_config_path( section_name )

        else:
            self.logger.warn(f"Incorrect type of config, should be '{collections.OrderedDict}'")

    def get_struct(self, section_name):
        config = self.sections[ section_name ].get_copied_config()
        rv = list()
        for key, value in config.items():
            rv.append([key, value])
        return rv


import openslide
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib
import os
import numpy as np
from .utils import crop_around_mask

def plot_count(
    df,
    feature,
    ax,
    title='',
    size=2,
    *args,
        **kwargs):
    # source : kaggle.com/rohitsingh9990/panda-eda-better-visualization-simple-baseline
    total = float(len(df))
    sns.countplot(
        df[feature],
        order=df[feature].value_counts().index,
        palette='Set2',
        ax=ax,
        *args,
        **kwargs)
    ax.set_title(title)
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
    for p in ax.patches:
        height = p.get_height()
        ax.text(p.get_x()+p.get_width()/2.,
                height + 3,
                '{:1.2f}%'.format(100*height/total),
                ha="center")

def plot_relative_distribution(
    df,
    feature,
    hue,
    ax,
    title='',
    size=2,
    *args,
        **kwargs):
    # source : kaggle.com/rohitsingh9990/panda-eda-better-visualization-simple-baseline
    total = float(len(df))
    sns.countplot(
        x=feature,
        hue=hue,
        data=df,
        palette='Set2',
        *args,
        **kwargs)
    ax.set_title(title)
    ax.set_xticklabels(ax.get_xticklabels(), rotation=45)
    for p in ax.patches:
        height = p.get_height()
        ax.text(p.get_x()+p.get_width()/2.,
                height + 3,
                '{:1.2f}%'.format(100*height/total),
                ha="center")

def makeSimpleEDAplots(df):
    f, ax = plt.subplots(2, 2, figsize=(15, 9))
    ax = ax.ravel()
    plot_count(
        df=df,
        feature='data_provider',
        title='data_provider count and % plot',
        ax=ax[0])
    plot_count(
        df=df,
        feature='isup_grade',
        title='isup_grade count and %age plot',
        ax=ax[1])
    plot_count(
        df=df,
        feature='gleason_score',
        title='gleason_score count and %age plot',
        size=3,
        ax=ax[2])
    plot_relative_distribution(
        df=df,
        feature='gleason_score',
        hue='data_provider',
        title='relative count plot of gleason_score with data_provider',
        size=3,
        ax=ax[3])
    plt.tight_layout()

def visualizeExampleSingeSlide(
    slide_id,
    ax,
    data_provider,
    isup_grade,
    gleason_score,
    DATA_DIR,
    *args,
        **kwargs):
    """
    source: https://www.kaggle.com/rohitsingh9990/panda-eda-better-visualization-simple-baseline
    """
    image = openslide.OpenSlide(os.path.join(
        DATA_DIR,
        f'train_images/{slide_id}.tiff'))
    mask = openslide.OpenSlide(os.path.join(
        DATA_DIR,
        f'train_label_masks/{slide_id}_mask.tiff'))
    image_patch = image.read_region(
        (0, 0),
        image.level_count - 1,
        image.level_dimensions[-1])
    mask_patch = mask.read_region(
        (0, 0),
        mask.level_count - 1,
        mask.level_dimensions[-1])
    ax.imshow(np.asarray(image_patch)[..., :3], *args, **kwargs)
    ax.imshow(np.asarray(mask_patch)[..., 0], alpha=0.25, *args, **kwargs)
    image_id = slide_id
    ax.set_title(f"ID: {image_id}\nSource: {data_provider} ISUP: {isup_grade} Gleason: {gleason_score}")

def visualizeExampleMaskSlide(
    slide_id,
    ax,
    isup_grade,
    data_provider,
    gleason_score,
    DATA_DIR,
    *args,
        **kwargs):
    """
    source: https://www.kaggle.com/rohitsingh9990/panda-eda-better-visualization-simple-baseline
    """
    mask = openslide.OpenSlide(os.path.join(
        DATA_DIR,
        f'train_label_masks/{slide_id}_mask.tiff'))
    cmap = matplotlib.colors.ListedColormap([
        'black',
        'gray',
        'green',
        'yellow',
        'orange',
        'red'])
    mask_patch = mask.read_region(
        (0, 0),
        mask.level_count - 1,
        mask.level_dimensions[-1])
    ax.imshow(
        np.asarray(mask_patch)[..., 0],
        cmap=cmap,
        interpolation='nearest',
        vmin=0,
        vmax=5,
        *args,
        **kwargs)
    image_id = slide_id
    ax.set_title(f"ID: {image_id}\nSource: {data_provider} ISUP: {isup_grade} Gleason: {gleason_score}")

def get_desc_image(df, slide_id):
    dp = df.data_provider[df.image_id == slide_id].values[0]
    isup_g = df.isup_grade[df.image_id == slide_id].values[0]
    gl_s = df.gleason_score[df.image_id == slide_id].values[0]
    return dp, isup_g, gl_s

def cropRandomExample(slide_id, DATA_DIR, cropsize=512):
    f, ax = plt.subplots(1, 3)
    mask = openslide.OpenSlide(os.path.join(
        DATA_DIR,
        f'train_label_masks/{slide_id}_mask.tiff'))
    image = openslide.OpenSlide(os.path.join(
        DATA_DIR,
        f'train_images/{slide_id}.tiff'))
    k = int(image.level_downsamples[-1])
    mask_full = mask.read_region((0, 0), 2, mask.level_dimensions[-1])
    mask_full = np.asarray(mask_full).astype(bool)[..., 0]
    ax[0].imshow(mask_full)
    crop_coords = crop_around_mask(mask_full, 32, 32)
    image_slice = image.read_region(
        (k*crop_coords['x_min'], k*crop_coords['y_min']),
        0,
        (cropsize, cropsize))
    mask_slice = mask.read_region(
        (k*crop_coords['x_min'], k*crop_coords['y_min']),
        0,
        (cropsize, cropsize))
    ax[1].imshow(np.asarray(image_slice)[..., :3])
    ax[1].imshow(np.asarray(mask_slice)[..., 0], alpha=0.5)
    cmap = matplotlib.colors.ListedColormap([
        'black',
        'gray',
        'green',
        'yellow',
        'orange',
        'red'])
    ax[2].imshow(
        np.asarray(mask_slice)[..., 0],
        cmap=cmap,
        interpolation='nearest',
        vmin=0,
        vmax=5)
    plt.tight_layout()