# -*- coding: utf-8 -*-
"""
Created on Sat Nov 27 18:44:28 2021

"""
import time
import os
import random

import pandas as pd
import numpy as np
import gensim.downloader as api
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

import csv

#%% Config
#Read
model_names = ['word2vec-google-news-300', 'glove-twitter-200', 'glove-wiki-gigaword-200', 'glove-wiki-gigaword-50', 'glove-wiki-gigaword-300']

#Model accuracy standards
gold_standard_mean = 0.8557
gold_standard_std  = 0.1318
gold_standard_top  = gold_standard_mean + gold_standard_std
gold_standard_bot  = gold_standard_mean - gold_standard_std

random_baseline = 0.25

#Write
local_directory = os.path.dirname(__file__)
output_directory = os.path.join(local_directory, 'output')

#%% Task 1
def get_model(model_name):
	start = time.perf_counter()
	wv = api.load(model_name)
	end = time.perf_counter()

	print(f"Elapsed time to get {model_name}: {end-start}s.")
	return wv

def get_synonym_test():
	#Read questionnaire file
	file = pd.read_csv("synonyms.csv")
	return file

def details_analysis(synonym_test, keyedVectors, model_name):
	file = synonym_test
	wv = keyedVectors

	answers = file["answer"].values
	questions = file["question"].values

	#extract all choices
	choices_all = [choices_all for _, _, *choices_all in file.values]
	#exclude options that the model doesn't know about.
	choices = [[choice for choice in choices if wv.has_index_for(choice)] for choices in choices_all]
	#is a guess if there are no choices, or the model doesn't know the question-word
	guess_labels = [not (choices and wv.has_index_for(question)) for choices, question in zip(choices, questions)]
	#if the question word exists, pick the most similar choice,
	# otherwise, pick randomly from the valid choices,
	# otherwise, pick randomly from all the choices.
	guess_words = [wv.most_similar_to_given(question, choices) if not guess_label else random.choice(choices or choices_all)
							  for question, choices_all, choices, guess_label in zip(questions, choices_all, choices, guess_labels)]

	#correct label is given when the answer matches, and is not a guess.
	correct_labels = answers == guess_words
	correct_labels[guess_labels] = False

	#Assign appropriate label to model's guess.
	labels = np.full_like(guess_words, "wrong")
	labels[correct_labels] = "correct"
	labels[guess_labels]   = "guess"

	#Collect the details of the synonym test.
	detail = np.array([questions, answers, guess_words, labels]).T

	vocab_size = len(wv.index_to_key)
	correct = np.count_nonzero(correct_labels)
	valid = np.count_nonzero(~np.array(guess_labels))
	accuracy = correct / valid
	#Collect the performance of the model in respect to the synonym test.
	performance = [model_name, vocab_size, correct, valid, accuracy]

	return detail, performance

def output_csv(output_filename, table):
	#Task 1 output details
	filename = output_filename
	filepath = os.path.join(output_directory, filename)
	with open(filepath, 'w', newline='') as output_file:
		writer = csv.writer(output_file)
		writer.writerows(table)

#Adapter to function generateAnalysisBarGraph_.
def generateAnalysisBarGraph(analysis):
	title = "Accuracy of Various Models"

	#adapt analysis into data that's easier to parse, then extract relevant info.
	data = list(zip(*analysis))
	xlabels = data[0]
	y = data[-1]
	y_indexes = list(range(len(y)))

	#call the actual function.
	generateAnalysisBarGraph_(title, xlabels, y, y_indexes)

#Make a combo plot out of the analysis.
def generateAnalysisBarGraph_(title, labels, values, value_indexes):
	#File format as specified in the mini-project document.
	file_format = "pdf"
	file_extension = "." + file_format

	#figure number hard-coded to 1.
	plot_title = f"Figure {1}. {title}."
	plot_size = (8, 8)

	#plot the model data as a bar graph.
	plt.bar(value_indexes, values, tick_label=labels, color="xkcd:battleship grey")
	#adjust the x-axis labels to be more readable.
	plt.gcf().autofmt_xdate()
	#write out the various labels of the graph
	plt.title(plot_title)
	plt.xlabel("Models")
	plt.ylabel("Accuracy of Model")
	#adjust the y-axis to include the 100% accuracy mark.
	plt.gca().set_ylim([None, 1])
	#adjust step size of ticks on y-axis.
	ytick_spacing = 0.05
	plt.gca().yaxis.set_major_locator(ticker.MultipleLocator(ytick_spacing))

	#linestyle
	#https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
	loosely_dashed = (0, (5, 10))

	#plot the constant lines.
	dashedline_color = "xkcd:cerulean"
	plt.axhline(y=random_baseline   , label="Random baseline", color = "xkcd:red")
	plt.axhline(y=gold_standard_mean, label="Gold standard mean", color="xkcd:light royal blue")
	plt.axhline(y=gold_standard_top , label="Gold standard one standard deviation away", color=dashedline_color, linestyle=loosely_dashed)
	plt.axhline(y=gold_standard_bot , color=dashedline_color, linestyle=loosely_dashed)
	#plot the area of uncertainty as a see-through span.
	plt.axhspan(gold_standard_top, gold_standard_bot, label="Gold standard within standard deviation", color="xkcd:robin's egg", alpha=0.3)

	#provide text values for each bar
	for count, value in enumerate(values):
		#value and count used as coordinates for the text.
		plt.text(value_indexes[count], value, f"{value:.2%}", va="top", ha="center", color="aliceblue")

	#add legend in a place that is out of the way.
	plt.gca().legend(loc='lower left', shadow=True)
	#change the size.
	plt.gcf().set_size_inches(plot_size)
	plt.savefig(os.path.join(output_directory, title + file_extension), bbox_inches='tight', format=file_format)
	plt.show()

# %% Main flow
def main():
	analysis = []

	synonym_test = get_synonym_test()
	#Batch Task1 and Task 2 together.
	for model_name in model_names:
		print(f"Currently on {model_name}...")
		wv = get_model(model_name)
		detail, performance = details_analysis(synonym_test, wv, model_name)

		#Step 1, output details
		print(f"Outputting details of {model_name}'s performance...")
		filename = f"{model_name}-details.csv"
		output_csv(filename, detail)
		analysis.append(performance)

	#Batch Step 2, output analysis
	print("Outputting analysis of all models...")
	filename = "analysis.csv"
	output_csv(filename, analysis)

	print("Generating analysis graph...")
	generateAnalysisBarGraph(analysis)
	print("Done")

if __name__ == "__main__":
    begin_time = time.perf_counter()
    main()
    end_time = time.perf_counter()
    print("This script has taken", end_time - begin_time, "seconds to execute.")


import json
from json import JSONDecodeError
from typing import Generator

import pytest

from mati import Client

VERIFICATION_RESP = {
    'expired': False,
    'identity': {'status': 'verified'},
    'steps': [],
    'flow': {
        'id': '5ae1c769ad10273b96fbc2b9',
        'name': 'Default flow'
    },
    'documents': [
        {
            'country': 'MX',
            'region': '',
            'photos': [
                'https://media.getmati.com/media/xxx',
                'https://media.getmati.com/media/yyy',
            ],
            'steps': [
                {'error': None, 'status': 200, 'id': 'template-matching'},
                {
                    'error': None,
                    'status': 200,
                    'id': 'mexican-curp-validation',
                    'data': {
                        'curp': 'CURP',
                        'fullName': 'LAST FIRST',
                        'birthDate': '01/01/1980',
                        'gender': 'HOMBRE',
                        'nationality': 'MEXICO',
                        'surname': 'LAST',
                        'secondSurname': '',
                        'name': 'FIRST',
                    },
                },
                {
                    'error': None,
                    'status': 200,
                    'id': 'document-reading',
                    'data': {
                        'fullName': {
                            'value': 'FIRST LAST',
                            'label': 'Name',
                            'sensitive': True,
                        },
                        'documentNumber': {
                            'value': '111',
                            'label': 'Document Number',
                        },
                        'dateOfBirth': {
                            'value': '1980-01-01',
                            'label': 'Day of Birth',
                            'format': 'date',
                        },
                        'expirationDate': {
                            'value': '2030-12-31',
                            'label': 'Date of Expiration',
                            'format': 'date',
                        },
                        'curp': {'value': 'CURP', 'label': 'CURP'},
                        'address': {
                            'value': 'Varsovia 36, 06600 CDMX',
                            'label': 'Address',
                        },
                        'emissionDate': {
                            'value': '2010-01-01',
                            'label': 'Emission Date',
                            'format': 'date',
                        },
                    },
                },
                {'error': None, 'status': 200, 'id': 'alteration-detection'},
                {'error': None, 'status': 200, 'id': 'watchlists'},
            ],
            'type': 'national-id',
            'fields': {
                'fullName': {
                    'value': 'FIRST LAST',
                    'label': 'Name',
                    'sensitive': True,
                },
                'documentNumber': {'value': '111', 'label': 'Document Number'},
                'dateOfBirth': {
                    'value': '1980-01-01',
                    'label': 'Day of Birth',
                    'format': 'date',
                },
                'expirationDate': {
                    'value': '2030-12-31',
                    'label': 'Date of Expiration',
                    'format': 'date',
                },
                'curp': {'value': 'CURP', 'label': 'CURP'},
                'address': {
                    'value': 'Varsovia 36, 06600 CDMX',
                    'label': 'Address',
                },
                'emissionDate': {
                    'value': '2010-01-01',
                    'label': 'Emission Date',
                    'format': 'date',
                },
            },
        }
    ],
    'hasProblem': False,
    'computed': {'age': {'data': 100}},
    'id': '5d9fb1f5bfbfac001a349bfb',
    'metadata': {'name': 'First Last', 'dob': '1980-01-01'},
}

def scrub_sensitive_info(response: dict) -> dict:
    response = scrub_access_token(response)
    response = swap_verification_body(response)
    return response

def scrub_access_token(response: dict) -> dict:
    try:
        resp = json.loads(response['body']['string'])
    except (JSONDecodeError, KeyError):
        pass
    else:
        if 'access_token' in resp:
            resp['access_token'] = 'ACCESS_TOKEN'
            try:
                user = resp['payload']['user']
            except KeyError:
                pass
            else:
                user['_id'] = 'ID'
                user['firstName'] = 'FIRST_NAME'
                user['lastName'] = 'LAST_NAME'
                resp['payload']['user'] = user
            response['body']['string'] = json.dumps(resp).encode('utf-8')
    return response

def swap_verification_body(response: dict) -> dict:
    if b'curp' not in response['body']['string']:
        return response
    response['body']['string'] = json.dumps(VERIFICATION_RESP).encode('utf-8')
    return response

@pytest.fixture(scope='module')
def vcr_config() -> dict:
    config = dict()
    config['filter_headers'] = [('Authorization', None)]
    config['before_record_response'] = scrub_sensitive_info  # type: ignore
    return config

@pytest.fixture
def client() -> Generator:
    yield Client('api_key', 'secret_key')

@pytest.fixture
def identity(client: Client) -> Generator:
    yield client.identities.create(
        client=client,
        nombres='Georg Wilhelm',
        primer_apellido='Friedrich',
        segundo_apellido='Hegel',
        dob='1770-08-27',
    )


import requests
from app import conf

ID_KEY = conf.getSetting('VK', 'id_key')
SECURE_KEY = conf.getSetting('VK', 'secure_key')
SERVICE_KEY = conf.getSetting('VK', 'service_key')
VERSION = conf.getSetting('VK', 'version')

def refactDict(func):
    # Декоратор для измения списка словарей друзей
    def wrapper(accesToken):
        friends = func(accesToken)
        for friend in friends:
            if 'sex' in friend:
                if friend['sex'] == 0:
                    friend['sex'] = 'не указан'
                elif friend['sex'] == 1:
                    friend['sex'] = 'женский'
                elif friend['sex'] == 2:
                    friend['sex'] = 'мужской'
            if 'online' in friend:
                if friend['online'] == 0:
                    friend['online'] = 'оффлайн'
                elif friend['online'] == 1:
                    friend['online'] = 'онлайн'
            if 'country' not in friend:
                friend['country'] = {'title': 'не указана'}
            if 'city' not in friend:
                friend['city'] = {'title': 'не указан'}
        return friends

    return wrapper

@refactDict
def getFriendsByToken(access_token):
    # Получение друзей пользователя с использованием токена
    friends = []
    fields = ['country', 'city', 'sex', 'photo_200_orig', ]
    responce = requests.get('https://api.vk.com/method/friends.get',
                            params={'access_token': access_token, 'order': 'random', "v": VERSION,
                                    'fields': ', '.join(fields), 'count': 5})
    if 'error' not in responce:
        friends = responce.json()['response']['items']
    return friends

