import unittest
from BBTools.BBToolsImpl import BBTools
from BBTools.BBToolsServer import MethodContext
from installed_clients.authclient import KBaseAuth as _KBaseAuth
from BBTools.utils.MemEstimatorRunner import MemEstimatorRunner
import os
try:
    from ConfigParser import ConfigParser  # py2
except:
    from configparser import ConfigParser  # py3

class MemEstimatorTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        token = os.environ.get('KB_AUTH_TOKEN', None)
        config_file = os.environ.get('KB_DEPLOYMENT_CONFIG', None)
        cls.cfg = {}
        config = ConfigParser()
        config.read(config_file)
        for nameval in config.items('BBTools'):
            cls.cfg[nameval[0]] = nameval[1]
        # Getting username from Auth profile for token
        authServiceUrl = cls.cfg['auth-service-url']
        auth_client = _KBaseAuth(authServiceUrl)
        user_id = auth_client.get_user(token)
        # WARNING: don't call any logging methods on the context object,
        # it'll result in a NoneType error
        cls.ctx = MethodContext(None)
        cls.ctx.update({'token': token,
                        'user_id': user_id,
                        'provenance': [
                            {'service': 'BBTools',
                             'method': 'please_never_use_it_in_production',
                             'method_params': []
                             }],
                        'authenticated': 1})
        cls.serviceImpl = BBTools(cls.cfg)
        cls.scratch = cls.cfg['scratch']
        cls.callback_url = os.environ['SDK_CALLBACK_URL']

    def test_mem_estimator_ok_unit(self):
        in_file = os.path.join('data','reads','interleaved.fastq')
        params = {
            "reads_file": in_file
        }
        runner = MemEstimatorRunner(params)
        estimate = runner.run()
        self.assertGreater(estimate["estimate"], 0)
        self.assertGreater(estimate["size"], 0)

    def test_mem_estimator_ok_pair(self):
        params = {
            "reads_file": os.path.join('data','reads','small.forward.fq'),
            "reads_file2": os.path.join('data','reads','small.reverse.fq')
        }
        runner = MemEstimatorRunner(params)
        estimate = runner.run()
        self.assertGreater(estimate["estimate"], 0)
        self.assertGreater(estimate["size"], 0)

    def test_mem_estimator_pair_dups(self):
        in_file = os.path.join('data','reads','interleaved.fastq')
        params = {
            "reads_file": in_file,
            "reads_file2": in_file
        }
        with self.assertRaises(ValueError) as e:
            MemEstimatorRunner(params)
        self.assertIn("If two files are present, they must be different.", str(e.exception))

    def test_mem_estimator_bad_file(self):
        in_file = os.path.join('data','reads','bad_reads.txt')
        params = {
            "reads_file": in_file
        }
        with self.assertRaises(ValueError) as e:
            MemEstimatorRunner(params).run()
        self.assertIn("Count of unique 31-mers not found.", str(e.exception))
        self.assertNotIn("31-mers processed", str(e.exception))
        self.assertNotIn("Correct 31-mers", str(e.exception))
        self.assertNotIn("Unique 31-mers", str(e.exception))

    def getImpl(self):
        return self.__class__.serviceImpl

    def getContext(self):
        return self.__class__.ctx

    def test_mem_estimator_e2e(self):
        impl = self.getImpl()
        ctx = self.getContext()
        in_file = os.path.join('data','reads','interleaved.fastq')
        params = {
            "reads_file": in_file
        }
        res = impl.run_mem_estimator(ctx, params)[0]
        self.assertIn("estimate", res)
        self.assertGreater(res["estimate"], 0)

        params = {
            "reads_file": os.path.join('data','reads','small.forward.fq'),
            "reads_file2": os.path.join('data','reads','small.reverse.fq')
        }
        res = impl.run_mem_estimator(ctx, params)[0]
        self.assertIn("estimate", res)
        self.assertGreater(res["estimate"], 0)
        self.assertIn("size", res)
        self.assertGreater(res["size"], 0)

    def test_bad_inputs(self):
        impl = self.getImpl()
        ctx = self.getContext()
        with self.assertRaises(ValueError) as e:
            MemEstimatorRunner({})
        self.assertIn('Parameter "reads_file" must be present!', str(e.exception))

        with self.assertRaises(ValueError) as e:
            impl.run_mem_estimator(ctx, {"reads_file": "not_real"})
        self.assertIn("The file not_real does not seem to exist, or is a directory", str(e.exception))

        with self.assertRaises(ValueError) as e:
            impl.run_mem_estimator(ctx, {
                "reads_file": os.path.join('data','reads','interleaved.fastq'),
                "reads_file2": "not_real2"}
            )
        self.assertIn("The file not_real2 does not seem to exist, or is a directory", str(e.exception))


import sys
import time
import pyspark
from operator import add
from collections import defaultdict, deque
from itertools import combinations
from pyspark import SparkContext, SQLContext, StorageLevel, SparkConf
from pyspark.sql import functions
from graphframes import *

threshold, inpath, btw_outpath, comm_outpath = int(sys.argv[-4]), sys.argv[-3], sys.argv[-2], sys.argv[-1]
start = time.time()
sc = SparkContext(appName="task2")
sc.setLogLevel("WARN")

#graph
def load(x):
    arr = x.split(',')
    return (str(arr[1]), str(arr[0]))
data = sc.textFile(inpath).filter(lambda x : x != ('user_id,business_id'))\
        .map(load).groupByKey().mapValues(list)\
        .map(lambda x: sorted(x[1]))\
        .flatMap(lambda x: [(com, 1) for com in combinations(x, 2)])\
        .reduceByKey(add).filter(lambda x: x[1] >= threshold)\
        .flatMap(lambda x: [(x[0][0], x[0][1]), (x[0][1], x[0][0])])
graph = defaultdict(set)
for n1, n2 in data.collect():
    graph[n1].add(n2)
    graph[n2].add(n1)

#Between
def get_btw(node):
    edgeVal = defaultdict(float)
    q = deque([node])
    parent = defaultdict(set)
    parent[node] = set()
    degree = {node: 0}
    node_val = {}
    mx = 0

    while q:
        n = q.popleft()
        for child in graph[n]:
            if child not in parent:
                parent[child].add(n)
                degree[child] = degree[n]+1
                mx = max(mx, degree[child])
                q.append(child)
            else:
                if degree[child] > degree[n]:
                    parent[child].add(n)

    degree = sorted(list(degree.items()), key=lambda x: x[1])
    q = deque([i[0] for i in degree][::-1])
    path = {node: 1}
    for arr in degree[1:]:
        n = arr[0]
        path[n] = sum([path[p] for p in parent[n]])

    while q:
        cur = q.popleft()
        for par in parent[cur]:
            if par not in node_val:
                node_val[par] = 1
            val = node_val.get(cur, 1)*path[par]/path[cur]
            node_val[par] += val
            pair = tuple(sorted([cur, par]))
            edgeVal[pair] += val

    return edgeVal.items()

nodes = sc.parallelize(graph.keys())
btw = nodes.flatMap(get_btw).reduceByKey(add).map(lambda x: (x[0], x[1]/2))
sort_btw = sorted(btw.collect(), key=lambda x: (-x[1], x[0]))

with open(btw_outpath, 'w') as f:
    for row in sort_btw:
        f.write(str(row[0])+','+str(round(row[1], 5))+'\n')

#Community
def get_community_btw(comm_idx):
    edgeVal = defaultdict(float)
    for node in graph.keys():
        if node not in comm[comm_idx]:
            comm_idx += 1
            comm[comm_idx] = set([node])

        q = deque([node])
        parent = defaultdict(set)
        parent[node] = set()
        degree = {node: 0}
        node_val = {}
        mx = 0

        while q:
            n = q.popleft()
            for child in graph[n]:
                if child not in parent:
                    comm[comm_idx].add(child)
                    parent[child].add(n)
                    degree[child] = degree[n]+1
                    mx = max(mx, degree[child])
                    q.append(child)
                else:
                    if degree[child] > degree[n]:
                        parent[child].add(n)

        degree = sorted(list(degree.items()), key=lambda x: x[1])
        q = deque([i[0] for i in degree][::-1])
        path = {node: 1}
        for arr in degree[1:]:
            n = arr[0]
            path[n] = sum([path[p] for p in parent[n]])

        while q:
            cur = q.popleft()
            for par in parent[cur]:
                if par not in node_val:
                    node_val[par] = 1
                val = node_val.get(cur, 1)*path[par]/path[cur]
                node_val[par] += val
                pair = tuple(sorted([cur, par]))
                edgeVal[pair] += val

    return sorted(list(edgeVal.items()), key=lambda x: (-x[1], x[0]))

def del_high_btw():
    if not sort_btw: return False
    pair, high = sort_btw.popleft()
    graph[pair[0]].remove(pair[1])
    graph[pair[1]].remove(pair[0])

    if not sort_btw: return False
    while sort_btw[0][1] == high:
        pair, high = sort_btw.popleft()
        graph[pair[0]].remove(pair[1])
        graph[pair[1]].remove(pair[0])
        if not sort_btw: return False
    return True

def get_Q():
    def get_sum(pair):
        n1, n2 = pair
        A = 1 if n2 in org_graph[n1] else 0
        return A-(len(graph[n1])*len(graph[n2])/(2*m))

    q_val = sc.parallelize(list(comm.values()))\
               .flatMap(lambda x: [(com, 1) for com in combinations(list(x), 2)])\
               .distinct().map(lambda x: x[0])\
               .map(get_sum).reduce(add)

    return q_val

mxQ = -1
res_comm = {}
comm = {0:set()}
m = len(sort_btw)
org_graph = graph
sort_btw = deque(sort_btw)
while del_high_btw():
    sort_btw = deque(get_community_btw(0))
    temp_q = get_Q()/(2*m)
    if temp_q > mxQ:
        mxQ = temp_q
        res_comm = comm
    comm = {0:set()}

del res_comm[0]
res = []
visited = set()
for idx, arr in res_comm.items():
    arr = sorted(arr)
    temp = arr[0]
    if temp not in visited:
        visited.add(temp)
        res.append(arr)
out = sorted(res, key=lambda x: (len(x), x[0]))
with open(comm_outpath, 'w') as f:
    for arr in out:
        f.write("'" + "', '".join(arr) + "'\n")

print("------------Time: ", time.time()-start)


class AllTrees:
    def __init__(self,n):
        self.edges=[]
        self.n=n

    def repres(self, x, parents):
        while x!=parents[x]:
            x=parents[x]
        return x

    def add_edge(self, a ,b):
        self.edges.append((a, b))

    def istree(self, edges):
        components=self.n
        parents=[i for i in range(self.n+1)]
        compsize=[1]*(self.n+1)
        def repres(x):
            while x!=parents[x]:
                x=parents[x]
            return x

        def merge(a, b):
            a=repres(a)
            b=repres(b)
            if a==b:
                return
            if compsize[a]<compsize[b]:
                a,b=b,a
            parents[b]=a
            compsize[a]+=compsize[b]
        for edge in edges:
            if repres(edge[0])==repres(edge[1]):
                continue
            merge(edge[0], edge[1])
            components-=1
        return components==1

    def find_edge_combinations(self, edgelist):
        if len(edgelist)==self.n-1:
            self.edgecombs.add(tuple(sorted(edgelist)))
            return
        for edge in self.edges:
            if edge in edgelist:
                continue
            self.find_edge_combinations(edgelist+[edge])

    def count(self):
        self.trees=0
        self.edgecombs=set()
        self.find_edge_combinations([])
        for combination in self.edgecombs:
            if self.istree(combination):
                self.trees+=1
        return self.trees

if __name__ == "__main__":
    a = AllTrees(3)
    a.add_edge(1,2)
    print(a.count()) # 0
    a.add_edge(1,3)
    print(a.count()) # 1
    a.add_edge(2,3)
    print(a.count()) # 3