@refactDict
def getFriendsById(idUser):
    # Получение списка друзей по его vk ID
    friends = []
    fields = ['country', 'city', 'sex', 'photo_200_orig', ]
    responce = requests.get('https://api.vk.com/method/friends.get',
                            params={'access_token': SERVICE_KEY, 'user_id': idUser, 'order': 'random', "v": VERSION,
                                    'count': 5})
    responce = responce.json()
    if 'error' not in responce:
        idFriends = responce['response']['items']
        friends = list(map(getUserDataById, idFriends))
    print(friends)
    return friends

def getUserDataByToken(access_token):
    # Получение имени и фамилии пользователя по токену
    responce = requests.get('https://api.vk.com/method/users.get',
                            params={'access_token': access_token, "v": VERSION, 'name_case': 'gen'})
    responce = responce.json()
    userName = responce['response'][0]
    return userName

def getUserDataById(idUser):
    # Получение имени и фамилии пользователя по vk id
    fields = ['country', 'city', 'sex', 'photo_200_orig', 'online']
    responce = requests.get('https://api.vk.com/method/users.get',
                            params={'user_id': idUser, 'access_token': SERVICE_KEY, "v": VERSION, 'name_case': 'gen',
                                    'fields': ', '.join(fields)})
    responce = responce.json()
    userName = responce['response'][0]
    return userName

def getAccessKey(code):
    responce = requests.get('https://oauth.vk.com/access_token',
                            params={'client_id': ID_KEY, 'client_secret': SECURE_KEY,
                                    'redirect_uri': 'https://flaskvkapitest.herokuapp.com', 'code': code})
    if responce.status_code == 200:
        data = responce.json()
        try:
            access_token = data['access_token']
        except KeyError:
            access_token = None
    return access_token


# %%
import cartpole
import gymnasium as gym
import numpy as np
from PID_cartpole import PD
import matplotlib.pyplot as plt

#This function is 1 around zero and for high x, 0 at small x
#basically two dips around x=1 and -1
def small_err_func(x):
    return (x**4 - 2*(x**2) + 1) / ((x**4) + 1)

class PIDEnvTrainer(gym.Wrapper):
    def __init__(self, env):
        super().__init__(env)
        self.controller_theta = PD(5, 100, 0)
        self.controller_x = PD(.75, 75, 0, 0.5)
        self.goal = 0
        self.steps = 0
        self.sum_errors = 0
        self.action_space = gym.spaces.Box(
            low=-1, high=1, shape=(1,), dtype=np.float32)
        high = np.array(
            [
                self.x_threshold * 2,
                np.finfo(np.float32).max,
                self.theta_threshold_radians * 2,
                np.finfo(np.float32).max,
                2.,
            ],
            dtype=np.float32,
        )
        self.observation_space = gym.spaces.Box(-high, high, dtype=np.float32)

    def reset(self):
        self.steps = 0
        self.sum_errors = 0
        state, info = self.env.reset()
        state = np.append(state, 0)
        return state, info

    #action represents a sensor modification
    def step(self, action):
        #provide input to the PID control layer
        if self.steps%100 == 0:
            self.goal = np.random.randint(-2,3)
            self.controller_x.goal = self.goal

        err = action.item()
        self.steps +=1
        self.sum_errors += err

        x, x_dot, theta, theta_dot = self.state
        theta_action = self.controller_theta.observe(theta-err)
        x_action = self.controller_x.observe(x)
        act = 1 if theta_action + x_action < 0 else 0
        state, reward, terminated, truncated, _ = self.env.step(act)
        speed = state[1]
        position = state[0]
        state = np.append(state, self.goal)
        position_err = (self.goal - position)

        #reward = 10-5*small_err_func(position_err*5)-10*abs(err)
        reward = 10-5*(err**2)-5*(abs(self.sum_errors)/self.steps)

        return state, reward, terminated, truncated, _


# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import dask.dataframe as dd
import seaborn as sns
import matplotlib.pyplot as plt
from __future__ import absolute_import, division, print_function

import tensorflow as tf
from tensorflow import keras
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
from sklearn.metrics import accuracy_score,confusion_matrix,classification_report
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LinearRegression
from sklearn import svm
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from sklearn.neural_network import MLPClassifier
from xgboost import XGBClassifier

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory

import os
print(os.listdir("../input"))

# Any results you write to the current directory are saved as output.
#path of the file
file = '../input/train.csv'
file_train='../input/test.csv'
# Set columns to most suitable type to optimize for memory usage
traintypes = {'fare_amount': 'float32',
              'pickup_datetime': 'str',
              'pickup_longitude': 'float32',
              'pickup_latitude': 'float32',
              'dropoff_longitude': 'float32',
              'dropoff_latitude': 'float32',
              'passenger_count': 'uint8'}

testtypes = { 'pickup_datetime': 'str',
              'pickup_longitude': 'float32',
              'pickup_latitude': 'float32',
              'dropoff_longitude': 'float32',
              'dropoff_latitude': 'float32',
              'passenger_count': 'uint8'}

cols = list(traintypes.keys())
cols_train=list(testtypes.keys())
df_train = pd.read_csv(file,usecols=cols,dtype=traintypes,nrows = 500)
df_test=pd.read_csv(file_train,usecols=cols_train,dtype=testtypes,nrows=500)
display(df_train.describe())
display(df_test.describe())
df_test.head()
def distance_between(df):
    lat1=df['pickup_latitude']
    lat2=df['dropoff_latitude']
    lon1=df['pickup_longitude']
    lon2=df['dropoff_longitude']
    dist = np.degrees(np.arccos(np.minimum(1,np.sin(np.radians(lat1)) * np.sin(np.radians(lat2)) + np.cos(np.radians(lat1)) * np.cos(np.radians(lat2)) * np.cos(np.radians(lon2 - lon1))))) * 60 * 1.515 * 1.609344
    return dist
def split_date_time(df):
    return df['pickup_datetime'].dt.year,df['pickup_datetime'].dt.month,df['pickup_datetime'].dt.day,df['pickup_datetime'].dt.dayofweek,df['pickup_datetime'].dt.hour

df_train[['date','time','time-zone']] =df_train['pickup_datetime'].str.split(' ', expand=True)
df_train[['year','month','date']] =df_train['date'].str.split('-',expand=True)
df_test[['date','time','time-zone']] =df_test['pickup_datetime'].str.split(' ', expand=True)
df_test[['year','month','date']] =df_test['date'].str.split('-',expand=True)
df_test[['HH','MM','SS']]=df_test['time'].str.split(':',expand=True)
df_train[['HH','MM','SS']]=df_test['time'].str.split(':',expand=True)
df_train['total_distance']=df_train.apply(distance_between,axis=1)
df_test['total_distance']=df_test.apply(distance_between,axis=1)
df_train.shape
df_train= df_train.drop(df_train[(df_train['total_distance']==0)].index, axis = 0)
df_train.head()
df_train.head()
def plot_history(history):
  plt.figure()
  plt.xlabel('Epoch')
  plt.ylabel('Mean Abs Error [1000$]')
  plt.plot(history.epoch, np.array(history.history['mean_absolute_error']),
           label='Train Loss')
  plt.plot(history.epoch, np.array(history.history['val_mean_absolute_error']),
           label = 'Val loss')
  plt.legend()
  plt.ylim([0, 5])
#ploting the fareamount again the number of passengers
sns.boxplot(x='passenger_count',y='fare_amount', data= df_train)
sns.regplot(x='total_distance',y='fare_amount',fit_reg=False, ci=None, truncate=True,data=df_train)
sns.boxplot(x=df_train['passenger_count'])
sns.swarmplot(x=df_train['fare_amount'])
df_train_label=df_train['fare_amount']
df_train_data=df_train.drop(['fare_amount','pickup_datetime','time-zone','time','MM','SS'],axis=1)
df_test_data=df_test.drop(['pickup_datetime','time-zone','time','MM','SS'],axis=1)
print("{}\n{}".format(df_train_data.shape,df_test_data.shape))
df_train_data.head()
epochs=30
def build_model():
  model = keras.Sequential([
    keras.layers.Dense(64, activation=tf.nn.relu,
                       input_shape=(df_train_data.shape[1],)),
    keras.layers.Dense(64, activation=tf.nn.relu),
    keras.layers.Dense(1)
  ])

  optimizer = tf.train.RMSPropOptimizer(0.001)

  model.compile(loss='mse',
                optimizer=optimizer,
                metrics=['mae'])
  return model

model = build_model()
model.summary()
#create model and train the model
trained_model=model.fit(df_train_data,df_train_label,epochs=epochs,validation_split=0.2)
test_predictions=model.predict(df_test_data)
print("actual: "+str(df_train_label[0:5].values))
print("pred:   "+str(test_predictions[24:35]))
clf=LinearRegression()
clf.fit(df_train_data,df_train_label)
predicted_values=clf.predict(df_test_data)
print("actual: "+str(df_train_label[0:5].values))
print("pred:   "+str(predicted_values[24:35]))


import os
import talib
import numpy as np
import pandas as pd
import fx_trading.utils.constants as cst
from fx_trading.b_fx_stats.format_stats import BuildStrategyReport
from fx_trading.utils.data_interact import read_data, save_data
from fx_trading.utils.parallel_tasks import AsyncMP

CANDLE_NAMES = talib.get_function_groups()['Pattern Recognition']
CANDLE_NAMES = ['CDLENGULFING']

def add_candlestick_pattern(df):
    """
    Description:
    ------------

    Add Candle stick pattern to the price.
    """
    op = df[cst.OPEN]
    hi = df[cst.HIGH]
    lo = df[cst.LOW]
    cl = df[cst.CLOSE]

    for candle in CANDLE_NAMES:
        df[candle] = getattr(talib, candle)(op, hi, lo, cl)

    return df

def fast_prepare_data(df, fx_pair, forecast_period):

    df.reset_index(inplace=True)
    df[CANDLE_NAMES] = df[CANDLE_NAMES].shift(1)

    _df = df[[cst.LOW, cst.HIGH, cst.OPEN]].copy()
    header = ['FORECAST_PERIOD_LOW', 'FORECAST_PERIOD_HIGH', 'BEAR_STOP', 'BULL_STOP', 'BEAR_TP', 'BULL_TP',
              'FORECAST_PERIOD_ENTRY_BEAR', 'FORECAST_PERIOD_ENTRY_BULL']
    _df.loc[:, header] = np.NaN
    x = _df.values

    for pos in range(0, len(x) - forecast_period):
        subset = x[pos: pos + forecast_period]

        forecast_period_low = np.nanargmin(subset[:, 0])
        forecast_period_high = np.nanargmax(subset[:, 1])

        bear_tp = (subset[0, 2] - subset[forecast_period_low, 0]) * cst.FX_PIP[fx_pair]
        bull_tp = (subset[forecast_period_high, 1] - subset[0, 2]) * cst.FX_PIP[fx_pair]

        bear_stop = (np.nanmax(subset[:forecast_period_low + 1, 1]) - subset[0, 2]) * cst.FX_PIP[fx_pair]
        bull_stop = (subset[0, 2] - np.nanmin(subset[:forecast_period_high + 1, 0])) * cst.FX_PIP[fx_pair]

        bear_entry_period = np.nanargmax(subset[:forecast_period_low + 1, 1])
        bull_entry_period = np.nanargmin(subset[:forecast_period_high + 1, 0])

        x[pos, -8:] = [forecast_period_low + 1, forecast_period_high + 1, bear_stop, bull_stop, bear_tp, bull_tp,
                       bear_entry_period + 1, bull_entry_period + 1]

    df.loc[:, header] = x[:, -8:]
    df.set_index([cst.FX_PAIR, cst.DATE], inplace=True)

    return df.dropna(subset=['BULL_TP'])