for r in range(int(input())):
    n = int(input())
    tem = input().split()
    nums = []
    for a in tem:
        nums.append(int(a))
    res = []
    for x in nums:
        tem = 1
        for y in nums:
            if y != x:
                tem = tem * y
        res.append(tem)
    for x in res:
        print(x,end = " ")
    print()


#!/usr/bin/env python
'''
Impactos Ambientales
---------------------------
Autor: Pedro Luis Lugo Garcia
Version: 1.0

Descripcion:
Programa creado para realizar los cálculos del ODP.
'''

__author__ = "Pedro Luis Lugo Garcia"
__email__ = "pedro.lugo@unc.edu.ar"
__version__ = "1.0"

import math

def validarNumero(numero):
    try:
        if len(numero) == 0:
            return False
        else:
            if isinstance(numero, str) == False:
                return False
            else:
                return True
    except ValueError:
        return False

def validaDatos(nombre, sodio, calcio, magnesio, bicarbonato, salinidadCe):

    if (isinstance(nombre, str) == False or len(nombre) == 0):
        return "El compuesto no puede estar vacio o nulo"
    if validarNumero(sodio) == False or float(sodio) <= 0:
        return "El Sodio no puede estar vacio, nulo, negativo o letras"
    if validarNumero(calcio) == False or float(calcio) <= 0:
        return "El Calcio no puede estar vacio, nulo, negativo o letras"
    if validarNumero(magnesio) == False or float(magnesio) <= 0:
        return "El Magnesio puede estar vacio, nulo, negativo o letras"
    if validarNumero(bicarbonato) == False or float(bicarbonato) <= 0:
        return "El Bicarbonato HCO3- no puede estar vacio, nulo, negativo o letras"
    if validarNumero(salinidadCe) == False or float(salinidadCe) <= 0:
        return "La salinidad no puede estar vacio, nulo, negativo o letras"


# coding: utf-8

# In[2]:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Reading tags.csv file
tag_headers = ['user_id', 'movie_id', 'tag', 'timestamp']
tags = pd.read_csv(r'C:\Users\Abhilash Gandham\Desktop\ml-latest-small\tags.csv',header=None,skiprows = 1, names=tag_headers)
#Reading ratings.csv file
rating_headers = ['user_id', 'movie_id', 'rating', 'timestamp']
ratings = pd.read_csv(r'C:\Users\Abhilash Gandham\Desktop\ml-latest-small\ratings.csv', header=None,skiprows = 1, names=rating_headers)
#Reading movies.csv file
movie_headers = ['movie_id', 'title', 'genres']
movies = pd.read_csv(r'C:\Users\Abhilash Gandham\Desktop\ml-latest-small\movies.csv', header=None,skiprows = 1, names=movie_headers)
movie_titles = movies.title.tolist()

# In[3]:

#Combined both movies and tags data
df = movies.join(ratings, on=['movie_id'], rsuffix='_r').join(tags, on=['movie_id'], rsuffix='_t')
#df is the dataframe obtained

# In[4]:

del df['movie_id_r']
del df['user_id_t']
del df['movie_id_t']
del df['timestamp_t']

# In[5]:

#Changed structure of dataframe by converting index to user_id; columns to movie_id and their values as rating
rp = df.pivot_table(columns='movie_id',index='user_id',values='rating')

# In[6]:

rp = rp.fillna(0) # Replace NaN

# In[7]:

Q = rp.values #Converting dataframe to matrix form

# In[31]:

Q

# In[8]:

W = Q>0.5
W[W == True] = 1
W[W == False] = 0
# To be consistent with our Q matrix
W = W.astype(np.float64, copy=False)
#W is the weight matrix to consider the users and movies who only rated

# In[9]:

lambda_ = 0.1
n_factors = 100 # number of latent factors to be considered
m, n = Q.shape
n_iterations = 1 # number of iterations

# In[46]:

np.random.rand(2,2)

# In[10]:

_X = 5 * np.random.rand(m, n_factors) #random matrix of m users with n_factors latent factors
Y = 5 * np.random.rand(n_factors, n) #random matrix of n_factors latent factors with n users

# In[11]:

#Error function between given data and modeled data
def get_error(Q, X, Y, W):
    return np.sum((W * (Q - np.dot(X, Y)))**2)

# In[12]:

np.dot(Y, Y.T) + lambda_ * np.eye(n_factors)

# In[13]:

np.dot(Y, Q.T)

# In[14]:

#calculating errors and also obtaining the best convergence point by iterating through n_iterations
#This is without considering the W (weight) factor
errors = []
for ii in range(n_iterations):
    X = np.linalg.solve(np.dot(Y, Y.T) + lambda_ * np.eye(n_factors),
                        np.dot(Y, Q.T)).T
    Y = np.linalg.solve(np.dot(X.T, X) + lambda_ * np.eye(n_factors),
                        np.dot(X.T, Q))
    if ii % 100 == 0:
        print('{}th iteration is completed'.format(ii))
    errors.append(get_error(Q, X, Y, W))
Q_hat = np.dot(X, Y)
print('Error of rated movies: {}'.format(get_error(Q, X, Y, W)))

# In[15]:

#print function to obtain the recommendend movies with predicted rating
def print_recommendations(W=W, Q=Q, Q_hat=Q_hat, movie_titles=movie_titles):
    #Q_hat -= np.min(Q_hat)
    #Q_hat[Q_hat < 1] *= 5
    Q_hat -= np.min(Q_hat)
    Q_hat *= float(5) / np.max(Q_hat)
    movie_ids = np.argmax(Q_hat - 5 * W, axis=1)
    for jj, movie_id in zip(range(m), movie_ids):
        #if Q_hat[jj, movie_id] < 0.1: continue
        print('User {} liked {}\n'.format(jj + 1, ', '.join([movie_titles[ii] for ii, qq in enumerate(Q[jj]) if qq > 3])))
        print('User {} did not like {}\n'.format(jj + 1, ', '.join([movie_titles[ii] for ii, qq in enumerate(Q[jj]) if qq < 3 and qq != 0])))
        print('\n User {} recommended movie is {} - with predicted rating: {}'.format(
                    jj + 1, movie_titles[movie_id], Q_hat[jj, movie_id]))
        print('\n' + 100 *  '-' + '\n')

# In[16]:

#Calculating weighter errors and iterating through n_iterations to get the best convergence point
weighted_errors = []
for ii in range(n_iterations):
    for u, Wu in enumerate(W):
        X[u] = np.linalg.solve(np.dot(Y, np.dot(np.diag(Wu), Y.T)) + lambda_ * np.eye(n_factors),
                               np.dot(Y, np.dot(np.diag(Wu), Q[u].T))).T
    for i, Wi in enumerate(W.T):
        Y[:,i] = np.linalg.solve(np.dot(X.T, np.dot(np.diag(Wi), X)) + lambda_ * np.eye(n_factors),
                                 np.dot(X.T, np.dot(np.diag(Wi), Q[:, i])))
    weighted_errors.append(get_error(Q, X, Y, W))
    print('{}th iteration is completed'.format(ii))
weighted_Q_hat = np.dot(X,Y)

# In[17]:

print_recommendations(Q_hat=weighted_Q_hat)

# In[18]:

from sklearn.metrics import accuracy_score

# In[25]:

Q1 = Q.tolist()

# In[26]:

weighted_Q_hat1 = weighted_Q_hat.tolist()

# In[47]:

Q_hat

# In[41]:

weighted_Q_hat

# In[48]:

Q

# In[38]:

sum = 0
for i in range(len(weighted_errors)):
    sum = sum + weighted_errors[i]
sum = sum /n_iterations
sum = sum ** (1/2)
print(sum)


from __future__ import division
from sklearn.metrics import accuracy_score, precision_score, recall_score

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

class CifarLogisticRegression:
    def __init__(self,
                 trainingDataSet,
                 testingDataSet,
                 learningRate=0.001,
                 tolerance=0.001,
                 maxIterations=1000):
        self.trainingDataSet = trainingDataSet
        self.testingDataSet = testingDataSet
        self.learningRate = learningRate
        self.tolerance = tolerance
        self.maxIterations = maxIterations

    def sigmoid(self, z):
        return 1.0 / (1.0 + np.exp(-z))

    def hypothesis(self, X, theta):
        return self.sigmoid(np.dot(X, theta))

    def cost(self, X, Y, theta):
        probabilities = self.hypothesis(X, theta)

        return (np.multiply(-Y, np.log(probabilities)) - np.multiply(
            (1 - Y), np.log(1 - probabilities))).mean()

    def gradient(self, X, Y, theta):
        prediction = self.hypothesis(X, theta)
        error = prediction - Y

        return np.dot(X.T, error) / X.shape[0]

    def logisticRegression(self, dataSet):
        X = np.matrix(dataSet.iloc[:, :-1])
        Y = np.matrix(dataSet.iloc[:, -1]).T

        attributes = dataSet.shape[1] - 1
        theta = np.matrix(np.random.uniform(-1, 1, attributes)).T

        logisticLoss = [self.cost(X, Y, theta)]
        iterations = 0
        for i in range(self.maxIterations):
            iterations = i + 1
            gradient = self.gradient(X, Y, theta)
            newTheta = theta - self.learningRate * gradient
            newCost = self.cost(X, Y, newTheta)
            if (logisticLoss[i] - newCost < self.tolerance):
                break
            else:
                logisticLoss.append(newCost)
                theta = newTheta

        plt.plot(logisticLoss)
        plt.xlabel('Iteration')
        plt.ylabel('Logistic Loss')
        plt.title('Logistic Regression')
        plt.show()

        return theta, iterations

    def predict(self, X, theta):
        probabilities = self.hypothesis(X, theta)

        return [
            1 if probability >= 0.5 else 0 for probability in probabilities
        ]

    def accuracy(self, dataSet, theta):
        X = np.matrix(dataSet.iloc[:, :-1])
        Y = dataSet.iloc[:, -1]

        prediction = self.predict(X, theta)

        accuracy = accuracy_score(Y, prediction)
        precision = precision_score(Y, prediction, average="weighted")
        recall = recall_score(Y, prediction, average="weighted")

        return accuracy, precision, recall

    def validate(self):
        print("Training Data Set:")
        theta, iterations = self.logisticRegression(self.trainingDataSet)
        print("\tIterations: {}".format(iterations))
        trainAccuracy, trainPrecision, trainRecall = self.accuracy(
            self.trainingDataSet, theta)
        print("\tAccuracy: {}\n\tPrecision: {}\n\tRecall: {}".format(
            trainAccuracy, trainPrecision, trainRecall))

        print("Test Data Set:")
        testAccuracy, testPrecision, testRecall = self.accuracy(
            self.testingDataSet, theta)

        print("\tAccuracy:{}\n\tPrecision:{}\n\tRecall:{}".format(
            testAccuracy, testPrecision, testRecall))

def importData(fileName):
    dataSet = pd.read_pickle(fileName)

    return dataSet

if __name__ == "__main__":
    cifarTrainFileName = 'TrainData.pkl'
    cifarTrainDataSet = importData(cifarTrainFileName)

    cifarTestFileName = 'TestData.pkl'
    cifarTestDataSet = importData(cifarTestFileName)

    for learningRate in [0.1]:
        print("Learning Rate: {}".format(learningRate))
        for tolerance in [0.0001]:
            print("Tolerance: {}".format(tolerance))
            cifarLogisticRegression = CifarLogisticRegression(
                cifarTrainDataSet, cifarTestDataSet, learningRate, tolerance)
            cifarLogisticRegression.validate()


import pygame
import sys
import pandas as pd

from settings import Settings
from tile import Tile
from sudoku import Solver

class SudokuVisualizer:
    """Overall class to manage algorithm visualizer"""

    def __init__(self):
        """Initialize game assets"""

        # Pygame basic settings
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode(
            (self.settings.screen_size,
            self.settings.screen_size)
        )
        pygame.display.set_caption("Sudoku Solver")

        # Matrix to represent board
        self.board, self.solution = self._create_board()
        self.tiles = pygame.sprite.Group()
        self._create_tiles()
        self.selected_tile = None

        # Solver object
        self.solver = Solver(self, self.board)

    def run_visualizer(self):
        """Main loop of visualizer"""
        while True:
            self._check_events()
            self.update_screen()

    def _check_events(self):
        """Respond to events"""
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            elif event.type == pygame.MOUSEBUTTONDOWN:
                mouse_pos = pygame.mouse.get_pos()
                self._check_mouse_click(mouse_pos)

            elif event.type == pygame.KEYDOWN:
                self._check_keydown_event(event)

    def _check_keydown_event(self, event):
        """Respond to key presses"""

        # Solve button clicked
        if event.key == pygame.K_s:
            self.solver.solve((0,0))

        # Number clicked
        if self.selected_tile:
            self._check_number_click(event)

            # Try to insert number into final board
            if event.key == pygame.K_RETURN:
                self._check_enter_press()

            self.selected_tile.prep_number()

    def _check_number_click(self, event):
        """Respond to number presses"""
        if event.key == pygame.K_0:
            self.selected_tile.user_number = 0
        elif event.key == pygame.K_1:
            self.selected_tile.user_number = 1
        elif event.key == pygame.K_2:
            self.selected_tile.user_number = 2
        elif event.key == pygame.K_3:
            self.selected_tile.user_number = 3
        elif event.key == pygame.K_4:
            self.selected_tile.user_number = 4
        elif event.key == pygame.K_5:
            self.selected_tile.user_number = 5
        elif event.key == pygame.K_6:
            self.selected_tile.user_number = 6
        elif event.key == pygame.K_7:
            self.selected_tile.user_number = 7
        elif event.key == pygame.K_8:
            self.selected_tile.user_number = 8
        elif event.key == pygame.K_9:
            self.selected_tile.user_number = 9

    def _check_enter_press(self):
        """Determine if user number is correct number"""

        # Get correct number from solution board
        correct_number = (self.solution[self.selected_tile.position[0]]
                         [self.selected_tile.position[1]])

        # Correct guess
        if (self.selected_tile.user_number == correct_number):
            self.selected_tile.number = self.selected_tile.user_number
            self.selected_tile.final = True

            # Update board number
            self.board[self.selected_tile.position[0]] \
                [self.selected_tile.position[1]] = self.selected_tile.number

        # Incorrect guess
        else:
            self.selected_tile.user_number = 0

    def _check_mouse_click(self, mouse_pos):
        """Respond to click on tile"""
        tiles_clicked = [
            t for t in self.tiles if t.rect.collidepoint(mouse_pos)
        ]

        if tiles_clicked and not tiles_clicked[0].final:
            # Deselect last clicked tile
            if self.selected_tile:
                self.selected_tile.selected = False

            # Select new tile
            self.selected_tile = tiles_clicked[0]
            self.selected_tile.selected = True

    def _create_board(self):
        """Choose random sudoku and create board along with solution"""
        with open("sudoku.csv", "r") as csv_file:
            sudokus = pd.read_csv("sudoku.csv")
            board_data = sudokus.sample()
            board_str = board_data.iloc[0, 0]
            solution_str = board_data.iloc[0, 1]

        return self._parse_board(board_str), self._parse_board(solution_str)

    def _parse_board(self, board_str):
        """Parse a string to sudoku board"""
        # print(board_str)
        board = [[0 for j in range(9)] for i in range(9)]
        counter = 0
        for i, row in enumerate(board):
            for j, element in enumerate(row):
                board[i][j] = int(board_str[counter])
                counter += 1

        return board

    def _create_tiles(self):
        """Create and place sudoku tiles"""
        for i in range(9):
            for j in range(9):
                x_coord = j * self.settings.tile_size
                y_coord = i * self.settings.tile_size
                number = self.board[i][j]
                tile = Tile(self, (i, j), number)

                if number:
                    tile.final = True

                tile.prep_number()
                self.tiles.add(tile)

    def _draw_separation_lines(self):
        """Draw the board lines that separate tiles"""
        for i in range(9):
            width = 4 if i % 3 == 0 else 1
            pygame.draw.line(
                self.screen,
                (0, 0, 0),
                (self.settings.tile_size*i, 0),
                (self.settings.tile_size*i, self.settings.screen_size),
                width=width
            )
            pygame.draw.line(
                self.screen,
                (0, 0, 0),
                (0, self.settings.tile_size*i),
                (self.settings.screen_size, self.settings.tile_size*i),
                width=width
            )

    def update_screen(self):
        """Draw Sudoku board"""
        self.screen.fill(self.settings.bg_color)

        # Draw tiles
        for tile in self.tiles.sprites():
            tile.draw_tile()

        # Draw board lines
        self._draw_separation_lines()

        # Switch to newest screen
        pygame.display.flip()

if __name__ == '__main__':
    sv = SudokuVisualizer()
    sv.run_visualizer()


import math
import subprocess
#mod = 100011010
#mod = int(pow(2,8)+pow(2,4)+pow(2,3)+pow(2,1)+pow(2,0))

def basic(b,mod):
    ult = int(math.log2(mod))
    #print("El ultimo es "+str(ult))
    flag = False
    b = b << 1
    #print(getString(b))
    if (b&(1<<ult)):
        #print("Esta prendido el ultimo")
        b = b ^ (1<<ult)
        #print(getString(b))
        #print("Despues del XOR nos da "+ str(b))
        b = b^(mod^(1<<ult))
    return b

def mul(a,b,mod):
    tam = int(math.log2(a))+1
    i = 0
    res = 0
    while (i < tam):
        if(a &(1<<i)):
            aux = b
            for j in range(i):
                aux = basic(aux,mod)
            res = res ^ aux
        i= i+1
    return res

def getPoly(s):
    tam = int(len(s))
    res = ""
    for i in range(tam):
        if(s[i] == '1'):
            pos = tam-i-1
            if(pos == 1):
                res+=("x+")
            elif(pos == 0):
                res+="1+"
            else:
                res += ("x^" + str(tam-i-1) + "+")
    return res[0:len(res)-1]

def getNumber(s):
    tam = int(len(s))
    ans = 0
    for i in range(tam):
        if(s[i] == '1'):
            pos = tam-i-1
            ans += pow(2,pos)
    return ans

def getString(a):
    tam = int(math.log2(a))+1
    ans = ""
    for i in range(tam):
        if(a & (1<<i)):
            ans+="1"
        else:
            ans+="0"
    return ans[::-1]

def binPow(a,b,mod):
	res = 1
	while(b > 0):
		if(b & 1):
			res = mul(res,a,mod)
		a = mul(a,a,mod)
		b >>= 1
	return res

def getMultiplicativeInverse(a):
    a = int("0x"+a,0)
    mod = int(pow(2,8)+pow(2,4)+pow(2,3)+pow(2,1)+pow(2,0))
    res = binPow(a,254,mod)
    return hex(res).split('x')[1]

def getSboxValue(b,c):
	res = ""
	for i in range(8):
		res += str(int(b[i]) ^ int(b[(i+4)%8]) ^ int(b[(i+5)%8]) ^ int(b[(i+6)%8]) ^ int(b[(i+7)%8]) ^ int(c[i]))
	return res

def individualValue(a):
	b = getMultiplicativeInverse(a)
	b = int("0x"+b,0) #Ya es entero
	b = getString(b)# Sacamos la cadena binaria
	b = b[::-1]# Volteamos esa cadena
	# Llenamos de ceros si hacen falta
	while(len(b) < 8):
		b+='0'
	c = "11000110"# Definida por default
	ans = getSboxValue(b,c)
	ans = ans[::-1]# Volteamos lo obtenido
	ans = getNumber(ans)# Obtenemos el entero de la cadena binaria
	#return str(ans)
	ans = hex(ans)# Obtenemos el hexa del entero
	return str(ans).split('x')[1]
	#print("Answer: " + str(ans).split('x')[1])

def generateSbox():
	alpha = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']
	for i in range(len(alpha)):
		for j in range(len(alpha)):
			if(i == 0 and j == 0):
				print(str(hex(99)).split('x')[1],end = " ")
				#print("99",end = " ")
			else:
				print(individualValue(alpha[i]+alpha[j]), end = " ")
		print("")

def clearTerminal():
    subprocess.call("cls", shell=True)

def main():
	clearTerminal()
	opc = int(input("1.- Multiplication in a binary field\n2.- Get the polynomial representation \n3.- Get the S-box value \nInput:"))
	clearTerminal()
	if(opc == 1):
		print("All the values should be introduced using a binary representation")
		mod = input("Introduce the irreducible polynomial:")
		mod = int(getNumber(mod))
		a = input("Introduce number A:")
		a = int(getNumber(a))
		b = input("Introduce number B:")
		b = int(getNumber(b))
		ans = mul(a,b,mod)
		ans = getString(ans)
		print("Answer: " + str(ans))
	elif(opc == 2):
		print("All the values should be introduced using a binary representation")
		a = input("Introduce number A:")
		ans = getPoly(a)
		print("Answer: "+str(ans))
	else:
		generateSbox()

def prueba():
	a = input()
	print(getMultiplicativeInverse(a))

#prueba()
main()


from tkinter import *
import database as db

def win_receiver(ws_status):
    def okReceptor():
        if ws_status == 1:
            idrec = entryval1.get()
            nomrec = entryval2.get()
            starec = entryval3.get()

            recnewid = []
            datarec = (idrec, nomrec, starec)

            recserie = int(idrec[4:7])
            recserie += 1
            recserie = "BEN-" + str(recserie).zfill(3)
            recnewid.append(recserie)
            recnewid = tuple(recnewid)

            db.insert_receptor(datarec)
            db.update_company_receptor(recnewid)

        riw.destroy()

    def noReceptor():
        riw.destroy()

    def closeDisable():
        pass

    riw = Toplevel()
    riw.transient()
    riw.grab_set()
    riw.title("Rekening - Información del Receptor")
    riw.geometry("480x165")
    riw.resizable(False, False)
    riwicon = PhotoImage(file="icon.png")
    riw.iconphoto(True, riwicon)
    riw.protocol("WM_DELETE_WINDOW", closeDisable)

    # Receptor Information - Variable Declaration

    entryval1 = StringVar()
    entryval2 = StringVar()
    entryval3 = IntVar()

    dc = db.verify_company()

    entryval1.set(dc[0][2])
    entryval3.set(1)

    # Receptor Information - LabelFrames, Labels, Entries & Checkbuttons

    riwlf = LabelFrame(riw, text=" Información General ",
                       width=458, height=95)
    riwlf.place(x=10, y=5)

    Label(riw, text="Id Receptor").place(x=17, y=30)
    Entry(riw, width=8, textvariable=entryval1,
          state=DISABLED).place(x=90, y=32)

    Label(riw, text="Nombre").place(x=17, y=60)
    Entry(riw, textvariable=entryval2, width=60).place(x=90, y=62)

    Checkbutton(riw, text="Activo", variable=entryval3,
                onvalue=1, offvalue=0).place(x=394, y=32)

    # Receptor Information - Buttons

    Button(riw, text="Aceptar", width=15,
           command=okReceptor).place(x=70, y=120)
    Button(riw, text="Cancelar", width=15,
           command=noReceptor).place(x=300, y=120)

    # Receptor Information - Window Loop
    riw.mainloop()


import csv
from tkinter.filedialog import *
from tkinter import *
from tkinter import messagebox as mb
import numpy as N