def prepare_data_for_stats(df, fx_pair, forecast_period):
    """
    Description:
    ------------
    Prepare the data set to compute the stats on accuracy.
    """
    df.reset_index(inplace=True)
    df[CANDLE_NAMES] = df[CANDLE_NAMES].shift(1)

    df['FORECAST_PERIOD_LOW'] = df[cst.LOW].rolling(forecast_period).apply(
        lambda x: x.idxmin()).shift(-forecast_period + 1)
    df['FORECAST_PERIOD_HIGH'] = df[cst.HIGH].rolling(forecast_period).apply(
        lambda x: x.idxmax()).shift(-forecast_period + 1)

    df['BEAR_STOP'] = np.NaN
    df['BULL_STOP'] = np.NaN

    h = [cst.LOW, cst.HIGH, 'FORECAST_PERIOD_HIGH', 'FORECAST_PERIOD_LOW', 'BEAR_STOP', 'BULL_STOP']

    for i, row in df[h].iterrows():

        if ~np.isnan(row['FORECAST_PERIOD_HIGH']):
            df.loc[i, 'BULL_STOP'] = df[h].iloc[i:int(row['FORECAST_PERIOD_HIGH']) + 1, 0].min()
        if ~np.isnan(row['FORECAST_PERIOD_LOW']):
            df.loc[i, 'BEAR_STOP'] = df[h].iloc[i:int(row['FORECAST_PERIOD_HIGH']) + 1, 1].max()

    df['BEAR_TP'] = df[cst.LOW].rolling(forecast_period).min().shift(-forecast_period + 1)
    df['BEAR_TP'] = (df[cst.OPEN] - df['BEAR_TP']) * cst.FX_PIP[fx_pair]
    df['BEAR_STOP'] = (df['BEAR_STOP'] - df[cst.OPEN]) * cst.FX_PIP[fx_pair]

    df['BULL_TP'] = df[cst.HIGH].rolling(forecast_period).max().shift(-forecast_period + 1)
    df['BULL_TP'] = (df['BULL_TP'] - df[cst.OPEN]) * cst.FX_PIP[fx_pair]
    df['BULL_STOP'] = (df[cst.OPEN] - df['BULL_STOP']) * cst.FX_PIP[fx_pair]

    df.set_index([cst.FX_PAIR, cst.DATE], inplace=True)

    return df.dropna(subset=['BULL_TP'])

def build_max_gain_stats(df, pip_target):
    """
    Description:
    ------------
    Compute the max potential gain as well as the RR ratio for an entry at the
    closing price.
    """

    df = df.copy()
    stats = {}
    df['YEAR'] = df[cst.DATE].dt.strftime('%Y').astype(str)
    group_by = [cst.FX_PAIR, 'Candle_type', 'YEAR']
    group_by_total = [cst.FX_PAIR, 'Candle_type']
    index = [cst.FX_PAIR, 'Candle_type', 'YEAR']
    percentiles = [0.5]

    dist = df.groupby(group_by)['TP'].describe(
        percentiles=percentiles
    ).reset_index()

    tot = df.groupby(group_by_total)['TP'].describe(
        percentiles=percentiles
    ).reset_index()
    tot['YEAR'] = 'Total'

    dist = pd.concat([dist, tot]).set_index(index)
    stats['Distribution'] = dist[['count', 'mean', '50%', 'std']].rename(
        columns={'count': 'N. Obs', 'mean': 'Avg.', '50%': 'Med', 'std': 'Std'})
    stats = pd.concat(stats, axis=1)

    accuracy = {}
    for i in pip_target:
        _df = df[df['TP'] >= i]

        tot = _df.groupby(group_by_total)[['TP', 'STOP']].agg({'TP': 'count', 'STOP': 'mean'})
        tot.rename(columns={'TP': 'Accuracy Target', 'STOP': 'Stop Loss'},
                   inplace=True)
        tot.reset_index(inplace=True)
        tot['YEAR'] = 'Total'

        _df = _df.groupby(group_by)[['TP', 'STOP']].agg(
            {'TP': 'count', 'STOP': 'mean'}).reset_index()
        _df.rename(columns={'TP': 'Accuracy Target', 'STOP': 'Stop Loss'},
                   inplace=True)
        accuracy[str(i)] = pd.concat([_df, tot]).set_index(index)

    tp = {}
    for i in pip_target:
        rr = []
        for j in [1, 2, 3]:
            _df = df[(df['TP'] >= i) & (df['STOP'] < i * j)]
            tot = _df.groupby(group_by_total)['TP'].count().to_frame('RR > {}'.format(round(1/j, 1))).reset_index()
            tot['YEAR'] = 'Total'

            _df = _df.groupby(group_by)[['TP']].count().reset_index()
            _df.rename(columns={'TP': 'RR > {}'.format(round(1/j, 1))}, inplace=True)

            rr.append(pd.concat([_df, tot]).set_index(index))
        tp[str(i)] = pd.concat(rr, axis=1)
    accuracy = pd.concat(accuracy, axis=1)
    tp = pd.concat(tp, axis=1)

    stats = pd.concat([stats, accuracy.swaplevel(axis=1), tp.swaplevel(axis=1)], axis=1)
    stats = stats[stats[('Distribution', 'N. Obs')] != 0]
    stats['Accuracy Target'] = (stats['Accuracy Target'].div(stats[('Distribution', 'N. Obs')], axis=0) * 100).fillna(0)
    stats['RR > 1.0'] = (stats['RR > 1.0'].div(stats[('Distribution', 'N. Obs')], axis=0) * 100).fillna(0).astype(int)
    stats['RR > 0.5'] = (stats['RR > 0.5'].div(stats[('Distribution', 'N. Obs')], axis=0) * 100).fillna(0).astype(int)
    stats['RR > 0.3'] = (stats['RR > 0.3'].div(stats[('Distribution', 'N. Obs')], axis=0) * 100).fillna(0).astype(int)

    stats['Accuracy Target'] = stats['Accuracy Target'].astype(int)
    stats['Distribution'] = stats['Distribution'].fillna(0).astype(int)
    stats['Stop Loss'] = stats['Stop Loss'].fillna(0).astype(int)
    h = ['Distribution', 'Accuracy Target', 'Stop Loss', 'RR > 1.0', 'RR > 0.5', 'RR > 0.3']

    stats = stats.loc[:, (h, slice(None))].round(0)

    return stats

def run_max_gain_stats(df, pip_target):
    """
    Description:
    ------------
    Compute the accuracy of the signals at the entry price based on the candle pattern.

    """

    header = ['TP', 'STOP', 'PERIOD_TP']
    stats = {}

    for candle in CANDLE_NAMES:

        df['Candle_type'] = np.NaN
        df.loc[df[candle].fillna(-1) > 0, 'Candle_type'] = cst.BULLISH
        df.loc[df[candle].fillna(-1) > 0, 'TP'] = df['BULL_TP']
        df.loc[df[candle].fillna(-1) > 0, 'STOP'] = df['BULL_STOP']
        df.loc[df[candle].fillna(-1) > 0, 'PERIOD_TP'] = df['FORECAST_PERIOD_HIGH']

        df.loc[df[candle].fillna(1) < 0, 'Candle_type'] = cst.BEARISH
        df.loc[df[candle].fillna(1) < 0, 'TP'] = df['BEAR_TP']
        df.loc[df[candle].fillna(1) < 0, 'STOP'] = df['BEAR_STOP']
        df.loc[df[candle].fillna(1) < 0, 'PERIOD_TP'] = df['FORECAST_PERIOD_LOW']

        _df = df.copy()
        _df.dropna(subset=['Candle_type'], inplace=True)
        _df.set_index('Candle_type', inplace=True, append=True)

        if len(_df) != 0:
            st = build_max_gain_stats(_df[header].reset_index(), pip_target)
            stats[('Candlestick_MaxG', candle)] = st

    stats = pd.concat(stats)
    stats.index.names = ['Stats', 'Candle_name', cst.FX_PAIR, 'Candle_type', cst.DATE]

    return stats.reset_index()

def get_optimal_entry_stats(df, pip_target):

    stats = {}
    df['YEAR'] = df[cst.DATE].dt.strftime('%Y').astype(str)
    group_by = [cst.FX_PAIR, 'Candle_type', 'YEAR']
    group_by_total = [cst.FX_PAIR, 'Candle_type']
    index = [cst.FX_PAIR, 'Candle_type', 'YEAR']

    for e in [10]:

        df['TARGET'] = df['TP'] + e
        df['NEW_STOP'] = df['STOP'] - e
        df.loc[df['NEW_STOP'] < 0, 'TARGET'] = np.NaN
        df.loc[df['NEW_STOP'] < 0, 'NEW_STOP'] = np.NaN

        accuracy = {}
        count = df.groupby(group_by)[['TARGET']].count().reset_index()
        tot = df.groupby(group_by_total)[['TARGET']].count().reset_index()
        tot['YEAR'] = 'Total'

        accuracy['N. Obs'] = pd.concat([count, tot]).set_index(index)['TARGET']

        count = df.groupby(group_by)[['PERIOD_TP']].mean().reset_index()
        tot = df.groupby(group_by_total)[['PERIOD_TP']].mean().reset_index()
        tot['YEAR'] = 'Total'
        accuracy['Avg. Per'] = pd.concat([count, tot]).set_index(index)['PERIOD_TP']

        for i in pip_target:
            _df = df[(df['TARGET'] >= i) & (df['NEW_STOP'] < 20)]
            tot = _df.groupby(group_by_total)[['TARGET', 'NEW_STOP']].agg(
                {'TARGET': 'count', 'NEW_STOP': 'mean'}).reset_index()
            tot['YEAR'] = 'Total'
            tot.rename(columns={'TARGET': 'Accuracy Target', 'NEW_STOP': 'Stop Loss'},
                       inplace=True)

            _df = _df.groupby(group_by)[['TARGET', 'NEW_STOP']].agg(
                {'TARGET': 'count', 'NEW_STOP': 'mean'}).reset_index()

            _df.rename(columns={'TARGET': 'Accuracy Target', 'NEW_STOP': 'Stop Loss'},
                       inplace=True)
            accuracy[str(i)] = pd.concat([_df, tot]).set_index(index)['Accuracy Target']

        accuracy = pd.concat(accuracy, axis=1)

        accuracy = accuracy[accuracy['N. Obs'] != 0]
        accuracy[list(map(str, pip_target))] = (100 * accuracy[list(map(str, pip_target))].div(
            accuracy['N. Obs'], axis=0)).round(1)
        stats[f'Open - {e}'] = accuracy

    return pd.concat(stats, axis=1).round(0)

def run_potential_entry(df, pip_target):

    header = ['TP', 'STOP', 'PERIOD_TP', 'PERIOD_ENTRY']
    stats = {}
    for candle in CANDLE_NAMES:

        df['Candle_type'] = np.NaN
        df.loc[df[candle].fillna(-1) > 0, 'Candle_type'] = cst.BULLISH
        df.loc[df[candle].fillna(-1) > 0, 'TP'] = df['BULL_TP']
        df.loc[df[candle].fillna(-1) > 0, 'STOP'] = df['BULL_STOP']
        df.loc[df[candle].fillna(-1) > 0, 'PERIOD_TP'] = df['FORECAST_PERIOD_HIGH']
        df.loc[df[candle].fillna(-1) > 0, 'PERIOD_ENTRY'] = df['FORECAST_PERIOD_ENTRY_BULL']

        df.loc[df[candle].fillna(1) < 0, 'Candle_type'] = cst.BEARISH
        df.loc[df[candle].fillna(1) < 0, 'TP'] = df['BEAR_TP']
        df.loc[df[candle].fillna(1) < 0, 'STOP'] = df['BEAR_STOP']
        df.loc[df[candle].fillna(1) < 0, 'PERIOD_TP'] = df['FORECAST_PERIOD_LOW']
        df.loc[df[candle].fillna(1) < 0, 'PERIOD_ENTRY'] = df['FORECAST_PERIOD_ENTRY_BEAR']

        _df = df.copy()
        _df.dropna(subset=['Candle_type'], inplace=True)
        _df.set_index('Candle_type', inplace=True, append=True)

        if len(_df) != 0:
            st = get_optimal_entry_stats(_df[header].reset_index(), pip_target)
            stats[('Candlestick_Entry', candle)] = st

    stats = pd.concat(stats)
    stats.index.names = ['Stats', 'Candle_name', cst.FX_PAIR, 'Candle_type', cst.DATE]

    return stats.reset_index()

def bulk_create_sav_dir(fx_pairs):

    for i in fx_pairs:
        path = cst.FX_STATS_CANDLESTICK.format(cst.ASSET[i], i)
        if not os.path.exists(path):
            os.makedirs(path)