def open_file():
    try:
        file = askopenfile(mode='r', filetypes=[('CSV files', '*.csv')])
        pars = csv.DictReader(file, delimiter=';')
        message = []
        parser = 'idps'
        signature = []
        for row in pars:
            message.append(row['message'])
        for line in message:
            if parser in line:
                signature_list = line.split('|')
                signature.extend(signature_list[5:6])
        uniq = list(set(signature))
        array_d = {}.fromkeys(uniq, 0)
        for a in signature:
            array_d[a] += 1
        cont = list(array_d.values())
        columns = ['Signature', 'count']
        with open('result.csv', 'w', newline='', encoding='utf-8') as file_obj:
            write = csv.writer(file_obj)
            write.writerow(columns)
            write.writerows(zip(uniq, cont))
        mb.showinfo(title='Информация', message='Готово')
    except:
        pass

def result_signature():
    try:
        sign = []
        with open('result.csv') as file:
            read = csv.DictReader(file, delimiter=',')
            for row in read:
                sign.append(row['Signature'])
        str(sign)
        root = Tk()
        root.resizable(width=False, height=False)
        root.geometry('800x500')
        root.title('Сигнатуры')
        root['bg'] = '#ccc'
        field = Text(root, width=80, height=50, wrap=WORD,
                     font='Arial 10')
        field.insert(0.0, f'\n'.join(sign))
        field.pack()
        root.mainloop()
    except FileNotFoundError:
        mb.showerror(title='Ошибка', message='Файл не найден')

def events():
    try:
        all_events = []
        old_events = []
        with open('all_sig.txt') as file:
            for line in file:
                rep = line.replace('\n', '')
                all_events.append(rep)
        with open('result.csv') as file_obj:
            reader = csv.DictReader(file_obj, delimiter=',')
            for row in reader:
                old_events.append(row['Signature'])
        result = list(set(old_events) - set(all_events))
        result.sort()
        counter = len(result)
        if len(result) == 0:
            mb.showinfo(title='Внимание', message='Новых сигнатур нет')
        else:
            root = Tk()
            root.resizable(width=False, height=False)
            root.geometry('800x500')
            root.title('Новых сигнатур  ' + str(counter))
            root['bg'] = '#ccc'
            field = Text(root, width=80, height=50, wrap=WORD,
                         font='Arial 10')
            field.insert(0.0, f'\n'.join(result))
            field.pack()
            root.mainloop()
            with open('all_sig.txt', 'a') as file:
                file.write('\n'.join(result))
    except FileNotFoundError:
        mb.showerror(title='Ошибка', message='Файл не найден')

def src_ip():
    def get():
        signature = name.get()
        file = askopenfile(mode='r', filetypes=[('CSV files', '*.csv')])
        pars = csv.DictReader(file, delimiter=';')
        message = []
        sor_ip = []
        print(signature)
        for row in pars:
            message.append(row['message'])
        for line in message:
            if signature in line:
                src_ip = line.split('=')
                sor_ip.extend(src_ip[10:11])
        res = N.array(sor_ip)
        unque_res = N.unique(res)
        res = f'\n'.join(unque_res)
        syka = res.replace('spt', '')
        root = Tk()
        root.resizable(width=False, height=False)
        root.geometry('800x500')
        root.title('SRC IP')
        root['bg'] = '#ccc'
        field = Text(root, width=80, height=50, wrap=WORD,
                     font='Arial 10')
        field.insert(0.0, syka)
        field.pack()
        root.mainloop()

    roof = Tk()
    roof.title("Поиск SRC ip")

    name = StringVar()

    name_label = Label(roof, text="Введите сигнатуру:")

    name_label.grid(row=0, column=0, sticky="w")

    name_entry = Entry(textvariable=name)
    name_entry.grid(row=0, column=1, padx=5, pady=5)
    message_button = Button(roof, text="Click Me", command=get)
    message_button.grid(row=2, column=1, padx=5, pady=5, sticky="e")
    roof.mainloop()

def gui():
    root = Tk()
    root.geometry("250x150+300+300")
    root.title('Парсер логов')
    btn = Button(root, text='Спарсить файл', command=open_file)
    btn_info = Button(root, text='Показать сигнатуры', command=result_signature)
    new_sign = Button(root, text='Найти новые сигнатуры', command=events)
    srt_butn = Button(root, text='Найти src.ip', command=src_ip)
    srt_butn.grid(column=1, row=1)
    btn_info.grid(column=0, row=2)
    btn.grid(column=0, row=1)
    new_sign.grid(column=0, row=3)

    root.mainloop()

gui()


from typing import List, Optional, Callable, Tuple, Any, Dict
import numpy as np
from dataclasses import dataclass, field
import math
from om.algorithms.crystallography import TypePeakList, Peakfinder8PeakDetection

## Some abstractions to call peakfinder8 in Python

def build_pixel_map(row: int, col: int, y0: int, x0: int) -> Dict[str, int]:
    """
    Calculate radius pixels map for a given center x0,y0.

    Parameters
    ----------
    row: int
        Number of rows of data.
    col: int
        Number of columns of data.
    y0:
        Radial center position in y axis (row).
    x0:
        Radial center position in x axis (column).

    Returns
    ----------
    radius_pixel_map: Dict
        "radius": radius pixel map in realtion to the give center. It has same size of data given by row and col.
    """
    radius_pixel_map = np.ones((row, col)).astype(int)
    for idy, i in enumerate(radius_pixel_map):
        for idx, j in enumerate(i):
            radius_pixel_map[idy, idx] = int(
                math.sqrt((idx - x0) ** 2 + (idy - y0) ** 2)
            )
    return dict(radius=radius_pixel_map)

@dataclass
class PF8Info:
    max_num_peaks: int
    pf8_detector_info: dict
    adc_threshold: float
    minimum_snr: int
    min_pixel_count: int
    max_pixel_count: int
    local_bg_radius: int
    min_res: float
    max_res: float
    _bad_pixel_map: np.array
    _pixelmaps: np.array = field(init=False)

    def __post_init__(self):

        self._pixelmaps = build_pixel_map(
            (self._bad_pixel_map).shape[0],
            (self._bad_pixel_map.shape[1]),
            int((self._bad_pixel_map).shape[0] / 2),
            int((self._bad_pixel_map).shape[1] / 2),
        )

    def modify_mask(self, mask):
        self._bad_pixel_map = mask

    def modify_radius(self, center_x, center_y):
        self._pixelmaps = build_pixel_map(
            (self._bad_pixel_map).shape[0],
            (self._bad_pixel_map.shape[1]),
            center_y,
            center_x,
        )

class PF8:
    def __init__(self, info):
        assert isinstance(
            info, PF8Info
        ), f"Info object expected type PF8Info, found {type(info)}."
        self.pf8_param = info

    def get_peaks_pf8(self, data):
        detector_layout = self.pf8_param.pf8_detector_info

        peak_detection = Peakfinder8PeakDetection(
            self.pf8_param.max_num_peaks,
            self.pf8_param.pf8_detector_info["asic_nx"],
            self.pf8_param.pf8_detector_info["asic_ny"],
            self.pf8_param.pf8_detector_info["nasics_x"],
            self.pf8_param.pf8_detector_info["nasics_y"],
            self.pf8_param.adc_threshold,
            self.pf8_param.minimum_snr,
            self.pf8_param.min_pixel_count,
            self.pf8_param.max_pixel_count,
            self.pf8_param.local_bg_radius,
            self.pf8_param.min_res,
            self.pf8_param.max_res,
            self.pf8_param._bad_pixel_map.astype(np.float32),
            (self.pf8_param._pixelmaps["radius"]).astype(np.float32),
        )
        peaks_list = peak_detection.find_peaks(data)
        return peaks_list


# @copy by sobhan siamak

import numpy as np
import pandas as pd
import  matplotlib.pyplot as plt
import time
from datetime import datetime
import networkx as nx
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report
# from sklearn import cross_validation
from sklearn.model_selection import cross_val_score,KFold, cross_validate
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_curve
# import scikitplot as skplt

start_time = datetime.now()

db = pd.read_csv("ppi_dmelanogaster.csv")
dbmain = pd.read_csv("comppi--compartments--tax_dmelanogaster_loc_all.txt", sep='\t')
labels = pd.read_csv("Labels.csv")
labels = labels[['locus','essentiality status']]
print(labels.head())

# la1 = pd.DataFrame(la)
# lb1 = pd.DataFrame(lb)
# la1.to_csv("goa.csv" , index=False)
# lb1.to_csv("gob.csv", index=False)
goa = dbmain.iloc[0:,3]
gob = dbmain.iloc[0:,11]

la = [x.split("|") for x in goa]
lb = [x.split("|") for x in gob]

alpha = 1 #coif of gene ontology
beta = 1 #coif of nieghborhood
gama = 0.001 #coif of score

print("la is:", la[0])
# print(goa)
print("lb is :", lb[0])
intersect = np.intersect1d(la[0],lb[0])
print(intersect)

go = []
for i in range(len(la)):
  go.append(len(np.intersect1d(la[i], lb[i]))/ len(la[i]+lb[i]))

######Change weigth #1

print(db.head())
db['go'] = go
db['Interaction Score'] = gama*db['Interaction Score'] + alpha*db['go']
db = db.drop(['go'], axis=1)
print(db.head())

db2 = np.array(db)
Pra = db.iloc[1:,0]
Prb = db.iloc[1:,1]
Sc = db.iloc[1:,2]
prota = db2[0:,0]
protb = db2[0:,1]
score = db2[0:,2]
Pa = pd.read_csv("ProtA.tab", sep='\t')
Pb = pd.read_csv("ProtB.tab", sep='\t')
frames =[Pa,Pb]
proteins = (pd.concat(frames))
proteins = proteins.drop_duplicates()
print(proteins.head())

#Labeling Dataset
prlabels = []
prot = proteins.iloc[:,1]

for i in prot:
    if(sum(labels['locus'].isin([i])) == 0):
        prlabels.append(['unknown'])
        continue
    temp = labels[labels['locus'].isin([i])]
    lbl = list(temp['essentiality status'])
    prlabels.append(lbl)

for i in range(len(prlabels)):
    if prlabels[i] == ['NE,NE']:
        prlabels[i] = ['NE']
    if prlabels[i] == ['E,NE']:
        prlabels[i] = ['E']
    if prlabels[i] == ['NE,E']:
        prlabels[i] = ['E']
    if prlabels[i] == ['E,E']:
        prlabels[i] = ['E']
    if prlabels[i] == []:
        prlabels[i] = ['unknown']

print(prlabels)
print(len(prlabels))
proteins['Labels'] = np.squeeze(prlabels)
print(proteins.head())
FProteins = proteins.drop('To', axis=1)
FProteins = FProteins.rename(columns={"From": "Proteins"})
FProteins = FProteins.drop_duplicates()
print(FProteins.head())
print(FProteins)
fpcsv = pd.DataFrame(FProteins)
fpcsv.to_csv("FPR.csv", index=False)

# unknown = sum(proteins['Labels'].isin(['unknown']))
# essential = sum(proteins['Labels'].isin(['E']))
# nessential = sum(proteins['Labels'].isin(['NE']))

unknown = sum(FProteins['Labels'].isin(['unknown']))
essential = sum(FProteins['Labels'].isin(['E']))
nessential = sum(FProteins['Labels'].isin(['NE']))

print("the number of unknown of proteins are:", unknown)
print("the number of essential of proteins are:", essential)
print("the number of not essential of proteins are:", nessential)

#Creation Graph
G2 = nx.from_pandas_edgelist(db, "Interactor A", "Interactor B", ['Interaction Score'], create_using= nx.Graph())
print(G2.nodes())
print(len(G2.nodes()))

nodes = list(G2.nodes())
nodelabels = []
for i in nodes:
    tmp = FProteins[FProteins['Proteins'].isin([i])]
    lbls = list(tmp['Labels'])
    nodelabels.append(lbls)

print("length nodelabels is:", len(nodelabels))
print(G2.nodes())
print(len(G2.nodes()))
Fnodelabels = []
for i in range(len(nodelabels)):
    if (nodelabels[i] == ['unknown']):
        G2.remove_node(nodes[i])
    else:
        Fnodelabels.append(nodelabels[i])
print(G2.nodes())

FNlabels =[]
for i in Fnodelabels:
    if i == ['NE']:
        FNlabels.append(0)
    else:FNlabels.append(1)
print(FNlabels)
print(len(FNlabels))

print("length Fnodelabels is:", len(Fnodelabels))
print("length G2.nodes is:", len(G2.nodes()))
Fnodes = G2.nodes()

######Centrality
central1 = nx.eigenvector_centrality(G2,weight = 'Interaction Score', max_iter=1000)
central1 = list(central1.values())
# central11 = pd.DataFrame(central1)
# central11.to_csv("central1.csv", index=False)
print(central1)
central2 = nx.degree_centrality(G2)
central2 = list(central2.values())
# central22 = pd.DataFrame(central2)
# central22.to_csv("central2.csv", index=False)
print(central2)
# central2 = nx.degree_pearson_correlation_coefficient(G2,x='P26802', y='Q9W5A9')
# print("pearson corralation is:", central2)
# print(type(central1))
#####High Time Complexity
# central3 = nx.closeness_centrality(G2)
# central3 = list(central3.values())
# central33 = pd.DataFrame(central3)
# central33.to_csv("central3.csv", index=False)
# print(central3)

#####High Time Complexity
# central4 = nx.betweenness_centrality(G2)
# central4 = list(central4.values())
# central44 = pd.DataFrame(central4)
# central44.to_csv("central4.csv", index=False)
# print(central4)

#####High Time Complexity
# central5 = nx.subgraph_centrality(G2)
# central5 = list(central5.values())
# central55 = pd.DataFrame(central5)
# central55.to_csv("central5.csv", index=False)
# print(central5)

###########Classifiers
# DecisionTreeClassifier(max_depth=5),\
# RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),

# central7 = nx.clustering(G2)
# print("clustering is :", central7)

print(len(Fnodes))
print(len(central1))
print(len(Fnodelabels))
FinalP = pd.DataFrame()
FinalP['Proteins'] = Fnodes
FinalP['C1'] = central1
FinalP['C2'] = central2
c3 = pd.read_csv("central3.csv")
c4 = pd.read_csv("central4.csv")
c5 = pd.read_csv("central5.csv")
print(c3.head())
print(c4.head())
print(c5.head())
FinalP['C3'] = c3
FinalP['C4'] = c4
FinalP['C5'] = c5
#labeling

FinalP['Labels'] = FNlabels
print(FinalP.head())
FinalP.to_csv("Finalp.csv", index=False)

#########################################################################
#Classification

FPro = pd.read_csv("Finalp.csv", header=None)
print(FPro.head())
x = FPro.iloc[1:,1:-1]
y = FPro.iloc[1:,-1]
target_names = ['0', '1']
# print(x.iloc[:,0])
# print(y)
# print(len(y))
X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.20)
# clf = RandomForestClassifier(n_estimators=1000, max_depth=4,random_state=5,class_weight ='imbalanced')
# clf.fit(X_train, y_train)
# result = clf.predict(X_test)
# print(classification_report(y_test, result,target_names=target_names))

clf = KNeighborsClassifier(n_neighbors=5)
clf.fit(X_train, y_train)
result2 = clf.predict(X_test)
print(classification_report(y_test, result2, target_names=target_names))

clf1 = SVC(gamma=2, C=1)
# clf1 = MLPClassifier(alpha=1, max_iter=1000)
# clf1 = GaussianNB()
clf1.fit(X_train, y_train)
result3 = clf1.predict(X_test)
print(classification_report(y_test, result3, target_names=target_names))

clf2 = LogisticRegression()
clf2.fit(X_train,y_train)
result4 = clf2.predict(X_test)
print(classification_report(y_test, result4, target_names=target_names))

clf4 = MLPClassifier(alpha=0.1, max_iter=1000)
clf4.fit(X_train,y_train)
result5 = clf4.predict(X_test)
print(classification_report(y_test, result5, target_names=target_names))

clf5 = GaussianNB()
clf5.fit(X_train,y_train)
result6 = clf5.predict(X_test)
print(classification_report(y_test, result6, target_names=target_names))

# score = cross_val_score(clf, x, y, cv=5)
# print(score)
######KNN
scoring = ['precision_macro', 'recall_macro', 'accuracy']
scores2 = cross_validate(clf, x, y, cv=5, scoring=scoring)
print("recall for 5-fold cross validation is:")
print(scores2['test_recall_macro'])
yknn1 = scores2['test_recall_macro']
print("precision for 5-fold cross validation is:")
print(scores2['test_precision_macro'])
yknn2 = scores2['test_precision_macro']
print("accuracy for 5-fold cross validation is:")
print(scores2['test_accuracy'])
yknn3 = scores2['test_accuracy']

print("++++++++++++++++++++++++++++++++++++++++++")
##### Gaussian Naive Bayse
scoring = ['precision_macro', 'recall_macro', 'accuracy']
scores3 = cross_validate(clf5, x, y, cv=5, scoring=scoring)
print("recall for 5-fold cross validation in GNB is:")
print(scores3['test_recall_macro'])
ygnb1 = scores3['test_recall_macro']
print("precision for 5-fold cross validation in GNB is:")
print(scores3['test_precision_macro'])
ygnb2 = scores3['test_precision_macro']
print("accuracy for 5-fold cross validationin GNB is:")
print(scores3['test_accuracy'])
ygnb3 = scores3['test_accuracy']

#Plot
#5-Fold Curve
xfold = [1,2,3,4,5]
plt.plot(xfold, yknn1, label='Recall')
plt.plot(xfold, yknn2, label='Precision')
plt.plot(xfold, yknn3, label='Accuracy')
plt.xlabel('5-Fold')
plt.ylabel('Measurment')
plt.title('KNN 5-Fold Curve')
plt.legend(loc='best')
plt.show()

xfold = [1,2,3,4,5]
plt.plot(xfold, ygnb1, label='Recall')
plt.plot(xfold, ygnb2, label='Precision')
plt.plot(xfold, ygnb3, label='Accuracy')
plt.xlabel('5-Fold')
plt.ylabel('Measurment')
plt.title(' Guassian Naive Bayse 5-Fold Curve')
plt.legend(loc='best')
plt.show()

#####ROC Curve
# fpr_knn_lm, tpr_knn_lm = roc_curve(y_test, result2)
# fpr_svc_lm, tpr_svc_lm = roc_curve(y_test, result3)
# fpr_lr_lm, tpr_lr_lm = roc_curve(y_test, result4)
#
# plt.figure(1)
# plt.plot([0, 1], [0, 1], 'k--')
# plt.plot(fpr_knn_lm, tpr_knn_lm, label='KNN')
# plt.plot(fpr_svc_lm, tpr_svc_lm, label='SVC')
# plt.xlabel('False positive rate')
# plt.ylabel('True positive rate')
# plt.title('ROC curve')
# plt.legend(loc='best')
# plt.show()

end_time = datetime.now()
print('Time for running this Code is: {}'.format(end_time - start_time))


"""
Write code to remove duplicates from an unsorted linked list

"""
from implementation import *

"""
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class SLinkedList:
    def __init__(self):
        self.head = None

    def pushToFront(self, data):
        newNode = Node(data)
        newNode.next = self.head
        self.head = newNode

    def popFromFront(self):
        if self.head == None:
            return None
        out = self.head
        self.head = out.next
        out.next = None
        return out

    def __len__(self):
        cur = self.head
        count = 0
        while cur:
            count += 1
            cur = cur.next
        return count

    def traverse(self):
        cur = self.head
        seen = []
        while cur:
            seen.append(str(cur.data))
            cur = cur.next
        return print("->".join(seen))

    def removeDups(self):
        if not self.head:
            return
        cur = self.head
        while cur.next:
            if cur.data == cur.next.data:
                cur.next = cur.next.next
            else:
                cur = cur.next
"""

def removeDups(l):
    if not l.head:
        return l
    cur = l.head
    while cur.next:
        if cur.data == cur.next.data:
            cur.next = cur.next.next
        else:
            cur = cur.next
    return l

# Where n is the size of the linked list
# Time  : O(n) - traverse the list and do O(1) node removal in place
# Space : O(1) - no additional data structres, removing dups in place

# Testing

l = SLinkedList() # a->a->c->c
l.pushToFront('c')
l.pushToFront('c')
l.pushToFront('b')
l.popFromFront()
l.pushToFront('a')
l.pushToFront('a')
l.traverse()
print(len(l))

l2 = SLinkedList()  # a->b->c
l2.pushToFront('c')
l2.pushToFront('b')
l2.pushToFront('a')

l3 = SLinkedList()  # c
l3.pushToFront('c')

l4 = SLinkedList()  # b->b
l4.pushToFront('b')
l4.pushToFront('b')

print("---- Remove Dups-----")
removeDups(l).traverse()  # a->c
removeDups(l2).traverse()  # a->b->c
removeDups(l3).traverse()  # c
removeDups(l4).traverse()  # b


# 거스름돈
# https://www.acmicpc.net/problem/5585

moneys = [1, 5, 10, 50, 100, 500]

n = int(input())