def build_candlestick_pattern_analysis(fx_pair, date_range, path=cst.FX_15MIN_DATA_PATH,
                                       forecasting_period=16):
    """
    Description:
    ------------
    Compute some simple stats on the predictive power of the candlestick

    """
    fx_quote = read_data(path, fx_pair, date_range)
    fx_quote[cst.FX_PAIR] = fx_quote[cst.FX_PAIR].astype(str)
    fx_quote = fx_quote.set_index(cst.FX_PAIR, append=True).swaplevel(axis=0)
    fx_quote.sort_index(inplace=True)
    fx_quote = fx_quote[[cst.OPEN, cst.HIGH, cst.LOW, cst.CLOSE]]
    return fx_quote
    #############################################################################
    # Add candlestick pattern
    #############################################################################
    params = [(df,) for (name, df) in fx_quote.groupby(level=0)]
    fx_quote = pd.concat(AsyncMP().exec(params, add_candlestick_pattern))
    del params

    #############################################################################
    # Prepare data set for the stats
    #############################################################################
    params = [(df, name, forecasting_period) for (name, df) in fx_quote.groupby(level=0)]
    fx_quote = pd.concat(AsyncMP().exec(params, fast_prepare_data))
    del params
    return fx_quote
    #############################################################################
    # Stats for each FX pair
    #############################################################################

    bulk_create_sav_dir(fx_pair)
    per_fx_stats = run_potential_entry(fx_quote, pip_target=[10])

    per_fx_stats.groupby(cst.FX_PAIR).apply(
        lambda x: save_data(
            x,
            path=cst.FX_STATS_CANDLESTICK.format(cst.ASSET[x.name], x.name) + f'potential_entry_plus.parquet',
            partition_cols=None
        )
    )

    per_fx_stats = run_max_gain_stats(fx_quote, pip_target=[10])

    per_fx_stats.groupby(cst.FX_PAIR).apply(
        lambda x: save_data(
            x,
            path=cst.FX_STATS_CANDLESTICK.format(cst.ASSET[x.name], x.name) + f'max_g_plus.parquet',
            partition_cols=None
        )
    )

    return per_fx_stats

def report(fx_pair):
    BuildStrategyReport(fx_pair).run()

if __name__ == '__main__':

    DATE_RANGE = list(range(2022, 2023))
    FX_PAIR = list(cst.FX_PIP.keys())
    FX_PAIR = ['eurgbp']
    for i in range(0, len(FX_PAIR), 7):
        pairs = FX_PAIR[i: i + 7]
        print(pairs)
        df = build_candlestick_pattern_analysis(pairs, DATE_RANGE, path=cst.FX_15MIN_DATA_PATH)

    # bullish, bearish = {}, {}
    #
    # for pair in FX_PAIR:
    #     if cst.ASSET[pair]==cst.FX:
    #         path = cst.FX_STATS_CANDLESTICK.format(cst.ASSET[pair], pair) + f'potential_entry_plus.parquet'
    #         df = pd.read_parquet(path).drop(columns=[('Stats', ), ('FX_PAIR',)])\
    #             .set_index([('Candle_name',), ('Candle_type', ), ('DATE', )])
    #         bullish[pair] = df[('Open - 10', 'N. Obs')].xs('2022', level=-1).xs(cst.BULLISH, level=-1)
    #         bearish[pair] = df[('Open - 10', 'N. Obs')].xs('2022', level=-1).xs(cst.BEARISH, level=-1)
    #
    # path = 'D:/Blackfire_Projects/Blackfire_fx_algo_trading/fx_stats/FOREX/'
    # bullish = pd.concat(bullish, axis=1).sort_index().sort_index(axis=1)
    # # bullish.to_excel(path + 'Candlestick_bull_statsn2.xlsx')
    # bearish = pd.concat(bearish, axis=1).sort_index().sort_index(axis=1)
    # bearish.to_excel(path + 'Candlestick_bear_statsn2.xlsx')
    # # FX_PAIR = ['eurusd']
    # print(CANDLE_NAMES)

    # for fx_pair in cst.FX_PIP:
    #     build_candlestick_pattern_analysis(fx_pair, DATE_RANGE, path=cst.FX_15MIN_DATA_PATH)
    #     report(fx_pair)
    #     print(fx_pair)

    # params = [(fx_pair,) for fx_pair in cst.FX_PIP]
    # fx_quote = pd.concat(AsyncMP().exec(params, report))

    # df[df[('Distribution', 'count')] > 600].xs('Total', level=4).sort_values(('Accuracy Direction', 15))


import flask
import pickle
from flask import current_app, flash, Response, request, url_for,\
    render_template
from flask_babelex import gettext
from flask_security import current_user
from flask_security.views import _security, _ctx
from flask_security.utils import config_value, get_post_logout_redirect, \
    get_post_login_redirect, logout_user

from flask import session

import config
from pgadmin.utils import PgAdminModule
from pgadmin.utils.constants import KERBEROS
from pgadmin.utils.csrf import pgCSRFProtect

from .registry import AuthSourceRegistry

MODULE_NAME = 'authenticate'

class AuthenticateModule(PgAdminModule):
    def get_exposed_url_endpoints(self):
        return ['authenticate.login',
                'authenticate.kerberos_login',
                'authenticate.kerberos_logout']

blueprint = AuthenticateModule(MODULE_NAME, __name__, static_url_path='')

@blueprint.route("/login/kerberos",
                 endpoint="kerberos_login", methods=["GET"])
@pgCSRFProtect.exempt
def kerberos_login():
    logout_user()
    return Response(render_template("browser/kerberos_login.html",
                                    login_url=url_for('security.login'),
                                    ))

@blueprint.route("/logout/kerberos",
                 endpoint="kerberos_logout", methods=["GET"])
@pgCSRFProtect.exempt
def kerberos_logout():
    logout_user()
    return Response(render_template("browser/kerberos_logout.html",
                                    login_url=url_for('security.login'),
                                    ))

@blueprint.route('/login', endpoint='login', methods=['GET', 'POST'])
def login():
    """
    Entry point for all the authentication sources.
    The user input will be validated and authenticated.
    """
    form = _security.login_form()
    auth_obj = AuthSourceManager(form, config.AUTHENTICATION_SOURCES)
    session['_auth_source_manager_obj'] = None

    # Validate the user
    if not auth_obj.validate():
        for field in form.errors:
            for error in form.errors[field]:
                flash(error, 'warning')
            return flask.redirect(get_post_logout_redirect())

    # Authenticate the user
    status, msg = auth_obj.authenticate()
    if status:
        # Login the user
        status, msg = auth_obj.login()
        current_auth_obj = auth_obj.as_dict()
        if not status:
            if current_auth_obj['current_source'] ==\
                    KERBEROS:
                return flask.redirect('{0}?next={1}'.format(url_for(
                    'authenticate.kerberos_login'), url_for('browser.index')))

            flash(gettext(msg), 'danger')
            return flask.redirect(get_post_logout_redirect())

        session['_auth_source_manager_obj'] = current_auth_obj
        return flask.redirect(get_post_login_redirect())

    elif isinstance(msg, Response):
        return msg
    flash(gettext(msg), 'danger')
    response = flask.redirect(get_post_logout_redirect())
    return response

class AuthSourceManager():
    """This class will manage all the authentication sources.
     """
    def __init__(self, form, sources):
        self.form = form
        self.auth_sources = sources
        self.source = None
        self.source_friendly_name = None
        self.current_source = None

    def as_dict(self):
        """
        Returns the dictionary object representing this object.
        """

        res = dict()
        res['source_friendly_name'] = self.source_friendly_name
        res['auth_sources'] = self.auth_sources
        res['current_source'] = self.current_source

        return res

    def set_current_source(self, source):
        self.current_source = source

    @property
    def get_current_source(self, source):
        return self.current_source

    def set_source(self, source):
        self.source = source

    @property
    def get_source(self):
        return self.source

    def set_source_friendly_name(self, name):
        self.source_friendly_name = name

    @property
    def get_source_friendly_name(self):
        return self.source_friendly_name

    def validate(self):
        """Validate through all the sources."""
        for src in self.auth_sources:
            source = get_auth_sources(src)
            if source.validate(self.form):
                return True
        return False

    def authenticate(self):
        """Authenticate through all the sources."""
        status = False
        msg = None
        for src in self.auth_sources:
            source = get_auth_sources(src)
            current_app.logger.debug(
                "Authentication initiated via source: %s" %
                source.get_source_name())

            if self.form.data['email'] and self.form.data['password'] and \
                    source.get_source_name() == KERBEROS:
                continue

            status, msg = source.authenticate(self.form)

            # When server sends Unauthorized header to get the ticket over HTTP
            # OR When kerberos authentication failed while accessing pgadmin,
            # we need to break the loop as no need to authenticate further
            # even if the authentication sources set to multiple
            if not status:
                if (hasattr(msg, 'status') and
                    msg.status == '401 UNAUTHORIZED') or\
                        (source.get_source_name() ==
                         KERBEROS and
                         request.method == 'GET'):
                    break

            if status:
                self.set_source(source)
                self.set_current_source(source.get_source_name())
                if msg is not None and 'username' in msg:
                    self.form._fields['email'].data = msg['username']
                return status, msg
        return status, msg

    def login(self):
        status, msg = self.source.login(self.form)
        if status:
            self.set_source_friendly_name(self.source.get_friendly_name())
            current_app.logger.debug(
                "Authentication and Login successfully done via source : %s" %
                self.source.get_source_name())
        return status, msg

def get_auth_sources(type):
    """Get the authenticated source object from the registry"""

    auth_sources = getattr(current_app, '_pgadmin_auth_sources', None)

    if auth_sources is None or not isinstance(auth_sources, dict):
        auth_sources = dict()

    if type in auth_sources:
        return auth_sources[type]

    auth_source = AuthSourceRegistry.create(type)

    if auth_source is not None:
        auth_sources[type] = auth_source
        setattr(current_app, '_pgadmin_auth_sources', auth_sources)

    return auth_source

def init_app(app):
    auth_sources = dict()

    setattr(app, '_pgadmin_auth_sources', auth_sources)
    AuthSourceRegistry.load_auth_sources()

    return auth_sources


from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import QDir
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QMessageBox, QFileDialog

import tcp_logic, udp_logic, web_logic
import socket
import sys
import binascii

from callscan import MyDialog
from constant import Constant