cur = 1000 - n
cnt = 0
while cur > 0:
    money = moneys.pop()
    cnt += (cur//money)
    cur %= money
print(cnt)


import tkinter as tk
import tkinter.ttk as ttk
root = tk.Tk()
root.geometry('300x120')

def calcular():
        try:
                if n.get() == "pulgadas":
                        resultado = round(int(p.get()) / 2.54,2)
                elif n.get() == "metros":
                        resultado = round(int(p.get()) / 100,2)
                else:
                        resultado = round(int(p.get()) / 100000,4)
                p.delete(first=0,last=1000)
                etiquetavalue.set("El resultado es " + str(resultado))
        except:
                etiquetavalue.set("Error de gravedad grave")

tk.Label(root, text="Escribe una cantidad de centímetros", fg = "black", font = "Helvetica 11").pack()
p = tk.Entry(root, width= 20)
p.pack()

n = ttk.Combobox(root, state="readonly", values=("pulgadas","metros", "kilómetros"))
n.set("pulgadas")
n.pack()

mibtn = ttk.Button(root, text = "Convertir", command=calcular)
mibtn.pack()

etiquetavalue = tk.StringVar()
etiqueta = ttk.Label(root,textvariable = etiquetavalue).pack()

root.mainloop()


#해야하는 것
#랜덤변수 중복없이 만들기
#

import random

def randomNum(): #중복없는 랜덤숫자 만들기 (배열로 추출 )
    result = []
    for i in range(3): #자릿수
        a = random.randint(0,9)
        while a in result :
            a = random.randint(0,9) #중복방
        result.append(a)
    return result
#단 두줄로 끝....
#pt = random.sample(range(1, 10),3)
#print(pt)

#게임 시작
print("Welcome To Baseball Game!")
print("Push the three number")

ranNum = randomNum() # 랜덤숫자 만듬
print("TEST:",ranNum) # 테스트용
s_ct = 0 #스트라이크 카운트
b_ct = 0 #볼 카운트

#반복입력하면서 중복방지와 카운 (배열로)
while(s_ct < 3):
    user_num = input("input : ")  #문자열로 추출
    #중복방지
    if(user_num[0] == user_num[1] == user_num[2]):
        print("Input the non-duplicated number")
        continue
    elif(user_num[0] == user_num[1]):
        print("Input the non-duplicated number")
        continue
    elif(user_num[0] == user_num[2]):
        print("Input the non-duplicated number")
        continue
    elif(user_num[1] == user_num[2]):
        print("Input the non-duplicated number")
        continue
    else:
        pass        #다른 예외 처리 필요 , try 사용해보자

    for i in range(0, 3):
        for j in range(0, 3):
            if(i == j and str(ranNum[i]) == user_num[j]):   # 문자열로 통일해서 비교
                s_ct += 1
            elif(i != j and str(ranNum[i]) == user_num[j]):
                b_ct += 1

    print(s_ct, "strike", b_ct,  "ball")
    if(s_ct == 3):
        print("Congratulation. Number is correct!")
        break
    s_ct = 0 #스트라이크 초기화
    b_ct = 0 #볼 초기화


import dash
from dash.dependencies import Input, Output
import dash_core_components as dcc
import dash_html_components as html
import plotly.graph_objs as go
from flask_sqlalchemy import SQLAlchemy
import numpy as np
import pandas as pd

TABLE_CLASSES = 'table table-hover table-sm'
GC_COLORS = {
    None: '#CCCCCC',
    'Adders': '#FFCC33',
    'Flames': '#AA77CC',
    'Maelstrom': '#FF5555',
}

app = dash.Dash()
app.server.config['SQLALCHEMY_DATABASE_URI'] = 'postgres:///gubal'
app.server.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
db = SQLAlchemy(app.server)

# Load Bootstrap
app.css.append_css({
    "external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css",
})
app.scripts.append_script({
    "external_url": "https://code.jquery.com/jquery-3.2.1.slim.min.js",
})
app.scripts.append_script({
    "external_url": "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js",
})
app.scripts.append_script({
    "external_url": "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js",
})

def build_table(df, **kwargs):
    return html.Table([
        html.Thead([
            html.Tr([html.Th(col) for col in df.columns]),
        ]),
        html.Tbody([
            html.Tr([
                html.Td([df.iloc[i][col]]) for col in df.columns
            ]) for i in range(len(df))
        ]),
    ], **kwargs)

def build_gender_chart(**kwargs):
    df = pd.read_sql('SELECT gender, COUNT(*) FROM characters GROUP BY gender ORDER BY gender DESC', db.engine, index_col='gender')
    return go.Pie(labels=df.index.tolist(), values=df['count'], **kwargs)

def build_race_chart(**kwargs):
    df = pd.read_sql('SELECT race, COUNT(*) FROM characters GROUP BY race ORDER BY race DESC', db.engine, index_col='race')
    return go.Pie(labels=df.index.tolist(), values=df['count'], **kwargs)

def build_race_clan_gender_chart(**kwargs):
    df = pd.read_sql('SELECT race, clan, gender, COUNT(*) FROM characters GROUP BY race, clan, gender ORDER BY race, clan, gender DESC', db.engine, index_col=['race', 'clan', 'gender'])

    # TODO: clean up this mess
    races = df.index.get_level_values('race').unique()
    series = [{"y": [], "text": []} for i in range(4)]
    for race in races:
        race_data = df.loc[race]
        for i, clan_and_gender in enumerate(race_data.index.values):
            series[i]["text"].append(" ".join(clan_and_gender))
            series[i]["y"].append(race_data.loc[clan_and_gender]['count'])
    return [go.Bar(x=races, **s, **kwargs) for s in series]

def build_level_breakdown(**kwargs):
    df = pd.read_sql('''
        SELECT
            CASE
                WHEN level = 1 THEN 1
                WHEN level > 1 AND level < 15 THEN 2
                WHEN level = 15 THEN 15
                WHEN level > 15 AND level < 30 THEN 16
                WHEN level = 30 THEN 30
                WHEN level > 30 AND level < 50 THEN 31
                WHEN level = 50 THEN 50
                WHEN level > 50 AND level < 60 THEN 51
                WHEN level = 60 THEN 60
                WHEN level > 60 AND level < 70 THEN 61
                WHEN level = 70 THEN 70
            END level_range,
            job,
            COUNT(*)
        FROM levels
        GROUP BY level_range, job
        ORDER BY job, level_range ASC
    ''', db.engine, index_col=['level_range', 'job'])
    ranges = list(df.index.get_level_values('level_range').unique())
    jobs = list(df.index.get_level_values('job').unique())
    return [go.Bar(
        x=jobs,
        y=df.loc[rng]['count'],
        name=rng,
    ) for rng in ranges]

def build_gc_chart(**kwargs):
    df = pd.read_sql('SELECT gc, COUNT(*) FROM characters GROUP BY gc ORDER BY gc ASC', db.engine, index_col=['gc'])
    gcs = df.index.tolist()
    colors = [GC_COLORS[gc] for gc in gcs]
    return go.Pie(
        labels=gcs,
        values=df['count'],
        marker=go.Marker(
            colors=colors,
            line=go.Line(color='#FFF', width=1),
        ),
        **kwargs,
    )

def build_gc_breakdown(**kwargs):
    df = pd.read_sql('SELECT gc, gc_rank, COUNT(*) FROM characters GROUP BY gc, gc_rank ORDER BY gc, gc_rank ASC', db.engine, index_col=['gc', 'gc_rank'])
    gcs = list(df.index.get_level_values('gc').unique().dropna())
    return [go.Bar(
        y=df.loc[gc]['count'],
        name=gc,
        marker=go.Marker(color=GC_COLORS[gc]),
        **kwargs,
    ) for gc in gcs]

def build_world_breakdown(**kwargs):
    df = pd.read_sql('SELECT world, COUNT(*) FROM characters GROUP BY world ORDER BY count DESC', db.engine, index_col=['world'])
    worlds = list(df.index.values)
    return [go.Bar(
        x=worlds,
        y=df['count'],
        **kwargs,
    )]

def build_title_table(**kwargs):
    df = pd.read_sql('SELECT title, COUNT(*) FROM characters INNER JOIN character_titles ON characters.title_id = character_titles.id GROUP BY title ORDER BY count DESC LIMIT 10', db.engine)
    return build_table(df, **kwargs)

def build_top_table(col, limit=10, **kwargs):
    df = pd.read_sql('SELECT {col}, COUNT(*) FROM characters GROUP BY {col} ORDER BY count DESC LIMIT {limit}'.format(col=col, limit=limit), db.engine)
    return build_table(df, **kwargs)

def build_layout():
    return html.Div([
        html.Div([
            dcc.Graph(
                id="gender-chart",
                figure=go.Figure(
                    data=[build_gender_chart(
                        textinfo='label+percent',
                        hole=0.5,
                        marker=go.Marker(
                            colors=['#00CCFF', '#FF0099'],
                            line=go.Line(color='#FFF', width=1),
                        ),
                    )],
                    layout=go.Layout(title="Gender"),
                ),
                className='col-sm-6',
            ),
            dcc.Graph(
                id="race-chart",
                figure=go.Figure(
                    data=[build_race_chart(
                        textinfo='label+percent',
                        hole=0.5,
                        marker=go.Marker(line=go.Line(color='#FFF', width=1)),
                    )],
                    layout=go.Layout(title="Race"),
                ),
                className='col-sm-6',
            ),
        ], className='row', style={'min-height': '500px'}),
        html.Div([
            dcc.Graph(
                id="race-clan-gender-chart",
                figure=go.Figure(
                    data=[*build_race_clan_gender_chart(
                        showlegend=False,
                        hoverinfo='y+text',
                        textposition='auto',
                    )],
                    layout=go.Layout(title="Breakdown", barmode='group'),
                ),
                className='col-sm-12',
            ),
        ], className='row', style={'min-height': '500px'}),
        html.Div([
            dcc.Graph(
                id="level-breakdown",
                figure=go.Figure(
                    data=[*build_level_breakdown(
                        # showlegend=False,
                        # hoverinfo='y+text',
                        # textposition='auto',
                    )],
                    layout=go.Layout(title="Levels", barmode='group'),
                ),
                className='col-sm-12',
            ),
        ], className='row', style={'min-height': '500px'}),
        html.Div([
            html.Div([
                dcc.Graph(
                    id="gc-graph",
                    figure=go.Figure(
                        data=[build_gc_chart()],
                        layout=go.Layout(title="Grand Companies"),
                    ),
                ),
            ], className='col-sm-4'),
            html.Div([
                dcc.Graph(
                    id="gc-breakdown",
                    figure=go.Figure(
                        data=[*build_gc_breakdown()],
                        layout=go.Layout(title="Grand Company Ranks"),
                    ),
                ),
            ], className='col-sm-8'),
        ], className='row'),
        html.Div([
            dcc.Graph(
                id="world-breakdown",
                figure=go.Figure(
                    data=[*build_world_breakdown()],
                    layout=go.Layout(title="Worlds"),
                ),
                className='col-sm-12',
            ),
        ], className='row', style={'min-height': '500px'}),
        html.Div([
            html.Div([
                html.H5("Top 10 Titles"),
                build_title_table(className=TABLE_CLASSES),
            ], className='col-sm-4'),
            html.Div([
                html.H5("Top 10 First Names"),
                build_top_table('first_name', className=TABLE_CLASSES),
            ], className='col-sm-4'),
            html.Div([
                html.H5("Top 10 Last Names"),
                build_top_table('last_name', className=TABLE_CLASSES),
            ], className='col-sm-4'),
        ], className='row'),
    ], className='container')

app.layout = build_layout

if __name__ == '__main__':
    app.run_server(debug=True)


# -*- coding: utf-8 -*-
"""
Created on Thu Jul 15 18:18:40 2021

@author: Hengheng Zhang

E-Mail: hengheng.zhang@kit.edu

Function：

"""
import requests
import json
import time
from datetime import datetime
import numpy as np
import pandas as pd
import os
DataOut = []
DateTimes = [datetime.now()]
Count = 0

while True:
    try:
        Channelr =requests.get('http://141.52.172.253/websites/ab/index.php/json/api/getchannels',timeout = 5)
        success = json.loads(Channelr.text)
        Channels=json.loads(Channelr.text)['channels']
        VariableNames = []
        valueids = ''
        for channel in Channels:
            if channel['app'] == 'wsserial':
                VariableNames.append(channel['measurementname'] +'('+channel['unitname'] +')')
                valueids = valueids + channel['valueid']+','
        valueids = valueids[:-1]

        Valuesr =requests.get('http://141.52.172.253/websites/ab/index.php/json/api/getvalues?valueids='+valueids,timeout = 5)
        Values=json.loads(Valuesr.text)['values']
        SenOut = []
        for values in Values:
            SenOut.append(values['value'])
        DateTimesingle =  datetime.strptime(Values[-1]['timestamp'], '%Y-%m-%d %H:%M:%S')
        if not DateTimesingle == DateTimes[-1]:
            DateTimes.append(DateTimesingle)
            DataOut.append(SenOut)
            Count = Count + 1
            print('system is Running')
        if Count == 360:
            DataOut = np.array(DataOut)
            DateTimes = DateTimes[1:]
            Datadf = pd.DataFrame(data = DataOut,index = DateTimes,columns = VariableNames)
            Datadf.index.name = 'DateTime'
            if not os.path.exists('./Data/'):
                os.makedirs('./Data/')
            SaveFileName = 'WS700_'+DateTimes[-1].strftime('%Y_%m_%d_%H_%M_%S')+'.txt'
            Datadf.to_csv('./Data/'+SaveFileName, sep='\t')
            print(str(len(DateTimes))+' recored has been save to file at'+datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

            DataOut = []
            DateTimes = [datetime.now()]
            Count = 0
    except requests.exceptions.RequestException as e:
        if len(DateTimes)>1:
            DataOut = np.array(DataOut)
            DateTimes = DateTimes[1:]
            Datadf = pd.DataFrame(data = DataOut,index = DateTimes,columns = VariableNames)
            Datadf.index.name = 'DateTime'
            if not os.path.exists('./Data/'):
                os.makedirs('./Data/')
            SaveFileName = 'WS700_'+DateTimes[-1].strftime('%Y_%m_%d_%H_%M_%S')+'.txt'
            Datadf.to_csv('./Data/'+SaveFileName, sep='\t')
            print(str(len(DateTimes))+' recored has been save to file at'+datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
            DataOut = []
            DateTimes = [datetime.now()]
            Count = 0
        print('cannot connect to serve')

      # DateTimes = datetime.strptime(value., '')


water = 400
milk = 540
coffee_beans = 120
cups = 9
money = 550

def machine_buy_option():
    """Choose one of three types of coffee that the coffee machine can make: espresso, latte, or cappuccino."""

    print()
    print("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:")
    choice = input()

    if choice == '1' or choice == 'espresso':
        espresso_supply_checker()

    elif choice == '2' or choice == 'latte':
        latte_supply_checker()

    elif choice == '3' or choice == 'cappuccino':
        cappuccino_supply_checker()

    elif choice == 'back':
        print()
    else:
        print()

def espresso_supply_checker():
    global water, milk, coffee_beans, cups, money

    if water < 250:
        print("Sorry, not enough water!\n")
    elif coffee_beans < 16:
        print("Sorry, not enough coffee beans\n")
    elif cups < 1:
        print("Sorry, not enough cups!\n")
    else:
        print("I have enough resources, making you a coffee!\n")
        water -= 250
        coffee_beans -= 16
        money += 4
        cups -= 1

def latte_supply_checker():
    global water, milk, coffee_beans, cups, money

    if water < 350:
        print("Sorry, not enough water!\n")
    elif milk < 75:
        print("Sorry, not enough milk!\n")
    elif coffee_beans < 20:
        print("Sorry, not enough coffee beans\n")
    elif cups < 1:
        print("Sorry, not enough cups!\n")
    else:
        print("I have enough resources, making you a coffee!\n")
        water -= 350
        milk -= 75
        coffee_beans -= 20
        cups -= 1
        money += 7

def cappuccino_supply_checker():
    global water, milk, coffee_beans, cups, money

    if water < 200:
        print("Sorry, not enough water!\n")
        return
    elif milk < 100:
        print("Sorry, not enough milk!\n")
    elif coffee_beans < 12:
        print("Sorry, not enough coffee beans\n")
    elif cups < 1:
        print("Sorry, not enough cups!\n")
    else:
        print("I have enough resources, making you a coffee!\n")
        water -= 200
        milk -= 100
        coffee_beans -= 12
        cups -= 1
        money += 6

def machine_fill_option():
    """ Asking user how much water, milk, coffee and how many disposable cups they want to add into the coffee machine. """
    global water, milk, coffee_beans, cups

    print("\nWrite how many ml of water do you want to add:")
    water += int(input())
    print("Write how many ml of milk do you want to add:")
    milk += int(input())
    print("Write how many grams of coffee beans do you want to add:")
    coffee_beans += int(input())
    print("Write how many disposable cups of coffee do you want to add:")
    cups += int(input())
    print()

    # coffee_machine_stats()

def machine_take_funds():
    """Give -->#ALL<-- the money that it earned from selling coffee."""
    global money
    print(f"\nI gave you ${money}")
    money -= money
    print()
    # coffee_machine_stats()

def coffee_machine_stats():
    """Displays machine stats"""
    global water, milk, coffee_beans, cups, money
    print()
    print("The coffee machine has:")
    if money == 0:
        print(f"{water} of water\n{milk} of milk\n{coffee_beans} of coffee beans\n{cups} of disposable cups\n{money} of money")
    else:
        print(f"{water} of water\n{milk} of milk\n{coffee_beans} of coffee beans\n{cups} of disposable cups\n${money} of money")

    print()

def start_here():
    """Initial starting point, a kind of main menu"""
    # coffee_machine_stats()

    print("Write action (buy, fill, take, remaining, exit):")
    user_choice = input()

    if user_choice == 'buy':
        machine_buy_option()
    elif user_choice == 'fill':
        machine_fill_option()
    elif user_choice == 'take':
        machine_take_funds()
    elif user_choice == 'remaining':
        coffee_machine_stats()
    elif user_choice == 'exit':
        global exit_time
        exit_time = 'gremlins'
    else:
        print("Invalid input, try again.")
        print()

exit_time = 'unicorns'

while exit_time is 'unicorns':
    start_here()


import os
import requests

from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.select import Select

from selenium.webdriver.chrome.options import Options
#https://stackoverflow.com/questions/16180428/can-selenium-webdriver-open-browser-windows-silently-in-background

from PBL import application

class Controller:
    def __init__(self):
        self.imagesFolder = os.path.join(application.resourcesFolder, 'images')#PBL/Resources/images
        self.createDriver()

    def createDriver(self):
        #self.driver = webdriver.Chrome(os.path.join(self.resourcesFolder,'chromedriver'))
        self.driver = webdriver.Chrome(ChromeDriverManager().install())

    def closeDriver(self):
         self.driver.close()

    def makeImagesFolder(self):
        if not os.path.isdir(self.imagesFolder):
            os.makedirs(self.imagesFolder)

    def getImage(self,url):
        self.driver.get(url)
        xpath2 = """//li[@class='image item itemNo0 maintain-height selected']//img"""
        xpath = """//li[@class='a-spacing-small item imageThumbnail a-declarative']//img"""
        WebDriverWait(self.driver,10).until(EC.presence_of_element_located(
            (By.XPATH, xpath2)))
        img = self.driver.find_elements_by_xpath(xpath2)[0]
        print(img)
        src = img.get_attribute('src')
        return src

    def download(self,url,productName):
        self.makeImagesFolder()
        response = requests.get(url, stream=True)
        filename = os.path.join(self.imagesFolder, productName+'.png')
        progress = response.iter_content(1024)
        with open(filename, "wb") as f:
            for data in progress:
                # write data read to the file
                f.write(data)

    def getItemPrice(self):
        price_xpath = "//*[@id='priceblock_ourprice']"
        item_price = self.driver.find_element_by_xpath(price_xpath).text
        #item starts with currency symbol $,¥,...
        item_price = item_price[1:]
        print(item_price)
        return item_price

    def getQuantities(self):
        # Click on one time purchase box
        one_time_purchase_div_xpath = "//*[@id='newAccordionRow']"
        one_time_purchase_alternate_xpath = "//*[@id='oneTimeBuyBox']"
        dropdown_menu = None
        try:
            self.naviguate(one_time_purchase_div_xpath, one_time_purchase_alternate_xpath)
        except TimeoutException:
            try:
                one_time_purchase_button = self.driver.find_element_by_id("oneTimeBuyBox").click()
            except:
                #Sometimes there are no boxes to click, the menu is already visible
                quantity_dropdown_menu_xpath = "//*[@id='quantity']"
                dropdown_menu = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                    (By.XPATH, quantity_dropdown_menu_xpath)))

        if not dropdown_menu:
            # Select quantity from dropdown menu
            quantity_dropdown_menu_xpath = "//*[@id='quantity']"
            dropdown_menu = WebDriverWait(self.driver, 5).until(EC.presence_of_element_located(
                (By.XPATH, quantity_dropdown_menu_xpath)))

        options_element = [x for x in dropdown_menu.find_elements_by_tag_name("option")]
        options = []
        for element in options_element:
            options.append(element.get_attribute("value"))

        return options

    def naviguate(self,xpath,alternative_xpath=None):
        try:
            WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                (By.XPATH, xpath)))
            self.driver.find_element_by_xpath(xpath).click()
        except TimeoutException:
            WebDriverWait(self.driver, 10).until(EC.presence_of_element_located(
                (By.XPATH, xpath)))
            self.driver.find_element_by_xpath(alternative_xpath).click()