class MainWindow(tcp_logic.TcpLogic, udp_logic.UdpLogic, web_logic.WebLogic):

    def __init__(self, num):
        super(MainWindow, self).__init__(num)
        self.client_socket_list = list()
        self.another = None
        self.link = False
        # 初始化的时候加载bin文件 存储在这个数组里面
        self.arrs = []
        self.setWindowIcon(QIcon("image/b.png"))
        # 打开软件时默认获取本机ip
        self.get_ip()
        self.setWindowFlags(QtCore.Qt.Window)

    def get_ip(self):
        self.lineEdit_ip_local.clear()
        my_addr = socket.gethostbyname(socket.gethostname())
        self.lineEdit_ip_local.setText(str(my_addr))

    def connect(self, ):
        """
        控件信号-槽的设置
        :param : QDialog类创建的对象
        :return: None
        """
        # 如需传递参数可以修改为connect(lambda: self.click(参数))
        super(MainWindow, self).connect()
        self.pushButton_link.clicked.connect(self.click_link)
        self.pushButton_unlink.clicked.connect(self.click_unlink)
        self.pushButton_get_ip.clicked.connect(self.click_get_ip)
        self.pushButton_clear.clicked.connect(self.click_clear)
        self.pushButton_send.clicked.connect(self.send)
        self.pushButton_dir.clicked.connect(self.click_dir)
        self.pushButton_exit.clicked.connect(self.close)
        self.pushButton_else.clicked.connect(self.another_window)
        self.label_written.clicked.connect(self.load_file)
        self.pushButton_reset_all.clicked.connect(self.show_confirm_message)

    def load_file(self):
        print("加载文件")
        dlg = QFileDialog()
        dlg.setFileMode(QFileDialog.AnyFile)
        dlg.setFilter(QDir.Files)

        if dlg.exec_():
            filenames = dlg.selectedFiles()
            print(filenames[0])
            self.read_bin(filenames[0])

    def click_link(self):
        """
        pushbutton_link控件点击触发的槽
        :return: None
        """
        # 连接时根据用户选择的功能调用函数
        if self.comboBox_tcp.currentIndex() == 0:
            self.tcp_server_start()
        if self.comboBox_tcp.currentIndex() == 1:
            self.tcp_client_start()
        if self.comboBox_tcp.currentIndex() == 2:
            self.udp_server_start()
        if self.comboBox_tcp.currentIndex() == 3:
            self.udp_client_start()
        if self.comboBox_tcp.currentIndex() == 4:
            self.web_server_start()

    def click_unlink(self):
        """
        pushbutton_unlink控件点击触发的槽
        :return: None
        """
        # 关闭连接
        self.close_all()
        self.link = False
        self.pushButton_unlink.setEnabled(False)
        self.pushButton_link.setEnabled(True)

    def click_get_ip(self):
        """
        pushbutton_get_ip控件点击触发的槽
        :return: None
        """
        # 获取本机ip
        # self.lineEdit_ip_local.clear()
        # my_addr = socket.gethostbyname(socket.gethostname())
        # self.lineEdit_ip_local.setText(str(my_addr))
        self.slotInformation()

    def slotInformation(self):
        reply = QMessageBox.question(self, '提示', '确认现在对云台进行更新?', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            if self.combox_port_select.currentText() == "all connections":
                reply_in = QMessageBox.question(self, '提示', '没有选择端口', QMessageBox.Yes | QMessageBox.No,
                                             QMessageBox.No)
                if reply_in ==QMessageBox.Yes:
                    return
                    pass
                else:
                    return
                    pass
            self.tcp_send(init_code=Constant.update)
        else:
            pass
    def select_file(self):
        reply = QMessageBox.question(self, '提示', '请选择bin文件之后进行操作,以免不必要的异常', QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.load_file()
        else:
            pass

    def show_confirm_message(self):
        reply = QMessageBox.question(self, '提示', "是否重置", QMessageBox.Yes | QMessageBox.No, QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.reset_data()
        else:
            pass
    def send(self):
        """
        pushbutton_send控件点击触发的槽
        :return:
        """
        # 连接时根据用户选择的功能调用函数
        if self.comboBox_tcp.currentIndex() == 0 or self.comboBox_tcp.currentIndex() == 1:
            self.tcp_send()
        if self.comboBox_tcp.currentIndex() == 2 or self.comboBox_tcp.currentIndex() == 3:
            self.udp_send()
        if self.comboBox_tcp.currentIndex() == 4:
            self.web_send()

    def click_clear(self):
        """
        pushbutton_clear控件点击触发的槽
        :return: None
        """
        # 清空接收区屏幕
        self.textBrowser_recv.clear()

    def click_dir(self):
        # WEB服务端功能中选择路径
        self.web_get_dir()

    def close_all(self):
        """
        功能函数，关闭网络连接的方法
        :return:
        """
        # 连接时根据用户选择的功能调用函数
        if self.comboBox_tcp.currentIndex() == 0 or self.comboBox_tcp.currentIndex() == 1:
            self.tcp_close()
        if self.comboBox_tcp.currentIndex() == 2 or self.comboBox_tcp.currentIndex() == 3:
            self.udp_close()
        if self.comboBox_tcp.currentIndex() == 4:
            self.web_close()
        self.reset()

    def reset(self):
        """
        功能函数，将按钮重置为初始状态
        :return:None
        """
        self.link = False
        self.client_socket_list = list()
        self.pushButton_unlink.setEnabled(False)
        self.pushButton_link.setEnabled(True)

    def another_window(self):
        """
        开启一个新的窗口的方法
        :return:
        """
        # 弹出一个消息框，提示开启了一个新的窗口
        QtWidgets.QMessageBox.warning(self,
                                      'TCP/UDP云台助手',
                                      "已经禁止串口模式,有需要请与标哥联系",
                                      QtWidgets.QMessageBox.Yes)
        # # 计数，开启了几个窗口
        # self.num = self.num + 1
        # # 开启新的窗口
        # self.another = MainWindow(self.num)
        # self.another.show()
        # 在这里开启串口模式
        # nn = ui_person.show()
        # mm = ui.hide()

        # myshow = Pyqt5_Serial()
        # myshow.show()
        # myshow.exec()

if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ui = MainWindow(1)
    ui.show()
    sys.exit(app.exec_())


"""
CP1404 Practical 7 - More Guitars!
Estimated time: 30 mins
Actual time: 35 mins
"""

from prac_07.guitar import Guitar

def main():
    guitars = []
    in_file = open("guitars.csv", "r")

    for line in in_file:
        parts = line.strip().split(",")
        guitar = Guitar(parts[0], int(parts[1]), parts[2])
        guitars.append(guitar)
    in_file.close()

    name = input("Name: ")
    while name != "":
        year = int(input("Year: "))
        cost = float(input("Cost: $"))
        new_guitar = Guitar(name, year, cost)
        print(new_guitar, "added.")
        guitars.append(new_guitar)
        name = input("Name: ")
    guitars.sort()

    out_file = open("guitars.csv", "w")
    for guitar in guitars:
        print(f"{guitar.name},{guitar.year},{guitar.cost}", file=out_file, end="\n")
    out_file.close()

main()


import json
import subprocess
import pathlib
import pytest
import sys

from openassetio.errors import BatchElementError
from openassetio.hostApi import ManagerFactory

# pylint: disable=no-self-use
# pylint: disable=invalid-name,redefined-outer-name
# pylint: disable=missing-class-docstring,missing-function-docstring

class Test_simpleResolver_errors:
    def test_when_lib_initialization_fails_then_error_written_to_stderr_and_return_code_non_zero(
        self, monkeypatch
    ):
        monkeypatch.delenv("OPENASSETIO_DEFAULT_CONFIG", raising=False)
        result = execute_cli()
        expected_message = [
            "ERROR: No default manager configured, "
            f"check ${ManagerFactory.kDefaultManagerConfigEnvVarName}"
        ]
        assert result.stderr.splitlines() == expected_message
        assert result.returncode == 1

    def test_when_env_set_and_no_args_then_usage_printed_and_return_code_is_one(
        self, test_config_env  # pylint: disable=unused-argument
    ):
        result = execute_cli()
        expected_message = [
            "usage: simpleResolver.py [-h] traitset entityref",
            "simpleResolver.py: error: the following arguments are required: traitset, entityref",
        ]
        assert result.stderr.splitlines() == expected_message
        assert result.returncode == 2

    def test_when_entity_ref_and_trait_set_valid_then_expected_data_output_and_return_code_zero(
        self, test_config_env  # pylint: disable=unused-argument
    ):
        result = execute_cli("animal,named", "bal:///cat")
        data = json.loads(result.stdout)
        expected_data = {
            "animal": {"species": "🐈", "age": 12},
            "named": {"name": "Martin"},
        }
        assert data == expected_data
        assert result.returncode == 0

    def test_when_entity_ref_valid_and_trait_set_invalid_then_data_empty_and_return_code_zero(
        self, test_config_env  # pylint: disable=unused-argument
    ):
        result = execute_cli("someMissingTrait", "bal:///cat")
        data = json.loads(result.stdout)
        assert data == {}
        assert result.returncode == 0

    def test_when_entity_ref_invalid_then_error_and_return_code_wrapped(
        self, test_config_env  # pylint: disable=unused-argument
    ):
        result = execute_cli("named", "bal:///doesNotExist")
        # Don't test the specific message as it couples to BAL specifics
        assert result.stderr.startswith("ERROR:")
        assert result.returncode == int(BatchElementError.ErrorCode.kEntityResolutionError)

def execute_cli(*args):
    """
    Executes simplerResolver with the supplied args, as per subprocess.run.
    """
    this_file = pathlib.Path(__file__)
    cli_path = this_file.parent / "simpleResolver.py"
    all_args = [sys.executable, str(cli_path)]
    all_args.extend(args)
    # We explicitly don't want an exception to be raised.
    # pylint: disable=subprocess-run-check
    return subprocess.run(all_args, capture_output=True, encoding="utf-8")

@pytest.fixture
def test_config_env(monkeypatch, tmpdir):
    """
    A fixture that configures the process environment such that the
    OpenAssetIO default config points to the example toml file.
    """
    this_file = pathlib.Path(__file__)
    config_file = this_file.parent / "bal_animals_openassetio_config.toml"
    monkeypatch.setenv("OPENASSETIO_DEFAULT_CONFIG", str(config_file))
    # Deliberately not same directory as the library JSON file, so
    # relies on ${config_dir} interpolation.
    monkeypatch.chdir(tmpdir)


#!/usr/bin/env python

def cycle(s):
	t = (s & 0x1ff) + (s >> 9) + s
	if t < 0:
		t = (t & 0x7fffffff) + 1
	return t

# test
start = n = 0xcafe
n = cycle(n)
cnt = 1
while n != start and cnt <= 0x7fffffff:
	n = cycle(n)
	cnt += 1
print('cnt=%d n=%d' % (cnt, n))


import json
from Chain import Chain
from WalletMainService import WalletMainService
from TxGetter import TxGetterScan

if __name__ == '__main__':
    wallet_main_service_scan = WalletMainService(TxGetterScan())
    chains = open('ChainData.json')
    chains_data = json.load(chains)
    to_analyse = open('ToAnalyse.json')
    to_analyse_data = json.load(to_analyse)

    for wallet in to_analyse_data['wallets']:
        needed_chain_data = next((x for x in chains_data['chains'] if x['chain'] == wallet['chain']), None)
        wallet_add = wallet['addr']

        if needed_chain_data is None:
            raise Exception("Chain " + wallet['chain'] + " not found in ChainData.json")

        chain_obj = Chain(needed_chain_data['chain'], needed_chain_data['api_base_url'], needed_chain_data['currency'],
                          needed_chain_data['decimals'], needed_chain_data['api_key'])

        wallet_main_service_scan.formatForWallet(wallet_add, chain_obj)


#!/usr/bin/env python3

from process import eyeless_render
import glob
import sys
from os import path

def affirmatrue(input_string):
    if "y" in input_string.lower():
        return True
    else:
        return False

input_argument_format = "eyeless.py face_input_dir render_output_dir (left)eye_input_dir (right_eye_input_dir)"
# Reading input arguments

properly_argumented = False
input_directory = ""
left_eye_directory = ""
right_eye_directory = ""
output_directory = ""

if len(sys.argv) == 4 or len(sys.argv) == 5:

    print("Reading input-folder argument...")
    input_directory = sys.argv[1]
    print(input_directory)

    print("Reading output-folder argument...")
    output_directory = sys.argv[2]
    print(output_directory)

    print("Reading eye-directory...")
    left_eye_directory = sys.argv[3]
    right_eye_directory = sys.argv[3]

if len(sys.argv) == 5:
    print("Reading right eye directory...")
    right_eye_directory = sys.argv[3]

elif len(sys.argv) > 5 or (len(sys.argv) < 4 and len(sys.argv) > 1):
    print("Wrong amount of input arguments!")
    print("Proper format:")
    print(input_argument_format)
    sys.exit()

# Runtime path input and verification
while not path.isdir(input_directory):
    print("Input filepaths.")
    print("Where is the folder containing the frames of the face?")
    input_directory = input()
    print("")

while not path.isdir(left_eye_directory):
    print("Where is the folder containing the eye animation?")
    left_eye_directory = input()
    right_eye_directory = left_eye_directory
    print("")

while not path.isdir(output_directory):
    print("Where do you want the finished files to go?")
    output_directory = input()
    print("")

# TODO: Separate left and right eye graphics

# Counting frames
face_frames = len(glob.glob1("media/face_input", "frame*.*"))
print("Counted "+str(face_frames)+" frames.")
eye_frames = len(glob.glob1("media/eye_input", "frame*.*"))
print("Counted "+str(eye_frames)+" frames in eye animation.")

current_eye_frame = 1
first_frame = "frame00001.png"

unpadded_frame_count = list(range(1, int(face_frames+1)))
frames = {}
for each_number in unpadded_frame_count:
    frames[str("frame"+str("%0*d" % (5, each_number))+".png")] = ("%0*d" % (5, each_number))

print("\nEngaging preview using: "+first_frame)

# Testing settings phase

testing = True
while testing:
    subdiv_res = int(input("\nInput subdivision resolution for eyes (1 to disable): "))

    if subdiv_res != 1:
        regr_mode = int(input("Input regression mode (3 for quadratic, 4 for cubic): "))
    else:
        regr_mode = 3

    pad_percent = float(int(input("Input padding percentage: %"))/100)
    mask_feather = int(input("Input mask feathering amount: "))

    eyeless_render(first_frame, current_eye_frame, testing, subdiv_res, regr_mode, pad_percent, mask_feather)
    testing = not affirmatrue(input("\nIs this result satisfactory? "))
    if testing:
        print("Ok, let's try again...")

reverse_animation = affirmatrue(input("Do you want to reverse the eye animation? "))

print("Great.")

# Rendering

print("\nRendering all frames...")
for every_frame in frames:
    try:
        eyeless_render(every_frame, current_eye_frame, testing, subdiv_res, regr_mode, pad_percent, mask_feather)
        print("Rendered frame: " + every_frame[5:-4] + "/" + str("%0*d" % (5, face_frames)))
    except ValueError:
        print("Could not find face in: "+every_frame)
        None
    except IndexError:
        print("Could not find face in: " + every_frame)
        None

    if reverse_animation:
        if current_eye_frame > 1:
            current_eye_frame -= 1
        else:
            current_eye_frame = eye_frames
    else:
        if current_eye_frame < eye_frames:
            current_eye_frame += 1
        else:
            current_eye_frame = 1


from Domain.book2 import *

def reducere_pret(lst_vanzari):
    result = []
    for vanzare in lst_vanzari:
        if get_reducere(vanzare)=="silver":
            pret_nou = get_pret(vanzare) - (5 / 100) * get_pret(vanzare)
            result.append(create_vanzare(
                get_id(vanzare),
                get_titlu(vanzare),
                get_gen(vanzare),
                pret_nou,
                get_reducere(vanzare),
            ))
        elif get_reducere(vanzare)=="gold":
            pret_nou = get_pret(vanzare) - (10 / 100) * get_pret(vanzare)
            result.append(create_vanzare(
                get_id(vanzare),
                get_titlu(vanzare),
                get_gen(vanzare),
                pret_nou,
                get_reducere(vanzare),
            ))
        else:
            result.append(vanzare)

    return result


import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns

labels = ['JC+I+G', 'K2P+I+G', 'F81+I+G', 'F84+I+G','HKY+I+G', 'GTR+I+G']

# labels_aa = ['JTT+I+G', 'LG+I+G', 'WAG+I+G', 'Dayhoff+I+G','-','-']

#matplotlib.style.use('fivethirtyeight')

#sns.set_style("dark")
sns.set_style("whitegrid")
#sns.set_style("white")
#sns.set_style("darkgrid")
#sns.set_style("ticks")

# Nucleotides:  data[0] - BioNJ, data[1] - ML, data[2] - NN (b10,b1,b1,cud,cu,cu)
data = [[72.47,87.83,73.63,87.3,88.27,79.87],
        [99.5,99.4,99.6,99.47,99.5,99.5],
        [99.5,99.27,99.6,99.57,99.5,99.43]]
# Nucleotides:  data[0] - BioNJ, data[1] - ML, data[2] - NN (b10,b1,b1,cud,cu,cu)
data_10000 = [[72.9,87.0,73.33,86.8,86.83,81.77],
        [100.0,100.0,100.0,100.0,100.0,100.0],
        [100.0,100.0,100.0,100.0,99.97,100.0]]

x = np.arange(len(labels))  # the label locations
# X = np.arange(len(labels_aa))
Y = np.arange(4)
#figs = plt.figure()
#ax = figs.add_axes([0,0,1,1])

fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1)
width = 0.35  # the width of the bars

# Nucleotides. Sequence length 1000
ax1.yaxis.set_major_formatter('{x:1.0f}%')

ax1.bar(x - width/2, data[0], color = 'darkorange', width=0.15, label='BioNJ')
ax1.bar(x , data[1], color = 'mediumblue', width=0.15, label='ML')
ax1.bar(x + width/2, data[2], color = 'maroon', width=0.15, label='NN')
ax1.set_ylim([0, 100])

# Amino acids. Sequence length 10000

ax2.yaxis.set_major_formatter('{x:1.0f}%')
ax2.bar(x - width/2, data_10000[0], color = 'darkorange', width = 0.15)
ax2.bar(x , data_10000[1], color = 'mediumblue', width = 0.15)
ax2.bar(x + width/2, data_10000[2], color = 'maroon', width = 0.15)
ax2.set_ylim([0, 100])

#ax1.annotate(text="p-value",xy=(1,120),annotation_clip=False)
#ax1.annotate(text="p-value",xy=(2,100),annotation_clip=False)

#fig.suptitle('Accuracy of reconstructions')
#fig.supylabel('%')

#legend = fig.legend(loc='upper right', frameon= False, ncol=3)
# Iterating over the bars one-by-one
counter = 0
for bar in ax1.patches:
        # Using Matplotlib's annotate function and
        # passing the coordinates where the annotation shall be done
        # x-coordinate: bar.get_x() + bar.get_width() / 2
        # y-coordinate: bar.get_height()
        # free space to be left to make graph pleasing: (0, 8)
        # ha and va stand for the horizontal and vertical alignment
 #       if counter == 0 or counter == 3 or counter == 6 or counter == 9 or counter == 12 or counter == 15:
         if counter < 6:
            ax1.annotate('***',
                       (bar.get_x() + bar.get_width() / 2,
                        bar.get_height()), ha='center', va='center',
                       size=10, xytext=(0, 4),
                       textcoords='offset points')
         elif counter >= 6 and counter < 12:
            ax1.annotate('ns',
                       (bar.get_x() + bar.get_width() / 2,
                        bar.get_height()), ha='center', va='center',
                       size=10, xytext=(0, 4),
                       textcoords='offset points')
         counter += 1
counter = 0

for bar in ax2.patches:
        # Using Matplotlib's annotate function and
        # passing the coordinates where the annotation shall be done
        # x-coordinate: bar.get_x() + bar.get_width() / 2
        # y-coordinate: bar.get_height()
        # free space to be left to make graph pleasing: (0, 8)
        # ha and va stand for the horizontal and vertical alignment
 #       if counter == 0 or counter == 3 or counter == 6 or counter == 9 or counter == 12 or counter == 15:
        if counter < 6:
            ax2.annotate('***',
                       (bar.get_x() + bar.get_width() / 2,
                        bar.get_height()), ha='center', va='center',
                       size=10, xytext=(0, 4),
                       textcoords='offset points')
        elif counter >= 6 and counter < 12:
            ax2.annotate('ns',
            (bar.get_x() + bar.get_width() / 2,
                        bar.get_height()), ha='center', va='center',
                        size=10, xytext=(0, 4),
                        textcoords='offset points')
        counter += 1

ax1.set_ylabel('1000 bp')
ax1.set_xticks(x, labels)

ax2.set_ylabel('10000 bp')
ax2.set_xticks(x, labels)

fig.tight_layout()

resolution_value = 200
plt.savefig("/home/nkulikov/Pictures/Final_plots/DNA_norm_high_resol.png", format="png", dpi=resolution_value)

plt.show()

legend = fig.legend(loc='upper right', frameon= False, ncol=3)
# Save the figure, ensuring that the legend doesn't get cut off
# using `bbox_extra_artists`
figpath = 'graph.png'
fig.savefig(figpath, bbox_extra_artists=[legend], bbox_inches='tight')

# ---------------------------------------------------------------------
# Create a separate figure for the legend
# ---------------------------------------------------------------------
# Bounding box for legend (in order to get proportions right)
# Issuing a draw command seems necessary in order to ensure the layout
# happens correctly; I was getting weird bounding boxes without it.
fig.canvas.draw()
# This gives pixel coordinates for the legend bbox (although perhaps
# if you are using a different renderer you might get something else).
legend_bbox = legend.get_tightbbox(fig.canvas.get_renderer())
# Convert pixel coordinates to inches
legend_bbox = legend_bbox.transformed(fig.dpi_scale_trans.inverted())

# Create teh separate figure, with appropriate width and height
# Create a separate figure for the legend
legend_fig, legend_ax = plt.subplots(figsize=(legend_bbox.width, legend_bbox.height))

# Recreate the legend on the separate figure/axis
legend_squared = legend_ax.legend(
    *ax1.get_legend_handles_labels(),
    bbox_to_anchor=(0, 0, 1, 1),
    bbox_transform=legend_fig.transFigure,
    frameon=False,
    fancybox=None,
    shadow=False,
    ncol=3,
    mode='expand',
)

# Remove everything else from the legend's figure
legend_ax.axis('off')

# Save the legend as a separate figure
legend_figpath = '/home/nkulikov/Pictures/Final_plots/graph-legend_final.png'
print(f"Saving to: {legend_figpath}")
legend_fig.savefig(
    legend_figpath,
    bbox_inches='tight',
    bbox_extra_artists=[legend_squared],
    dpi=resolution_value
)


import numpy as np
# import pandas as pd
import h5py
import argparse
import os

# def seq2instance(data, P, Q):
#     num_step, dims, nodes = data.shape
#     num_sample = num_step - P - Q + 1
#     x = np.zeros(shape = (num_sample, P, dims, nodes))
#     y = np.zeros(shape = (num_sample, Q, dims, nodes))
#     for i in range(num_sample):
#         x[i] = data[i : i + P, :, :]
#         y[i] = data[i + P : i + P + Q, :, :]
#     return x, y
#
# def loadTrafficData(args):
#     # Traffic
#     if args.traffic_file.endswith('npy'):
#         Traffic = np.load(args.traffic_file)
#     else:
#         f = h5py.File(args.traffic_file, 'r')
#         Traffic = f['data'].value
#
#     T_trend, len_trend, len_test = args.T_trend, args.len_trend, args.len_test
#
#     if len_trend > 0:
#         number_of_skip_hours = T_trend * len_trend
#     else:
#         print("wrong")
#     print('number_of_skip_hours:', number_of_skip_hours)
#
#     Traffic = Traffic[number_of_skip_hours - args.P - args.Q + 1:len(Traffic)]
#
#
#     Traffic = np.reshape(Traffic, (-1, Traffic.shape[1], Traffic.shape[2] * Traffic.shape[3]))
#     Traffic = np.transpose(Traffic, (0, 2, 1))
#
#     allX, allY = seq2instance(Traffic, args.P, args.Q)
#     num_step = allX.shape[0]
#     train_steps = round(args.train_ratio * (num_step - len_test))
#     test_steps = len_test
#     val_steps = num_step - train_steps - test_steps
#     trainX, trainY = allX[:train_steps], allY[:train_steps]
#     valX, valY = allX[train_steps:train_steps + val_steps], allY[train_steps:train_steps + val_steps]
#     testX, testY = allX[-test_steps:], allY[-test_steps:]
#
#     return (trainX, trainY, valX, valY, testX, testY)

def loadTrafficData(args):
    # Traffic
    if args.traffic_file.endswith('npy'):
        all_data = np.load(args.traffic_file)
        max, min = np.max(all_data), np.min(all_data)
    else:
        df = h5py.File(args.traffic_file, 'r')
        all_data = df['data'][:]
        max, min = np.max(all_data), np.min(all_data)

    len_total = len(all_data)
    T_closeness, T_period, T_trend = 1, args.T, args.T * 7

    if args.len_trend > 0:
        number_of_skip_hours = T_trend * args.len_trend
    elif args.len_period > 0:
        number_of_skip_hours = T_period * args.len_period
    elif args.len_closeness > 0:
        number_of_skip_hours = T_closeness * args.len_closeness
    else:
        print("wrong")
    print('number_of_skip_hours:', number_of_skip_hours)

    Y = all_data[number_of_skip_hours:len_total]
    len_train = round((len(Y) - args.len_test) * args.train_ratio)
    len_val = len(Y) - len_train - args.len_test

    if args.len_closeness > 0:
        X_closeness = all_data[number_of_skip_hours - T_closeness:len_total - T_closeness]
        for i in range(args.len_closeness - 1):
            X_closeness = np.concatenate(
                (X_closeness, all_data[number_of_skip_hours - T_closeness * (2 + i):len_total - T_closeness * (2 + i)]),
                axis=1)
    if args.len_period > 0:
        X_period = all_data[number_of_skip_hours - T_period:len_total - T_period]
        for i in range(args.len_period - 1):
            X_period = np.concatenate(
                (X_period, all_data[number_of_skip_hours - T_period * (2 + i):len_total - T_period * (2 + i)]), axis=1)
    if args.len_trend > 0:
        X_trend = all_data[number_of_skip_hours - T_trend:len_total - T_trend]
        for i in range(args.len_trend - 1):
            X_trend = np.concatenate(
                (X_trend, all_data[number_of_skip_hours - T_trend * (2 + i):len_total - T_trend * (2 + i)]), axis=1)

    X_closeness_train = X_closeness[:len_train]
    X_period_train = X_period[:len_train]
    X_trend_train = X_trend[:len_train]

    X_closeness_val = X_closeness[len_train:len_train + len_val]
    X_period_val = X_period[len_train:len_train + len_val]
    X_trend_val = X_trend[len_train:len_train + len_val]

    X_closeness_test = X_closeness[-args.len_test:]
    X_period_test = X_period[-args.len_test:]
    X_trend_test = X_trend[-args.len_test:]

    trainX = np.concatenate([X_closeness_train, X_period_train, X_trend_train], axis=1)
    valX = np.concatenate([X_closeness_val, X_period_val, X_trend_val], axis=1)
    testX = np.concatenate([X_closeness_test, X_period_test, X_trend_test], axis=1)

    trainY = Y[:len_train]
    valY = Y[len_train:len_train + len_val]
    testY = Y[-args.len_test:]

    # batch_size, seq, H * W, 2
    trainX = trainX.reshape(trainX.shape[0], trainX.shape[1], -1)
    trainX = trainX.reshape(trainX.shape[0], -1, 2, trainX.shape[-1])
    trainX = np.transpose(trainX, (0, 1, 3, 2))
    trainY = trainY.reshape(trainY.shape[0], trainY.shape[1], -1)
    trainY = np.expand_dims(np.transpose(trainY, (0, 2, 1)), 1)

    valX = valX.reshape(valX.shape[0], valX.shape[1], -1)
    valX = valX.reshape(valX.shape[0], -1, 2, valX.shape[-1])
    valX = np.transpose(valX, (0, 1, 3, 2))
    valY = valY.reshape(valY.shape[0], valY.shape[1], -1)
    valY = np.expand_dims(np.transpose(valY, (0, 2, 1)), 1)

    testX = testX.reshape(testX.shape[0], testX.shape[1], -1)
    testX = testX.reshape(testX.shape[0], -1, 2, testX.shape[-1])
    testX = np.transpose(testX, (0, 1, 3, 2))
    testY = testY.reshape(testY.shape[0], testY.shape[1], -1)
    testY = np.expand_dims(np.transpose(testY, (0, 2, 1)), 1)

    return trainX, trainY, valX, valY, testX, testY

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--dataset', default='BikeNYC', help='traffic file load path')
    parser.add_argument('--train_ratio', type=float, default=0.9, help='training set [default : 0.9]')
    parser.add_argument('--T', type=int, default=48, help='num of time intervals in one day = 48')
    parser.add_argument('--T_trend', type=int, default=336, help='num of time intervals in one day * num of day intervals in trend = 48 * 7')
    parser.add_argument('--len_closeness', type=int, default=3, help='len of closeness sequence = 3')
    parser.add_argument('--len_period', type=int, default=4, help='len of period sequence = 4')
    parser.add_argument('--len_trend', type=int, default=4, help='len of trend sequence = 4')
    parser.add_argument('--len_test', type=int, default=960, help='num of test samples = 960')
    parser.add_argument('--P', type=int, default=11, help='history steps')
    parser.add_argument('--Q', type=int, default=1, help='prediction steps')
    args = parser.parse_args()
    if args.dataset == 'BikeNYC':
        args.traffic_file = 'data/BikeNYC/bike_flow.npy'
        args.save_path = 'data/BikeNYC'
    elif args.dataset == 'TaxiNYC':
        args.traffic_file = 'data/TaxiNYC/taxi_flow.npy'
        args.save_path = 'data/TaxiNYC'
    elif args.dataset == 'TaxiBJ':
        args.traffic_file = 'data/TaxiBJ/BJ13_M32x32_T30_InOut.h5'
        args.save_path = 'data/TaxiBJ'
    else:
        raise ValueError('dataset does not exist')

    trainX, trainY, valX, valY, testX, testY = loadTrafficData(args)

    np.savez(os.path.join(args.save_path, 'train.npz'), x=trainX, y=trainY)
    np.savez(os.path.join(args.save_path, 'val.npz'), x=valX, y=valY)
    np.savez(os.path.join(args.save_path, 'test.npz'), x=testX, y=testY)


import datetime
import sqlite3
from flask import current_app, g

def obtain():
	if 'db_instance' not in g:
		g.db_instance = Database()
		g.db_instance.init_schema()
	return g.db_instance

def close_connection(e=None):
	db_instance = g.pop('db_instance', None)

	if db_instance is not None:
		db_instance.close()

class Database:
	def __init__(self):
		self.conn = sqlite3.connect(current_app.config["DB_NAME"])
		self.inp_register = InpRegister(self.conn)

	def init_schema(self):
		self.inp_register.init_schema()

	def close(self):
		self.conn.close()

class InpRegister:
	def __init__(self, conn):
		self.conn = conn

	def init_schema(self):
		cur = self.conn.cursor()
		cur.execute('''
			CREATE TABLE IF NOT EXISTS inp_register(
				id			 INTEGER    PRIMARY KEY    AUTOINCREMENT,
				sensor_date    INTEGER    NOT NULL,
				sensor_state   TEXT       NOT NULL,
				pc_date  INTEGER    NOT NULL       DEFAULT CURRENT_TIMESTAMP
			);
			''')
		self.conn.commit()
		cur.close()

	def insert(self, sensor_date, state):
		cur = self.conn.cursor()
		cur.execute('''
			INSERT INTO inp_register(sensor_date, sensor_state)
			VALUES (?, ?);
		''', (sensor_date.timestamp(), state))
		self.conn.commit()
		cur.close()

	def fetch_all(self, limit=0, offset=0):
		cur = self.conn.cursor()
		if limit > 0:
			result = cur.execute('''
				SELECT *
				FROM inp_register
				LIMIT ?
				OFFSET ?;
			''', (limit, offset))
		else:
			result = cur.execute('''
				SELECT *
				FROM inp_register;
			''')
		records = []
		for record in result.fetchall():
			record[1] = datetime.datetime.fromtimestamp(record[1])
			records.append(record)
		cur.close()
		return records

	def fetch_one(self, identifier):
		cur = self.conn.cursor()
		result = cur.execute('''
			SELECT *
			FROM inp_register
			WHERE id == ?;
		''', identifier)
		cur.close()
		data = result.fetchone()
		data[1] = datetime.datetime.fromtimestamp(data[1])
		return


import random
import sys
import itertools

def MR(n, k):
    """Implementation of the Miller-Rabin primality test.
        Inputs:
            - integer n, we will ensure it is greater than two and odd.
            - integer k, number rounds of testing to perform

        Pseudocode from
    https://en.wikipedia.org/wiki/Miller–Rabin_primality_test#Example.

    Returns False if definitely composite, True if probably prime.
    """

    # First test to ensure n > 2 and n odd
    if n == 1:
        return False
    if n == 2:
        return True
    if (n % 2 == 0):
        return False
    if n == 3:
        return True

    # Now find s and d
    s, d = get_s_d(n)

    #print(f"N:\n{n}\nn-1 = (2**{s})*{d}")

    for _ in range(k):
        b = random.randint(2, n-2)
        #print(f"B: {b}")
        x = pow(b, d, n)
        for _ in range(s):
            y = pow(x, 2, n)
            if y == 1 and x != 1 and (x != n-1):
                return False
            x = y
        if y != 1:
            return False

    return True

def get_s_d(n):
    n_m_1 = n-1
    s = 0
    old_d = n_m_1
    old_r = 0

    # Implementation of do-while loop
    while True:
        d, r = divmod(old_d, 2)
        if r != 0:
            break
        s += 1
        old_d = d
        old_r = r

    return s, old_d

if __name__ == "__main__":
    num_tests = int(sys.stdin.readline().rstrip('\n'))
    for i in range(num_tests):
        line = sys.stdin.readline()
        # Convert line to list of possible integers
        line = list(line.rstrip('\n'))

        subsets = []
        for i in range(1, len(line)+1):
            subsets.extend(itertools.permutations(line, r=i))

        possible_ints = [int(''.join(e)) for e in subsets]

        # Strip out duplicates
        possible_ints = list(set(possible_ints))

        #print(len(possible_ints))

        num_primes = 0
        for e in possible_ints:
            if MR(e, 20):
                num_primes += 1

        print(f"{num_primes}")


import torch
import torch.nn as nn
import torchvision.models as models

# model saved in /uac/gds/yuewang/.cache/torch/checkpoints/vgg16-397923af.pth
class EncoderCNN(nn.Module):
    def __init__(self, img_ext_model):
        """Load the pretrained ResNet-152 and replace top fc layer."""
        super(EncoderCNN, self).__init__()
        self.img_ext_model = img_ext_model
        if img_ext_model == 'resnet':
            resnet = models.resnet152(pretrained=True)
            modules = list(resnet.children())[:-1]  # delete the last fc layer.
            self.img_ext = nn.Sequential(*modules)
        elif self.img_ext_model == 'complex_resnet':
            resnet = models.resnet101(pretrained=True)
            modules = list(resnet.children())[:-2]  # delete the last fc layer.
            self.img_ext = nn.Sequential(*modules)
        elif img_ext_model == 'vgg':
            vgg = models.vgg16(pretrained=True)
            modules = list(vgg.children())[:-1]  # delete the last fc layer.
            self.img_ext = nn.Sequential(*modules)

    def forward(self, images):
        """Extract feature vectors from input images."""
        with torch.no_grad():
            features = self.img_ext(images)

        if self.img_ext_model == 'resnet':
            features = features.reshape(features.size(0), -1)
        elif self.img_ext_model == 'complex_resnet':
            features = features.view([features.size(0), 2048, -1]).permute([0, 2, 1])  # [batch_size, 49, 2048]
        elif self.img_ext_model == 'vgg':
            features = features.view([features.size(0), 512, -1]).permute([0, 2, 1])  # [batch_size, 49, 512]
        return features


import gspread
from tkinter import *
import pandas as pd

#a json-ön keresztül itt írom be a fájl nevét
gc = gspread.service_account(filename='finance.json')
#a google sheet kulcsát használva megnyitom és accesselem az elérést
sh = gc.open_by_key('1dEDppsJ306OLhxor_76GsV-pPLxmTt3wWhDGZjyxZe4')
#a sheet1 adatait használom
worksheet = sh.sheet1
#a sheetnek ezt a ranget használom, ezt olvasom be, külön el lehet érni sorokat, cellákat, oszlopokat vagy kiíratom az egész táblázatot
res = worksheet.get_all_records()
#printelem az egész sheetet, amit lekértem tőle

df = pd.DataFrame(res)
df = df.iloc[:342, 2:8]
df['Open'] = pd.to_numeric(df['Open'], downcast="float")
df['High'] = pd.to_numeric(df['High'], downcast="float")
df['Low'] = pd.to_numeric(df['Low'], downcast="float")
df['Close'] = pd.to_numeric(df['Close'], downcast="float")
df['Volume'] = pd.to_numeric(df['Volume'], downcast="float")
print(df.dtypes)
column = ['Date','Open', 'High', 'Low', 'Close', 'Volume']
df.to_csv('data.csv', columns=column)


import csv

def count_emotions_percentage_per_title(file_path):
    emotions_per_title = {}

    # Open the CSV file
    with open(file_path, 'r', newline='', encoding="utf-8") as file:
        reader = csv.reader(file, delimiter='\t')

        # Skip the header row
        next(reader)

        # Iterate over each row in the CSV file
        for row in reader:
            title = row[0]      # Extract the title from the row
            emotion = row[4]    # Extract the emotion from the row

            # Initialize a dictionary for each title if it doesn't exist
            if title not in emotions_per_title:
                emotions_per_title[title] = {'Freude': 0, 'Leid': 0, 'Ärger': 0, 'Verehrung': 0, 'Liebe': 0, 'Angst': 0, 'Abscheu': 0}

            # Initialize the emotion count for each title if it doesn't exist
            # if emotion not in emotions_per_title[title]:
            #     emotions_per_title[title][emotion] = 0

            # Increment the count for the emotion for the specific title
            emotions_per_title[title][emotion] += 1

        # Calculate the percentage of emotions for each title
        for title, emotions in emotions_per_title.items():
            total_emotions = sum(emotions.values())  # Calculate the total emotion count
            for emotion in emotions:
                # Calculate the percentage of each emotion for the specific title
                emotions[emotion] = emotions[emotion] / total_emotions * 100

    # Return the dictionary containing emotions percentage per title
    return emotions_per_title

# Define the file path of the CSV file
file_path = 'dialogue_data.csv'

#print(count_emotions_percentage_per_title(file_path))


def solution(lottos, win_nums):
    rank  = {6: 1, 5: 2, 4: 3, 3: 4, 2: 5, 1: 6, 0: 6}
    cnt = 0
    for n in lottos:
        if n in win_nums:
            cnt += 1
            win_nums.remove(n)
    return [rank[cnt+lottos.count(0)], rank[cnt]]

# 다른 풀이
# def solution(lottos, win_nums):
#     rank = {
#         0: 6,
#         1: 6,
#         2: 5,
#         3: 4,
#         4: 3,
#         5: 2,
#         6: 1
#     }
#     return [rank[len(set(lottos) & set(win_nums)) + lottos.count(0)], rank[len(set(lottos) & set(win_nums))]]
# set을 이용해 중복을 제거한 lottos와 중복을 제거한 win_nums의 교집합 원소의 개수에 lottos에 들어있는 0의 개수를 합한 값을
# rank의 key로 하면 최대 등수가 나오고, 그냥 교집합 원소의 개수를 key로 하면 최소 등수가 나온다.
# 문제에서 0을 제외한 다른 숫자들은 2개 이상 존재하지 않는다고 하였다. 따라서 set 쓰는 것이 가능!

python_programmers_school/level 1/로또의 최고 순위와 최저 순위.py

로또의 최고 순위와 최저 순위.py


class Solution:
    def completeRows(self, n : int) -> int:
        # code here
        total_rows = 0
        bricks_needed = 1
        while n >= bricks_needed:
            n -= bricks_needed
            bricks_needed += 1
            total_rows += 1
        return total_rows

#{
 # Driver Code Starts

if __name__=="__main__":
    t = int(input())
    for _ in range(t):

        n = int(input())

        obj = Solution()
        res = obj.completeRows(n)

        print(res)

# } Driver Code Ends

GFG/Problem of the day/Complete the Staircase.py


import re

def parse_data(puzzle_input: str):
    puzzle_data = []
    for line in puzzle_input.splitlines():
        if line != "":
            groups = re.search(r"(\d+),(\d+) -> (\d+),(\d+)", line).groups()
            puzzle_data.append(
                ((int(groups[0]), int(groups[1])), (int(groups[2]), int(groups[3])))
            )
    return puzzle_data

class HydroMap:
    def __init__(self, maxdimension):
        self.map = [[0] * maxdimension for _ in range(maxdimension)]

    def draw_line(self, start: tuple[int], end: tuple[int], diagonal=False):
        if start[0] == end[0] or start[1] == end[1]:
            x_range = sorted([start[0], end[0]])
            x_range[-1] += 1

            y_range = sorted([start[1], end[1]])
            y_range[-1] += 1

            for x in range(*x_range):
                for y in range(*y_range):
                    self.map[y][x] += 1
        elif diagonal:
            delta = abs(start[0] - end[0])
            x_rising = end[0] - start[0] > 0
            y_rising = end[1] - start[1] > 0

            for n in range(delta + 1):
                x = start[0] + n if x_rising else start[0] - n
                y = start[1] + n if y_rising else start[1] - n
                self.map[y][x] += 1

def solution_1(puzzle_input: str):
    puzzle_data = parse_data(puzzle_input)
    hydro_map = HydroMap(max([max(*start, *end) for start, end in puzzle_data]) + 1)
    for line in puzzle_data:
        hydro_map.draw_line(*line)

    return sum([cell > 1 for line in hydro_map.map for cell in line])

def solution_2(puzzle_input: str):
    puzzle_data = parse_data(puzzle_input)
    hydro_map = HydroMap(max([max(*start, *end) for start, end in puzzle_data]) + 1)
    for line in puzzle_data:
        hydro_map.draw_line(*line, diagonal=True)

    return sum([cell > 1 for line in hydro_map.map for cell in line])


#!/usr/bin/env python3
##############################################################################
###
### This file is part of the BBS software (Bioconductor Build System).
###
### Author: Hervé Pagès <hpages.on.github@gmail.com>
### Last modification: Oct 6, 2020
###

import sys
import os
import time

import bbs.parse
import bbs.notify
import BBSutils
import BBSvars
import BBSreportutils

published_report_url = BBSutils.getenv('BBS_PUBLISHED_REPORT_URL')

from_addr = "BBS-noreply@bioconductor.org"

msg_head = "[This is an automatically generated email. Please don't reply.]\n"

msg_tail = "Please take the time to address this by committing and pushing\n" \
         + "changes to your package at git.bioconductor.org\n"

msg_footnote = "Notes:\n\n" \
             + "  * This was the status of your package at the time this email was sent to you.\n" \
             + "    Given that the online report is updated daily (in normal conditions) you\n" \
             + "    could see something different when you visit the URL(s) above, especially if\n" \
             + "    you do so several days after you received this email.\n\n" \
             + "  * It is possible that the problems reported in this report are false positives,\n" \
             + "    either because another package (from CRAN or Bioconductor) breaks your\n" \
             + "    package (if yours depends on it) or because of a Build System problem.\n" \
             + "    If this is the case, then you can ignore this email.\n\n" \
             + "  * Please check the report again 24h after you've committed your changes to the\n" \
             + "    package and make sure that all the problems have gone.\n\n" \
             + "  * If you have questions about this report or need help with the\n" \
             + "    maintenance of your package, please use the Bioc-devel mailing list:\n\n" \
             + "      https://bioconductor.org/help/mailing-list/\n\n" \
             + "    (all package maintainers are requested to subscribe to this list)\n\n" \
             + "For immediate notification of package build status, please\n" \
             + "subscribe to your package's RSS feed. Information is at:\n\n" \
             + "https://bioconductor.org/developers/rss-feeds/\n\n" \
             + "Thanks for contributing to the Bioconductor project!\n\n"

def collect_problems(pkg, node):
    stage2command = {'install': 'R CMD INSTALL',
                     'buildsrc': 'R CMD build',
                     'checksrc': 'R CMD check'}
    stages_on_report = BBSreportutils.stages_to_display(BBSvars.buildtype)
    stages_to_collect = list(stage2command.keys() & stages_on_report)
    problem_descs = []
    for stage in stages_to_collect:
        status = BBSreportutils.get_pkg_status(pkg, node.node_id, stage)
        if status in ["TIMEOUT", "ERROR"]:
            problem_desc = "%s for '%s' on %s" % \
                           (status, stage2command[stage], node.node_id)
            rurl = BBSreportutils.get_leafreport_rel_url(pkg, node.node_id,
                                                         stage)
            problem_desc = "  o %s. See the details here:\n      %s%s\n" % \
                           (problem_desc, published_report_url, rurl)
            problem_descs.append(problem_desc)
    return problem_descs

def send_notification(dcf_record):
    pkg = dcf_record['Package']
    package_status = dcf_record.get('PackageStatus')
    if package_status == 'Deprecated':
        return
    maintainer_email = dcf_record['MaintainerEmail']
    #print("%s %s %s %s" % (pkg, version, maintainer, maintainer_email))
    #key = 'Last Changed Date'
    #last_changed_date = BBSreportutils.get_vcs_meta(pkg, key)
    #key = 'Last Changed Rev'
    #last_changed_rev = BBSreportutils.get_vcs_meta(pkg, key)

    problem_descs = []
    for node in BBSreportutils.supported_nodes(pkg):
        problem_descs += collect_problems(pkg, node)
    if len(problem_descs) == 0:
        return

    report_nodes = BBSutils.getenv('BBS_REPORT_NODES')
    report_title = BBSreportutils.make_report_title(report_nodes)
    if maintainer_email == "bioconductor@stat.math.ethz.ch":
        to_addrs = ["maintainer@bioconductor.org"]
    else:
        to_addrs = [maintainer_email]
    subject = "%s problems reported in the %s" % (pkg, report_title)
    msg = "%s\nHi %s maintainer,\n\n" % (msg_head, pkg) \
        + "According to the %s,\n" % report_title \
        + "the %s package has the following problem(s):\n\n" % pkg \
        + "%s\n%s\n%s" % ('\n'.join(problem_descs), msg_tail, msg_footnote)
    if arg1 == "":
        print("###########################################################")
        print("maintainer_email: %s\n" % maintainer_email)
        print("subject: %s\n" % subject)
        print(msg)
        print()
    print("BBS> Notifying maintainer(s) of %s:" % pkg)
    sys.stdout.flush()
    bbs.notify.sendtextmail(from_addr, to_addrs, subject, msg)
    return

def send_notifications(allpkgs):
    for pkg in allpkgs:
        send_notification(meat_pkgs[pkg])
    return

def send_BioC_notifications(allpkgs):
    print("BBS> [send_BioC_notifications] BEGIN...")
    send_notifications(allpkgs)
    print("BBS> [send_BioC_notifications] END.")
    return

def send_CRAN_notifications(allpkgs):
    print("BBS> [send_CRAN_notifications] BEGIN...")
    send_notifications(allpkgs)
    print("BBS> [send_CRAN_notifications] END.")
    return

##############################################################################
### MAIN SECTION
##############################################################################

print("BBS> [stage7] STARTING stage7 at %s..." % time.asctime())

notify_nodes = BBSutils.getenv('BBS_NOTIFY_NODES')
report_path = BBSutils.getenv('BBS_REPORT_PATH')

argc = len(sys.argv)
if argc > 1:
    arg1 = sys.argv[1]
else:
    arg1 = ""

if arg1 != "":
    bbs.notify.mode = "do-it"
    if arg1 != "do-it":
        bbs.notify.redirect_to_addr = arg1

os.chdir(report_path)

BBSreportutils.set_NODES(notify_nodes)

### Compute 'meat_pkgs' (dict) and 'allpkgs' (list).
meat_index = bbs.parse.parse_DCF(BBSutils.meat_index_file)
meat_pkgs = {}
for dcf_record in meat_index:
    meat_pkgs[dcf_record['Package']] = dcf_record
allpkgs = list(meat_pkgs.keys())
allpkgs.sort(key=str.lower)

print("BBS> [stage7] Import package statuses from %s ..." % \
      BBSreportutils.BUILD_STATUS_DB_file, end=" ")
sys.stdout.flush()
BBSreportutils.import_BUILD_STATUS_DB(allpkgs)
print("OK")
sys.stdout.flush()

print("BBS> [stage7] Notifying package maintainers for nodes: %s" % notify_nodes)
buildtype = BBSutils.getenv('BBS_BUILDTYPE', False, "bioc")
if buildtype == "cran":
    send_CRAN_notifications(allpkgs)
else:
    send_BioC_notifications(allpkgs)

print("BBS> [stage7] DONE at %s." % time.asctime())


#!/usr/bin/python
import flask
import logging
import foosball.blueprint

logger = logging.getLogger(__name__)

controller = foosball.blueprint.Blueprint('main', __name__)

# Handler for the GET requests
@controller.route('/')
def home():
    return flask.render_template(
        'players.html', players=controller.db.players(), title='FOOS', page_name='home')

@controller.route('/player/<int:player_id>/results.json')
def player_results(player_id):
    player = controller.db.player(player_id)
    result_count = controller.db.result_count(player)
    results = {'results': controller.db.results(player, offset=0, limit=result_count, epoch=True)}
    return flask.jsonify(results)

@controller.route('/player/<int:player_id>/graph/')
def player_graph(player_id):
    return flask.render_template('cumlativegraph.html',
        player=controller.db.player(player_id), title='FOOS');

@controller.route('/player/<int:player_id>/<string:name>/')
@controller.route('/player/<int:player_id>/')
def player(player_id, name=None):
    result_page = int(flask.request.args.get('page', '1'))
    page_size = 10
    player = controller.db.player(player_id)
    if name is not None and not name == player['name'].lower():
        raise Exception("name does not match")

    scores = controller.db.scores(player)
    offset = (result_page-1) * page_size
    results = controller.db.results(player, offset=offset, limit=page_size)
    result_count = controller.db.result_count(player)
    total_pages = int(result_count/page_size)
    if result_page < 0 or (total_pages > 1 and result_page > total_pages):
        raise Exception('cant be less than 0')

    return flask.render_template(
        'player.html', player=player, scores=scores,
        results=results, result_count=result_count,
        result_page=result_page, total_pages=total_pages,
        page_size=page_size,
        title='FOOS')


from glob import glob

token = ''
line = ''
cIdx = 0

def error():
    print("syntax error!")
    exit(1)

def getchar():
    global cIdx
    c = line[cIdx]
    cIdx += 1
    return c

def getToken():
    global token
    while (True):
        token = getchar()
        if (token != ' '):
            return

def match(c):
    if (token == c):
        getToken()
    else:
        error()

def command():
    result = expr()
    if (token == '\n'):
        print(str(result))
    else:
        error()

# <expr> -> <term> (+ <term>, -<term>)

def expr():
    result = term()
    while (token == '+' or token == '-'):
        if (token == '+'):
            match('+')
            result += term()
        elif (token == '-'):
            match('-')
            result -= term()

    return result

# <term> -> <factor> (* <factor> | / <factor>) */

def term():
    result = factor()
    while (token == '*' or token == '/'):
        if (token == '*'):
            match('*')
            result *= factor()
        elif (token == '/'):
            match('/')
            result /= factor()
    return result

# <factor> -> [-](<number> | (<expr>) )

def factor():
    result = 1
    if (token == '-'):
        match('-')
        result = -1
    if (token == '('):
        match('(')
        result *= expr()
        if (token == ')'):
            match(')')
        else:
            error()
            exit(1)
    else:
        result *= number()
    return result

# <number> -> <digit>:{<digit>}

def number():
    result = digit()
    while (token.isdigit()):
        result = 10 * result + digit()
    return result

# digit -> 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

def digit():
    result = 1
    if (token.isdigit()):
        result = int(token)
        match(token)
    else:
        error()
    return result

def parse():
    getToken()
    command()

def main():
    global line, token, cIdx
    while(True):
        token = ''
        cIdx = 0
        print(">> ", end='')
        line = input() + '\n'
        parse()

main()