# if __name__ == "__main__":
#     c = Controller()
#     url = "https://www.amazon.co.jp/%E5%92%8C%E5%85%89%E5%A0%82-FQ4-%E3%81%AF%E3%81%98%E3%82%81%E3%81%A6%E3%81%AE%E9%9B%A2%E4%B9%B3%E9%A3%9F-%E8%A3%8F%E3%81%94%E3%81%97%E3%81%8A%E3%81%95%E3%81%8B%E3%81%AA-2-6g%C3%976%E5%80%8B/dp/B0052VL6RI/ref=sr_1_12?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&dchild=1&keywords=baby+food&qid=1592376143&sr=8-12"
#     c.getImage(url)
#
#     c.closeDriver()


#tutorial/03-run-hello.py
from azureml.core import Workspace, Experiment, Environment, ScriptRunConfig

ws = Workspace.from_config()
experiment = Experiment(workspace=ws, name='ml-workspace')

config = ScriptRunConfig(source_directory='./motion-sense-har', script='hello.py', compute_target='cpu-cluster')

run = experiment.submit(config)
aml_url = run.get_portal_url()
print(aml_url)


import  os , csv , io
from  Customer import *

class Customers():

    def __init__(self):
        self.customers = self.__extract_customers_records()

    def __extract_customers_records(self):
        path = input("Type your book's file . Type any other key for default file: ")
        if (os.path.exists(path))==False:
            path = os.path.join(os.path.dirname(__file__),r'library-books.csv')
            print(f"Wrong file  . Choosing from default file: {path}")

        with  open(path, 'r') as f:
            csv_reader = csv.reader(f , delimiter=' ', quotechar='|')
        #create books records
            customers_list = []
            for line in csv_reader:
                l=line[0].split(",")
                name , city , age = l[0] , l[1] , int(l[2])
                customer = Customer(name , city , age)
                customers_list.append(customer)
            f.close()

            return customers_list
#########################################################

    def getCustomerByID(self, myID):
        try:
            for customer in self.customers:
                if customer.id == myID:
                    return customer
            return -1
        except:
            return -1
##########################################################

    def getCustomerByName(self, name):
        try:
            for customer in self.customers:
                if customer.name.upper() == name.upper():
                    return customer
            return "no customer found !"
        except:
            return "no customer found !"
#######################################################

    def showCustomers(self):
        s=f"____________________________________CUSTOMERS________________________________________\n"
        try:
            for customer in self.customers:
                s+= f"{str(customer)} \n"
        except:
            pass
        return s
#########################################################

    def addCustomer(self,name =" ",city=" ",age=0):
        try:
            new_cust = Customer(name,city,int(age))
            self.customers.append(new_cust)
            print(f"Customer id: {new_cust.id} added succefuly !")
        except:
            print("Adding customer failed . Please try again !")
#########################################################

    def delCustomer(self,c_id=0):
        try:
            customer = self.getCustomerByID(c_id)
            self.customers.remove(customer)
            print("Customer delited !")
        except:
            print("wrong customer . please try again !")


"""Algorithms."""
from itertools import cycle
import numpy as np
from util import SlideShow, Slide

class OutputItem(object):
    """Item representing row in output file."""

    def __init__(self):
        self.members = []
        #self.time_counter = 0
        #self.position = [0,0]
        #self.last_visited_index_sorted = 0

    def __str__(self):
        """Output format"""
        return ' '.join([str(x) for x in self.members])

def algorithm(input_data):
    solution = []

    verticals = set()
    horizontals = set()
    for image in input_data.photos:
        if image.orientation == 'V':
            verticals.add(image)
        else:
            horizontals.add(image)

    # Add horizontals
    slideshow = [SlideShow(Slide(photo)) for photo in horizontals]

    # Add verticals
    if len(verticals) > 0:
        avg_vert_size = avg_tag_size(verticals)
        vert_slideshow = list(pair_verticals(verticals, avg_vert_size))
        slideshow = slideshow + vert_slideshow

    return slideshow

def pair_verticals(verticals, avg_vert_size):
    vert_temp = list(verticals)
    vert_temp = sorted(vert_temp)
    NUM_BINS = min([100, len(vert_temp)])
    vert_temp_list_of_cycles = list(chunks(vert_temp, NUM_BINS))
    for i in range(int(NUM_BINS / 2)):
        first_bin = vert_temp_list_of_cycles[i]
        last_bin = vert_temp_list_of_cycles[NUM_BINS-1-i]
        for photo1 in first_bin:
            costs = [cost_vertical_pair(photo1, photo2, avg_vert_size) for photo2 in last_bin]
            amin = np.argmin(costs)
            photo2 = last_bin.pop(amin)
            yield SlideShow(Slide(photo1, photo2))

def chunks(l, n_bins):
    size = int(len(l) / n_bins)
    for i in range(0, len(l), size):
        #yield cycle(l[i:i + size])
        yield list(l[i:i + size])

def avg_tag_size(set1):
    tag_sizes = [photo.size for photo in set1]
    return sum(tag_sizes) / len(tag_sizes)

def cost_vertical_pair(v1, v2, avg):
    is_avg = abs(avg - (v1.size + v2.size) / 2.0)
    inter = len(set(v1.tags).intersection(set(v2.tags)))
    return is_avg + inter


LANG = {
    "main_menu" : {
        "title" : {
            "fr" : "Menu Principal",
            "en" : "Main Menu",
            "es" : "Menu principal"
        },
        "savebutton" : {
            "fr" : "Sauvegarder",
            "en" : "Save",
            "es" : "Salvar"
        },
        "selectfile" : {
            "fr" : "Selectionner un fichier",
            "en" : "Select a file",
            "es" : "Selectionar una fila"
        }
    }
}


from typing import Optional, List
import logging
import datetime
import pandas as pd
from us_stock_wizard.database.db_utils import StockDbUtils, DbTable

logging.basicConfig(level=logging.INFO)

class FundamentalMeasurements:
    CRITERIA_1 = "cret_1"

class FundamentalAnalyzer:
    """

    Usage:
    >>> analyzer = FundamentalAnalyzer(ticker="AAPL")
    >>> await analyzer.get_fundamental()
    >>> res: bool = analyzer.get_result([FundamentalMeasurements.CRITERIA_1])

    """

    def __init__(self, ticker: str) -> None:
        self.ticker = ticker
        self.db_utils = StockDbUtils()
        self.data: Optional[pd.DataFrame] = pd.DataFrame()

    async def get_fundamental(self) -> None:
        """
        Get fundamental data from database
        """
        fundamental = await StockDbUtils.read(
            DbTable.FUNDAMENTALS, where={"ticker": self.ticker}, output="df"
        )
        self.data = fundamental

    def analyze(self) -> pd.DataFrame:
        """
        Analyze fundamental data
        """
        if self.data.empty:
            logging.info("No fundamental data found")
            return
        fundamental = self.data.copy()

        # Handle Quarterly Report only
        fundamental["reportDate"] = pd.to_datetime(fundamental["reportDate"])
        fundamental = fundamental[fundamental["reportType"] == "QUARTERLY"]
        fundamental = fundamental.sort_values(by="reportDate", ascending=True)

        # Calculate the YoY increasement
        fundamental["sales_YoY"] = fundamental["sales"].pct_change(periods=4)
        fundamental["netIncome_YoY"] = fundamental["netIncome"].pct_change(periods=4)
        fundamental["grossMarginRatio_YoY"] = fundamental[
            "grossMarginRatio"
        ].pct_change(periods=4)

        # Calculate the QoQ increasement
        fundamental["sales_QoQ"] = fundamental["sales"].pct_change(periods=1)
        fundamental["netIncome_QoQ"] = fundamental["netIncome"].pct_change(periods=1)
        fundamental["grossMarginRatio_QoQ"] = fundamental[
            "grossMarginRatio"
        ].pct_change(periods=1)

        return fundamental

    def get_result(self, criteria: List[FundamentalMeasurements]) -> bool:
        """
        Get result of fundamental analysis
        """
        if self.data.empty:
            return False
        combined_bool = []
        for cret in criteria:
            if cret == FundamentalMeasurements.CRITERIA_1:
                _ = self.cret_1()
                combined_bool.append(_)
            else:
                raise ValueError(f"Unknown criteria: {cret}")
        return all(combined_bool)

    def cret_1(self) -> bool:
        """
        Criteria
        1. Sales YoY growth rate > 30%
        """
        try:
            data = self.analyze()
            if data.empty:
                logging.warning("No fundamental data found")
                return False

            sales_yoy = data.iloc[-1]["sales_YoY"] > 0.3
            # Disable for now
            # netIncome_yoy = data.iloc[-1]["netIncome_YoY"] > 0.2

            _ = sales_yoy
            return _
        except Exception as e:
            logging.error(e)
            return False

class FundamentalScreener:
    """
    Screen a list of stocks based on fundamental analysis

    Example:
        >>> screener = FundamentalScreener()
        >>> await screener.initialize()
    """

    def __init__(self) -> None:
        self.stocks_df = pd.DataFrame()

        self.preferred_keywords = [
            "tech",
            "bio",
            "health",
            "pharm",
            "software",
            "medic",
            "consumer",
        ]
        self.blacklist_keywords = [
            "bank",
            "insurance",
            "estate",
            "oil",
            "energy",
            "gas",
            "power",
        ]

    async def initialize(self):
        await self.get_stocks()

    async def get_stocks(self) -> None:
        """
        Get stocks!
        """
        all_stocks = await StockDbUtils.read(table=DbTable.TICKERS, output="df")
        all_stocks = all_stocks[all_stocks["ticker"].str.len() < 5]
        self.stocks_df = all_stocks

    def filter_preferred(self) -> List[str]:
        """
        Return the preferred stock list
        """
        if self.stocks_df.empty:
            raise ValueError("No stocks in the dataframe!")
        df = self.stocks_df.copy()
        df["joint_kw"] = df["sector"] + " " + df["industry"]
        df["joint_kw"] = df["joint_kw"].str.lower()
        pattern = "|".join(self.preferred_keywords)
        df["contains_preferred"] = df["joint_kw"].str.contains(pattern)
        df = df[df["contains_preferred"] == True]
        return df["ticker"].tolist()

    def filter_blacklist(self) -> List[str]:
        """
        Return the blacklist stock list
        """
        if self.stocks_df.empty:
            raise ValueError("No stocks in the dataframe!")
        df = self.stocks_df.copy()
        df["joint_kw"] = df["sector"] + " " + df["industry"]
        df["joint_kw"] = df["joint_kw"].str.lower()
        pattern = "|".join(self.blacklist_keywords)
        df["contains_blacklist"] = df["joint_kw"].str.contains(pattern)
        df = df[df["contains_blacklist"] == True]
        return df["ticker"].tolist()

    async def filter_fundamentals(
        self,
        crets: List[FundamentalMeasurements] = [FundamentalMeasurements.CRITERIA_1],
    ) -> List[str]:
        """
        Filter stocks based on fundamental analysis
        """
        if self.stocks_df.empty:
            raise ValueError("No stocks in the dataframe!")
        df = self.stocks_df.copy()
        tickers = df["ticker"].tolist()
        res = []
        for ticker in tickers:
            _: bool = False
            try:
                analyzer = FundamentalAnalyzer(ticker=ticker)
                await analyzer.get_fundamental()
                _ = analyzer.get_result(crets)
            except Exception as e:
                logging.error(f"Analyse {ticker} failed: {e}")
            if _:
                res.append(ticker)
        return res


from ET import *
import sys

# issue- 12790 : https://github.com/elastic/elasticsearch/issues/12790
# 1. create an index with settings having creation_date and version
# 2. get settings of the index of step 1
# Observed: the new index settings has creation_date and version same as settings given
# Expected: the new index settings should have creation_date and version to new updated values

indexone_name = "index1";
if sys.argv[1:]:
  indexone_name = sys.argv[1];
#*******************************************************
#1
settings            = {'settings': {
                                     'index': {
                                                 'number_of_replicas': '1',
                                                 'version': {'created': '2000001'},
                                                 'creation_date': '1439384094544',
                                                 'uuid': 'ayzHgwB3Sgey-Pk_Okgwyg',
                                                 'number_of_shards': '5'
                                              }
                                   }
                      }
put("http://localhost:9200/%s" % (indexone_name), settings);

#********************************************************
#2
new_index = get("http://localhost:9200/%s/_settings" % (indexone_name));
print("input settings \n");
print(settings);
print("\n");
print("new index settings \n");
print(new_index.get(indexone_name));

#NOTE: for repeated test case just change the indexone_name value above and run
# or run with command line arguments


#!/usr/bin/env python3

from pydub import AudioSegment

song = AudioSegment.from_mp3("hyperreal.mp3")

# pydub does things in milliseconds
ten_seconds = 10 * 1000

first_10_seconds = song[ten_seconds:]
last_5_seconds = song[:-5000]

# boost volume by 6dB
beginning = first_10_seconds + 6

# reduce volume by 3dB
end = last_5_seconds - 3

without_the_middle = beginning + end

# song is not modified
backwards = song.reverse()

# 1.5 second crossfade
with_style = beginning.append(end, crossfade=1500)

# repeat the clip twice
do_it_over = with_style * 2

# 2 sec fade in, 3 sec fade out
awesome = do_it_over.fade_in(2000).fade_out(3000)

beat = (song[8800:9300].fade_out(13000).reverse() + 5) * 10
beat.export("mashup.mp3", format="mp3", bitrate="192k")


from dataclasses import dataclass
from functools import lru_cache

import numpy as np

from piafedit.model.geometry.point import PointAbs
from piafedit.model.geometry.rect import RectAbs, RawRect
from piafedit.model.geometry.size import SizeAbs
from piafedit.model.libs.operator import Buffer
from piafedit.model.source.data_source import DataSource

@dataclass(frozen=True)
class TileConfig:
    size: SizeAbs

    @property
    def width(self):
        return self.size.width

    @property
    def height(self):
        return self.size.height

class TileSource(DataSource):
    def __init__(self, source: DataSource, config: TileConfig):
        self.source = source
        self.config = config
        self.cache = dict()

    def infos(self):
        return self.source.infos()

    def read(self, window: RectAbs = None, output_size: SizeAbs = None) -> Buffer:
        window = self.update_window(window)
        tiles = self._tiles(window)
        lines = []

        h = len(tiles) * self.config.width
        w = len(tiles[0]) * self.config.height
        b = self.source.infos().bands
        shape = (h, w, b)
        buffer = np.zeros(shape)

        for line in tiles:
            for row in line:
                tile = RectAbs.from_raw(row)
                tile_buffer = self._read_tile(row)
                b = tile.crop(buffer)
                if b.shape == tile_buffer.shape:
                    b[...] = tile_buffer
        return buffer[:window.item_per_page.height, :window.item_per_page.width, ...]

    def write(self, buffer: Buffer, window: RectAbs = None):
        self.source.write(buffer, window)

    def _tiles(self, rect: RectAbs):
        start = self.point_to_tile(rect.pos)
        end = self.point_to_tile(rect.pos.copy().move(*rect.size.raw()))
        lines = [
            [
                RectAbs(PointAbs(x, y), self.config.size).raw()
                for x in range(start.pos.x, end.pos.x, self.config.width)
            ]
            for y in range(start.pos.y, end.pos.y, self.config.height)
        ]
        return lines

    @lru_cache()
    def _read_tile(self, tile: RawRect):
        return self.source.read(RectAbs.from_raw(tile))

    def point_to_tile(self, pos: PointAbs):
        dx = pos.x % self.config.width
        dy = pos.y % self.config.height
        return RectAbs(
            pos=PointAbs(pos.x - dx, pos.y - dy),
            size=self.config.size
        )


# Basic script to toggle the LED state on GPIO pin 7
# For Raspberry Pi pin mapping, see:
# https://www.raspberrypi.org/documentation/usage/gpio/README.md
#
# Insipired by:
# https://www.raspberrypi.org/learning/python-quick-reaction-game/worksheet/
#

from gpiozero import LED
from time import sleep

flag = True
led = LED(7)
while True:
    if flag:
        print("on");
        led.on()
    else:
        print("off");
        led.off()
    flag = not flag
    sleep(1)