'''
Created on Nov 19, 2015

@author: Sameer Adhikari

'''

from patterns.state.node import Node

# All the states are defined is one file due to the circular dependency between router and each state.
# Putting each state in a separate model meant that the circular dependency caused import errors.

class StartState(object):
    '''
    The starting state of the parser, when no
    processing of the input string has taken place.
    '''

    def process(self, remaining_string, parser):
        i_start_tag = remaining_string.find('<')
        i_end_tag = remaining_string.find('>')
        tag_name = remaining_string[i_start_tag + 1 : i_end_tag]
        root = Node(tag_name)
        parser.root = root
        parser.current_node = root
        parser.state = RouterState()
        return remaining_string[i_end_tag + 1:]

class TagOpenState(object):
    '''
    '''
    def process(self, remaining_string, parser):
        i_start_tag = remaining_string.find('<')
        i_end_tag = remaining_string.find('>')
        tag_name = remaining_string[i_start_tag + 1 : i_end_tag]
        node = Node(tag_name, parser.current_node)
        parser.current_node.children.append(node)
        parser.current_node = node
        parser.state = RouterState()
        return remaining_string[i_end_tag + 1:].strip()

class TagCloseState(object):
    '''
    '''
    def process(self, remaining_string, parser):
        i_start_tag = remaining_string.find('<')
        i_end_tag = remaining_string.find('>')
        assert remaining_string[i_start_tag + 1] == '/'
        tag_name = remaining_string[i_start_tag + 2 : i_end_tag]
        assert tag_name == parser.current_node.tag_name
        parser.current_node = parser.current_node.parent #closing a tag so switch back to parent
        parser.state = RouterState()
        return remaining_string[i_end_tag + 1:].strip()

class TagTextState(object):
    '''
    '''
    def process(self, remaining_string, parser):
        i_start_tag = remaining_string.find('<')
        text = remaining_string[:i_start_tag]
        parser.current_node.text = text
        parser.state = RouterState()
        return remaining_string[i_start_tag:]

class RouterState(object):
    '''
    State that determines which state to switch to next.
    All states switch to this state once they finish their tasks.
    Then this states decides which one of those to move to next.
    This state does not actually extract parts of the string.
    '''
    def process(self, remaining_string, parser):
        stripped = remaining_string.strip()
        if stripped.startswith('</'):
            parser.state = TagCloseState()
        elif stripped.startswith('<'):
            parser.state = TagOpenState()
        else:
            parser.state = TagTextState()

        return stripped


# coding: utf-8

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
from collections import Counter
from nltk.corpus import stopwords
import string
from matplotlib import rcParams
from itertools import chain
from nltk import everygrams, word_tokenize
sns.set_style("whitegrid")

df_train = pd.read_csv('/home/andrew/Desktop/Kaggle_Competition/Data/train.csv')
df_test = pd.read_csv('/home/andrew/Desktop/Kaggle_Competition/Data/test.csv')

stop = stopwords.words('english')

df_train.head()

pat = r'\b(?:{})\b'.format('|'.join(stop))
df_train['question_text'] = df_train['question_text'].str.lower()
df_train['question_text'] = df_train['question_text'].str.replace(pat, '')
df_train['question_text'] = df_train['question_text'].str.replace('[{}]'.format(string.punctuation), '')
df_train.head()

df_test.head(5)

rcParams['figure.figsize'] = 11.7,8.27
sns.countplot(df_train['target'])

sincere = df_train.loc[df_train['target'] == 0]
insincere = df_train.loc[df_train['target'] == 1]

insincere_bag_of_words = []
for row in insincere['question_text']:
    for word in row.split():
        insincere_bag_of_words.append(word)
insincere_dictionary = Counter(insincere_bag_of_words)

insincere_df = pd.DataFrame.from_dict(insincere_dictionary, orient='index')
insincere_df.columns = ['word_count']
insincere_df.sort_values(by = ['word_count'], inplace = True, ascending = False)
insincere_df.reset_index(inplace = True)
insincere_df.columns = ['word', 'word_count']
insincere_df.head()

words_selected = 10
rcParams['figure.figsize'] = 11.7,8.27
plt.title("Word Count: Top " + str(words_selected) + " in Insincere Questions")
sns.barplot(x = 'word', y = 'word_count', data = insincere_df.head(words_selected))

sincere_bag_of_words = []
for row in sincere['question_text']:
    for word in row.split():
        sincere_bag_of_words.append(word)
sincere_dictionary = Counter(sincere_bag_of_words)

sincere_df = pd.DataFrame.from_dict(sincere_dictionary, orient='index')
sincere_df.columns = ['word_count']
sincere_df.sort_values(by = ['word_count'], inplace = True, ascending = False)
sincere_df.reset_index(inplace = True)
sincere_df.columns = ['word', 'word_count']
sincere_df.head()

words_selected = 10
rcParams['figure.figsize'] = 11.7,8.27
plt.title("Word Count: Top " + str(words_selected) + " in Sincere Questions")
sns.barplot(x = 'word', y = 'word_count', data = sincere_df.head(words_selected))

fig, (ax1, ax2) = plt.subplots(ncols = 2, sharey = True)
sns.barplot(x = insincere_df['word'].head(10), y = insincere_df['word_count'], ax = ax1)
sns.barplot(x = sincere_df['word'].head(10), y = sincere_df['word_count'], ax = ax2)
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(rotation = 45)
ax1.title.set_text('Word Count: Top 10 Insincere Words')
ax2.title.set_text('Word Count: Top 10 Sincere Words')

sincere_2gram = sincere
sincere_2gram['question_text'] = sincere_2gram['question_text'].apply(lambda x: [' '.join(ng) for ng in everygrams(word_tokenize(x), 2)])

sincere_2gram.head()

sincere_2gram_list = []
for row in sincere_2gram['question_text']:
    for n_gram in row:
        sincere_2gram_list.append(n_gram)

sincere_2gram_dictionary = Counter(sincere_2gram_list)

sincere_2gram_df = pd.DataFrame.from_dict(sincere_2gram_dictionary, orient='index')
sincere_2gram_df.columns = ['word_count']
sincere_2gram_df.sort_values(by = ['word_count'], inplace = True, ascending = False)
sincere_2gram_df.reset_index(inplace = True)
sincere_2gram_df.columns = ['word', 'word_count']
sincere_2gram_df.head()

words_selected = 10
rcParams['figure.figsize'] = 11.7,8.27
plt.title("Word Count: Top " + str(words_selected) + " 2-Grams in Sincere Questions")
sns.barplot(x = 'word_count', y = 'word', data = sincere_2gram_df.head(words_selected))

insincere_2gram = insincere
insincere_2gram['question_text'] = insincere_2gram['question_text'].apply(lambda x: [' '.join(ng) for ng in everygrams(word_tokenize(x), 3)])

insincere_2gram.head()

insincere_2gram_list = []
for row in insincere_2gram['question_text']:
    for n_gram in row:
        insincere_2gram_list.append(n_gram)

insincere_2gram_dictionary = Counter(insincere_2gram_list)
insincere_2gram_df = pd.DataFrame.from_dict(insincere_2gram_dictionary, orient='index')
insincere_2gram_df.columns = ['word_count']
insincere_2gram_df.sort_values(by = ['word_count'], inplace = True, ascending = False)
insincere_2gram_df.reset_index(inplace = True)
insincere_2gram_df.columns = ['word', 'word_count']
insincere_2gram_df.head()

words_selected = 25
rcParams['figure.figsize'] = 11.7,8.27
plt.title("Word Count: Top " + str(words_selected) + " 2-Grams in Insincere Questions")
sns.barplot(x = 'word_count', y = 'word', data = insincere_2gram_df.head(words_selected))

fig, (ax1, ax2) = plt.subplots(ncols = 2, sharey = True)
sns.barplot(x = insincere_2gram_df['word'].head(10), y = insincere_2gram_df['word_count'], ax = ax1)
sns.barplot(x = sincere_2gram_df['word'].head(10), y = sincere_2gram_df['word_count'], ax = ax2)
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(rotation = 70)
ax1.title.set_text('Word Count: Top 10 2-Gram Insincere Words')
ax2.title.set_text('Word Count: Top 10 2-Gram Sincere Words')


import os
import sqlite3
#import pprint
#import time
#import iata_codes
from flask import Flask, request, render_template

application = Flask(__name__)
@application.route('/', methods=['POST', 'GET'])
def index():
    if request.method == 'GET':
        return render_template('index.html')

    elif request.method == 'POST':
        conn = sqlite3.connect('skytroo.db')
        cur = conn.cursor()
        weekendid= request.form['weekend']

#        homecity = request.form['City']
#        homecity = 'London'  ##### change with a request from webpage

######## FINDING THE COORDINATES OF THE HOMECITY (manually is London in this version)#############
######## for different cities i.e. berlin we will use different databases: cities and flights #########
        myData=[]

        cur.execute('''SELECT city_id, Temp_Sat, Cloud_Sat, Temp_Sun, Cloud_Sun, Duration, Score
        FROM Weather WHERE weekend_id = ? ORDER BY Score DESC LIMIT 10''', (weekendid,))
        row = cur.fetchall()
        for i in row:
            if i[5] < 240: #lets than 240/60 = 4 hours distance from departure city
                average_temp = (i[1]+i[3])/2
                average_clouds = (i[2]+i[4])/2
                flight = i[5]
                score = i[6]
                cur.execute('''SELECT * FROM Cities WHERE city_id = ?''', (i[0],))
                coords=cur.fetchone()
                if average_clouds<=0.3:
                    type = 'mostly sunny'
                elif 0.3>average_clouds<0.5:
                    type = 'sun and clouds'
                elif 0.5>average_clouds:
                    type = 'partial sunshine'
                cur.execute('''SELECT price FROM Prices WHERE city = ? AND weekend = ?''', (coords[1], weekendid))
                price=cur.fetchone()
                # a quick 'if' command to check and remove N/A flights from the results on the map#
                # careful there must be 20 number of prices to match 20 weather results. if there are less prices then the object returned is NoneType and the code blows
                #######  the if excludes higher prices from 300 quid and unavailable flights ##############
                if price[0]!= 'timeoutException' and price[0]!='Sorry, there are no results that match your search' and price[0]!='Sorry, there are no results that match your filters':
                    if float(price[0].strip('£'))<300:
                        zz = [coords[4], coords[3], coords[1], coords[2], round(average_temp,0), type, flight, price[0]]
                        myData.append(zz)
#        print(myData)
    return render_template('where.html', myData=myData)
#    return render_template('where.html')
#@application.route('/results')
#def results():
#    return render_template('where.html', myData=myData)

#@application.route('/contact/')
#def contact():
#    return render_template('contact.html')

#@application.route('/pricing/')
#def pricing():
#    return render_template('pricing.html')

if __name__ == '__main__':
    application.debug = True
    host = os.environ.get('IP', '127.0.0.1')
    port = int(os.environ.get('PORT', 80))
    application.run(host=host, port=port)


n = int(input(""))
lst = []
for i in range(0,n):
    l = int(input(""))
    lst.append(l)

lst1 = []

for i in lst :
    for t in range (0,10):
        f = (t**3)+((t+1)**3)
        if(i == f):
            lst1.append(i)

lst1.sort()

if(lst1):
    for i in lst1 :
        print(i,end = " ")
else:
    print(-1)


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def searchBST(self, root, val: int):
        if root is None:
            return None
        if root.val == val:
            return root
        if root.left is not None:
            left_re = self.searchBST(root.left, val)
            if left_re is not None:
                return left_re

        if root.right is not None:
            right_re = self.searchBST(root.right, val)
            if right_re is not None:
                return right_re
        return None


def isInList(list, item):
    list.sort()
    lower = 0
    middle = (len(list))/2
    higher = len(list) - 1

    while middle != lower and middle != higher:
        print('lower: {}, middle: {}, higher: {}'.format(lower, middle, higher))
        if list[lower] == item or list[higher] == item:
            return True
        if item > list[middle]:
            lower = middle
            middle = (lower + higher)/2
        elif item < list[middle]:
            higher = middle
            middle = (lower + higher)/2
        else:
            return True

    return False

if __name__== "__main__":
    result = isInList([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 100)
    print(result)


import pygame
import socket

HOST = '192.168.178.129'
PORT = 5555
player_img = pygame.image.load("spaceship/R.png")
player_width, player_height = 50, 50
player_img = pygame.transform.scale(player_img, (player_width, player_height))

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((HOST, PORT))

pygame.init()

width, height = 500, 500
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("Client")

player_x, player_y = 250, 250
player_width, player_height = 50, 50
player_color = (0, 255, 0)
player_vel = 20

clock = pygame.time.Clock()

def send_movement(key):
    message = f"MOVE:{key}"
    client.send(message.encode())

def redraw_window(x, y):
    win.fill((255, 255, 255))
    win.blit(player_img, (x,y))
    pygame.display.update()

def main():
    run = True
    global player_x, player_y
    while run:
        clock.tick(60)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    if player_y - player_vel > 0:
                        player_y -= player_vel
                        send_movement("UP")
                elif event.key == pygame.K_DOWN:
                    if player_y + player_vel < height - player_height:
                        player_y += player_vel
                        send_movement("DOWN")
                elif event.key == pygame.K_LEFT:
                    if player_x - player_vel > 0:
                        player_x -= player_vel
                        send_movement("LEFT")
                elif event.key == pygame.K_RIGHT:
                    if player_x + player_vel < width - player_width:
                        player_x += player_vel
                        send_movement("RIGHT")
                elif event.key == pygame.K_SPACE:
                    player_x += player_vel
                    send_movement("SPACE")

        redraw_window(player_x, player_y)

    client.close()

if __name__ == "__main__":
    main()


import tensorflow as tf
import itertools
import scipy.spatial.distance
import numpy as np
import time

worker_hosts = ["10.142.0.16:2222", "10.142.0.17:2223"]
# get internal ips of each instance from Google Cloud Compute Engine
# worker_hosts = ["ip1:port","ip2:port"]
# parameter_server = ["ip:port"]

# Set up a TensorFlow cluster
cluster = tf.train.ClusterSpec({"worker": worker_hosts})
# cluster = tf.train.ClusterSpec({"worker": worker_hosts, "ps": parameter_server})

# FLAGS need to be included when run the script using command line
tf.flags.DEFINE_string("job_name", "", "'worker or ps")
tf.flags.DEFINE_integer("task_index", 0, "Index of task")
FLAGS = tf.flags.FLAGS
server = tf.train.Server(cluster, job_name=FLAGS.job_name, task_index=FLAGS.task_index)

# Define computation graph as usual
# Put operations into desired instance
inter = 24
exc = 48

n_inter = inter*inter
n_exc = exc*exc

x = list(itertools.product(range(exc),repeat=2))
d = scipy.spatial.distance.pdist(x,'sqeuclidean')
y = scipy.spatial.distance.squareform(d)
y2 = y[::2]
z = np.reshape(range(inter*exc),(exc,inter))
z = np.reshape(z[::2],(n_inter))
y2 = y2[z]
Pee_granular = 0.15*np.exp(-(y/4)**2)
Pie_granular = 0.3*np.exp(-(y2/4)**2)
Pee_supra = 0.15*np.exp(-(y/4)**2)
Pie_supra = 0.3*np.exp(-(y2/4)**2)
rand_granular_ee = np.random.rand(n_exc,n_exc)
rand_granular_ie = np.random.rand(n_inter,n_exc)
rand_supra_ee = np.random.rand(n_exc,n_exc)
rand_supra_ie = np.random.rand(n_inter,n_exc)
x1,y1 = np.where(Pee_granular-rand_granular_ee<0)
Pee_granular[x1,y1] = 0
Pee_granular = Pee_granular*5
np.fill_diagonal(Pee_granular,0)
x1,y1 = np.where(Pie_granular-rand_granular_ie<0)
Pie_granular[x1,y1] = 0
x1,y1 = np.where(Pee_supra-rand_supra_ee<0)
Pee_supra[x1,y1] = 0
Pee_supra = Pee_supra*5
np.fill_diagonal(Pee_supra,0)
x1,y1 = np.where(Pie_supra-rand_supra_ie<0)
Pie_supra[x1,y1] = 0

x = list(itertools.product(range(inter),repeat=2))
d = scipy.spatial.distance.pdist(x,'sqeuclidean')
y = scipy.spatial.distance.squareform(d)
Pii_granular = 0.5*np.exp(-(y/2)**2)
Pii_supra = 0.5*np.exp(-(y/2)**2)
rand_granular_ii = np.random.rand(n_inter,n_inter)
rand_supra_ii = np.random.rand(n_inter,n_inter)
x1,y1 = np.where(Pii_granular-rand_granular_ii<0)
Pii_granular[x1,y1]=0
np.fill_diagonal(Pii_granular,0)
x1,y1 = np.where(Pii_supra-rand_supra_ii<0)
Pii_supra[x1,y1]=0
np.fill_diagonal(Pii_supra,0)

x = list((0,i) for i in range(exc))
y = list((1,i) for i in range(exc))
d = scipy.spatial.distance_matrix(x,y)
Pee_vertical = 0.8*np.exp(-(d/2)**2)
rand_vertical_ee = np.random.rand(exc,exc)
x1,y1 = np.where(Pee_vertical-rand_vertical_ee<0)
Pee_vertical[x1,y1]=0
y = y[::2]
d = scipy.spatial.distance_matrix(x,y)
Pie_vertical = 0.5*np.exp(-(d/2)**2)
rand_vertical_ie = np.random.rand(exc,inter)
x1,y1 = np.where(Pie_vertical-rand_vertical_ie<0)
Pie_vertical[x1,y1]=0

sess = tf.InteractiveSession()

class SynapticDelay(tf.contrib.rnn.RNNCell):

    def __init__(self,num_units):
        self._state_size = num_units

    def __call__(self, inputs, state, scope=None):
        output = state[:,-1]
        newstate = tf.concat([inputs,state[:,0:-1]],1)
        return output,newstate

class NewCell(tf.contrib.rnn.RNNCell):

    def __init__(self, num_state):
        self._state_size = num_state

    def __call__(self, inputs, state, scope=None):
        Iext = inputs
        V, G, F, W, B = tf.split(state, [1, 1, 1, 1, 1],1)
        dt = 0.01
        g_Na = 120
        g_K = 15
        g_L = 0.3
        g_A = 9
        V_Na = 55
        V_K = -72
        V_L = -53
        V_syn = 55
        taus = 2
        synth = 10

        def Steady_Variable(a, V, V_half):
            P = 1 / (1 + tf.exp(-2 * a * (V - V_half)))
            return P

        def TimeConstantW(Lam, V, V_half):
            tao = 1 / (Lam * (tf.exp(0.055 * (V - V_half)) + tf.exp(-0.055 * (V - V_half))))
            return tao

        Im = Steady_Variable(0.065, V, -31)
        IW = Steady_Variable(0.055, V, -35)
        IA = Steady_Variable(0.020, V, -20)
        IB = Steady_Variable(-0.10, V, -70)
        taow = TimeConstantW(0.08, V, -35)

        W_ = W + dt * (IW - W) / taow
        B_ = B + dt * (IB - B) / 10
        F_ = F + dt / taus * (-F + (tf.sign(V - synth) + 1) / 2)
        G_ = G + dt / taus * (-G + F)

        I_Na = g_Na * Im ** 3 * (1 - W) * (V - V_Na)
        I_K = g_K * W ** 4 * (V - V_K)
        I_A = g_A * IA * B * (V - V_K)
        I_L = g_L * (V - V_L)
        SumI = Iext - I_Na - I_K - I_A - I_L
        V_ = V + dt * SumI
        output = G*(V-V_syn)

        nextstate = tf.concat([V_,G_,F_,W_,B_],1)

        return output,nextstate

cell = NewCell(5)
delay = SynapticDelay(100)

granular_supra_ee0 = tf.Variable(tf.zeros(shape=(exc, exc), dtype=tf.float32))
granular_supra_ei0 = tf.Variable(tf.zeros(shape=(inter, inter), dtype=tf.float32))

global1 = tf.Variable(0)
global2 = tf.Variable(0)

# queue  = queue = tf.FIFOQueue(1, shapes=(), shared_name="Que", dtypes=tf.int32)

with tf.device("/job:worker/task:0"):
    granular_pyramidal_input = tf.placeholder(shape=(n_exc,1),dtype=tf.float32)
    granular_pyramidal_state = tf.placeholder(shape=(n_exc,5),dtype=tf.float32)
    granular_pyramidal_delay = tf.placeholder(shape=(n_exc,300),dtype=tf.float32)

    granular_basket_input = tf.placeholder(shape=(n_inter,1),dtype=tf.float32)
    granular_basket_state = tf.placeholder(shape=(n_inter,5),dtype=tf.float32)
    granular_basket_delay = tf.placeholder(shape=(n_inter,1200),dtype=tf.float32)

    (granular_pyramidal_output, granular_pyramidal_nextstate) = cell(granular_pyramidal_input, granular_pyramidal_state)
    (granular_pyramidal_synout, granular_pyramidal_synstate) = delay(granular_pyramidal_output, granular_pyramidal_delay)

    (granular_basket_output, granular_basket_nextstate) = cell(granular_basket_input, granular_basket_state)
    (granular_basket_synout, granular_basket_synstate) = delay(granular_basket_output, granular_basket_delay)

    granular_ee = tf.layers.dense(tf.reshape(granular_pyramidal_synout, (1, n_exc)), n_exc,
                                  kernel_initializer=tf.constant_initializer(Pee_granular))
    granular_ei = tf.layers.dense(tf.reshape(granular_pyramidal_synout, (1, n_exc)), n_inter,
                                  kernel_initializer=tf.constant_initializer(Pie_granular))
    granular_ie = tf.layers.dense(tf.reshape(granular_basket_synout, (1, n_inter)), n_exc,
                                  kernel_initializer=tf.constant_initializer(-np.transpose(Pie_granular)))
    granular_ii = tf.layers.dense(tf.reshape(granular_basket_synout, (1, n_inter)), n_inter,
                                  kernel_initializer=tf.constant_initializer(-Pii_granular))

    granular_supra_ee = tf.layers.dense(tf.reshape(granular_pyramidal_synout, (exc, exc)), exc,
                                        kernel_initializer=tf.constant_initializer(Pee_vertical))
    Layer_ei = tf.reshape(granular_pyramidal_synout, (exc, exc))
    granular_supra_ei = tf.layers.dense(tf.transpose(Layer_ei[:, ::2]), inter,
                                        kernel_initializer=tf.constant_initializer(np.transpose(Pie_vertical)))

    granular_pyramidal = tf.add(granular_ee, granular_ie)
    granular_basket = tf.add(granular_ei, granular_ii)

    connect = tf.group(granular_supra_ee0.assign(granular_supra_ee), granular_supra_ei0.assign(granular_supra_ei))

with tf.device("/job:worker/task:1"):

    supra_pyramidal_input = tf.placeholder(shape=(n_exc,1),dtype=tf.float32)
    supra_pyramidal_state = tf.placeholder(shape=(n_exc,5),dtype=tf.float32)
    supra_pyramidal_delay = tf.placeholder(shape=(n_exc,300),dtype=tf.float32)

    supra_basket_input = tf.placeholder(shape=(n_inter,1),dtype=tf.float32)
    supra_basket_state = tf.placeholder(shape=(n_inter,5),dtype=tf.float32)
    supra_basket_delay = tf.placeholder(shape=(n_inter,1200),dtype=tf.float32)

    (supra_pyramidal_output,supra_pyramidal_nextstate) = cell(supra_pyramidal_input,supra_pyramidal_state)
    (supra_pyramidal_synout,supra_pyramidal_synstate) = delay(supra_pyramidal_output,supra_pyramidal_delay)

    (supra_basket_output,supra_basket_nextstate) = cell(supra_basket_input,supra_basket_state)
    (supra_basket_synout,supra_basket_synstate) = delay(supra_basket_output,supra_basket_delay)

    supra_ee = tf.layers.dense(tf.reshape(supra_pyramidal_synout,(1,n_exc)),n_exc,kernel_initializer=tf.constant_initializer(Pee_supra))
    supra_ei = tf.layers.dense(tf.reshape(supra_pyramidal_synout,(1,n_exc)),n_inter,kernel_initializer=tf.constant_initializer(Pie_supra))
    supra_ie = tf.layers.dense(tf.reshape(supra_basket_synout,(1,n_inter)),n_exc,
                                  kernel_initializer=tf.constant_initializer(-np.transpose(Pie_supra)))
    supra_ii = tf.layers.dense(tf.reshape(supra_basket_synout,(1,n_inter)),n_inter,kernel_initializer=tf.constant_initializer(-Pii_supra))

    supra_pyramidal = tf.add(tf.add(supra_ee,supra_ie),tf.reshape(granular_supra_ee0,(1,n_exc)))
    supra_basket = tf.add(tf.add(supra_ii,supra_ei),tf.reshape(granular_supra_ei0,(1,n_inter)))

Input_granular_pyramidal = np.zeros((n_exc,1))
y = [int(exc*i+(exc/2-1)) for i in range(exc)]
Input_granular_pyramidal[y] = 8
Input_granular_basket = np.zeros((n_inter,1))
y = [int(inter*i+(inter/2-1)) for i in range(inter)]
Input_granular_basket[y] = 8
Input_supra_pyramidal = np.zeros((n_exc,1))
Input_supra_basket = np.zeros((n_inter,1))

V_init = -60
G_init = 0
F_init = 0
W_init = 1 / (1 + np.exp(-2 * 0.055 * (V_init + 35)))
B_init = 1 / (1 + np.exp(2 * 0.1 * (V_init + 70)))
cell_init = np.array([V_init,G_init,F_init,W_init,B_init])

state_granular_pyramidal = np.matrix([cell_init for _ in range(n_exc)])
state_granular_basket = np.matrix([cell_init for _ in range(n_inter)])
state_supra_pyramidal = np.matrix([cell_init for _ in range(n_exc)])
state_supra_basket = np.matrix([cell_init for _ in range(n_inter)])

delay_granular_pyramidal = np.zeros((n_exc,300))
delay_granular_basket = np.zeros((n_inter,1200))
delay_supra_pyramidal = np.zeros((n_exc,300))
delay_supra_basket = np.zeros((n_inter,1200))

is_chief = (FLAGS.task_index == 0)

# Define the sessions to be called on different instance
# If there is a parameter server, use server.join() to block the server
if FLAGS.job_name == "ps":
    server.join()
elif FLAGS.job_name == "worker":
    with tf.Session(server.target) as sess:
        if is_chief:
            sess.run(tf.global_variables_initializer())
            print("chief initialized")
        else:
            sess.run(tf.global_variables_initializer())
            while len(sess.run(tf.report_uninitialized_variables())) > 0:
                print("worker:%d waiting for initialization" % FLAGS.task_index)
            print("worker:%d ready"% FLAGS.task_index)

        if FLAGS.task_index == 0:
            Input_granular_pyramidal1 = Input_granular_pyramidal
            Input_granular_basket1 = Input_granular_basket
            P_granular_pyramidal = []
            P_granular_basket = []
            t = time.time()
            for i in range(20000):
                # sess.run(queue.enqueue(i))
                state_granular_pyramidal, delay_granular_pyramidal, state_granular_basket, delay_granular_basket,\
                Input_granular_pyramidal2, Input_granular_basket2,_,g1 = \
                    sess.run([granular_pyramidal_nextstate, granular_pyramidal_synstate, granular_basket_nextstate,
                              granular_basket_synstate,granular_pyramidal, granular_basket, connect,global1.assign_add(1)],
                             feed_dict={granular_pyramidal_input: Input_granular_pyramidal1,
                                        granular_pyramidal_state: state_granular_pyramidal,
                                        granular_pyramidal_delay: delay_granular_pyramidal,
                                        granular_basket_input: Input_granular_basket1,
                                        granular_basket_state: state_granular_basket,
                                        granular_basket_delay: delay_granular_basket})
                Input_granular_pyramidal1 = Input_granular_pyramidal - np.transpose(Input_granular_pyramidal2)
                Input_granular_basket1 = Input_granular_basket - np.transpose(Input_granular_basket2)
                P_granular_pyramidal.append(state_granular_pyramidal[:, 0])
                P_granular_basket.append(state_granular_basket[:, 0])
                while sess.run(global2) != g1:
                    time.sleep(0.0005)
                if i%100 == 0:
                    print('step %d'%i)
            np.savetxt('GP.csv', P_granular_pyramidal)
            np.savetxt('GB.csv', P_granular_basket)
            print(time.time()-t)

        if FLAGS.task_index == 1:
            P_supra_pyramidal = []
            P_supra_basket = []
            t = time.time()
            for i in range(20000):
                state_supra_pyramidal, delay_supra_pyramidal, state_supra_basket, delay_supra_basket,Input_supra_pyramidal2, Input_supra_basket2, g2 = \
                    sess.run([supra_pyramidal_nextstate, supra_pyramidal_synstate, supra_basket_nextstate,
                              supra_basket_synstate, supra_pyramidal, supra_basket, global2.assign_add(1)],
                             feed_dict={supra_pyramidal_input: Input_supra_pyramidal,
                                        supra_pyramidal_state: state_supra_pyramidal,
                                        supra_pyramidal_delay: delay_supra_pyramidal,
                                        supra_basket_input: Input_supra_basket, supra_basket_state: state_supra_basket,
                                        supra_basket_delay: delay_supra_basket})
                Input_supra_pyramidal = -np.transpose(Input_supra_pyramidal2)
                Input_supra_basket = -np.transpose(Input_supra_basket2)
                P_supra_pyramidal.append(state_supra_pyramidal[:, 0])
                P_supra_basket.append(state_supra_basket[:, 0])
                while sess.run(global1) != g2:
                    time.sleep(0.0005)
                # sess.run(queue.dequeue())
                if i % 100 == 0:
                    print('step %d' % i)
            np.savetxt('SP.csv', P_supra_pyramidal)
            np.savetxt('SB.csv', P_supra_basket)
            print(time.time()-t)


#!/usr/bin/env python
usage="""Checks the status for a subset of reads within a bam file.

Three categories:
    Not Mapped
    Mapping to < 1000 bp contig
    Mapping to > 1000 bp contig (not MAG)
    Mapping to MAG contig
"""

import argparse
import sys
import re

soft_clip_re = re.compile('([0-9]+)S')
matched_re = re.compile('([0-9]+)M')

nr_mismatched_re = re.compile('XM:i:([0-9]+)')

def parse_cigar(cigar):
    soft_clipped_matches = soft_clip_re.findall(cigar)
    matched_matches = matched_re.findall(cigar)
    soft_clipped_bases = sum([int(x) for x in soft_clipped_matches])
    matched_bases = sum([int(x) for x in matched_matches])

    return soft_clipped_bases, matched_bases

def main(args):
    all_reads = set()
    for line in open(args.subset_reads, 'r'):
        read = line.strip()
        all_reads.add(read)

    MAG_contigs = set()
    for line in open(args.mag_contigs, 'r'):
        contig = line.strip()
        MAG_contigs.add(contig)

    not_mapped = set()
    short_mapped = set()
    long_mapped = set()
    MAG_mapped = set()

    contig_len_re = re.compile('SN:(.*)		*LN:([0-9]*)$')
    contig_lens = {}

    # Read the input sam file
    for line in sys.stdin:
        line = line.strip()

        # Check if in header
        if line[0] == '@':
            if line[0:3] == '@SQ':
                contig, contig_len = contig_len_re.findall(line)[0]
                contig = contig.split('_')[0]
                contig_lens[contig] = int(contig_len)
        else:
            # Not in header
            line_split = line.split('\t')
            if (int(line_split[1]) / 128) == 1:
                read_id = line_split[0] + "_2"
            else:
                read_id = line_split[0] + "_1"

            # Ignore reads which are not in the subset
            if read_id in all_reads:

                no_mapping_bit = (((((int(line_split[1]) % 128) % 64) % 32) % 16) % 8) / 4
                if no_mapping_bit == 1:
                    not_mapped.add(read_id)
                else:
                    contig = line_split[2]
                    contig = contig.split('_')[0]
                    if contig in MAG_contigs:
                        MAG_mapped.add(read_id)
                    elif contig_lens[contig] >= 1000:
                        long_mapped.add(read_id)
                    else:
                        short_mapped.add(read_id)

    print("Not Mapped\tShort Mapped\tLong Mapped\tMAG mapped")
    print("{}\t{}\t{}\t{}".format(len(not_mapped), len(short_mapped),
        len(long_mapped), len(MAG_mapped)))

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=usage)
    parser.add_argument('subset_reads')
    parser.add_argument('mag_contigs')
    args = parser.parse_args()

    main(args)


'''
Described at PyMOL wiki: http://www.pymolwiki.org/index.php/lisica

'''

import os
import stat
import urllib.request, urllib.error, urllib.parse
from urllib.request import urlopen
from urllib.error import URLError, HTTPError
import zipfile
import tempfile
import shutil
import json
import sys
import platform
from distutils.dir_util import copy_tree
from tkinter import *
from tkinter.ttk import *
import webbrowser
import time
import tkinter.messagebox

from threading import Thread
import contextlib

HOME_DIRECTORY=os.path.expanduser('~')
LISICA_DIRECTORY=os.path.join(HOME_DIRECTORY,".lisicagui")
versionFile = os.path.join(LISICA_DIRECTORY, "version.txt")

class Configuration:
    def __init__(self):

        self.system = platform.system()
        self.machine = platform.machine()
        self.architecture = platform.architecture()
        import struct
        self.python_bit = 8 * struct.calcsize("P")
        self.python_version = platform.python_version_tuple()

    def is_os_64bit(self):
        if self.system == 'Windows':
            return platform.architecture()[0] == "64bit"
        else:
            return platform.machine().endswith('64')

    def exe_File(self):
        if self.system == 'Windows':
            if self.is_os_64bit():
                exe_filename = "LiSiCAx64.exe"
            else:
                exe_filename = "LiSiCAx86.exe"

        elif self.system == 'Linux':
            exe_filename = "lisica"
        else:
            print("The plugin might not be compatible with your machine")
            exe_filename = "lisica"
        return exe_filename

class UpdateCheck:

    def __init__(self):
        self.firstVersionURL = "http://insilab.org/files/lisica-plugin/version.txt"
        self.firstArchiveURL = "http://insilab.org/files/lisica-plugin/archive.zip"
        self.currentVersion=""
        self.latestVersion = ""

    def installationFailed(self):
        global running, status
        status = "failed"
        running = False

    def deleteTmpDir(self):
        try:
            shutil.rmtree(self.tmpDir)
            print("deleted temporary ", self.tmpDir)
        except:
            print("error : could not remove temporary directory")

    def createTmpDir(self):
        try:
            self.tmpDir= tempfile.mkdtemp()
            print("created temporary ", self.tmpDir)
        except:
            print("error : could not create temporary directory")
            self.installationFailed()
        self.zipFileName=os.path.join(self.tmpDir, "archive.zip")

    def downloadInstall(self):
        try:
            print("Fetching plugin from the git server")
            urlcontent = urlopen(self.firstArchiveURL, timeout=5)
            zipcontent = urlcontent.read()
            LiSiCAzipFile = open(self.zipFileName, 'wb')
            LiSiCAzipFile.write(zipcontent)
        except HTTPError as e1:
            print("HTTP Error:", e1.code, e1.reason)
            self.installationFailed()
        except URLError as e2:
            print("URL Error:", e2.reason)
            self.installationFailed()
        except Exception as e:
            print("Error: download failed, check if http://insilab.org website is up...")
            self.installationFailed()
        finally:
            try:
                LiSiCAzipFile.close()
            except:
                pass
            try:
                urlcontent.close()
            except:
                pass

    def extractInstall(self):
        # this must be called before import LisicaGUI, otherwise
        # rmtree will fail on NFS systems due to open log file handle
        try:
            with contextlib.closing(zipfile.ZipFile(self.zipFileName, "r")) as LiSiCAzip:
                for member in LiSiCAzip.namelist():
                    masterDir = os.path.dirname(member)
                    break
                LiSiCAzip.extractall(self.tmpDir)
            # copy new
            copy_tree(os.path.join(self.tmpDir, masterDir, ".lisicagui"), LISICA_DIRECTORY)
        except:
            print("installation of lisicagui failed")
            self.installationFailed()

    def firstUpgrade(self):
        return not os.path.isdir(LISICA_DIRECTORY)

    def upgrade(self):

        #try:
        #    shutil.rmtree(LISICA_DIRECTORY)
        #except Exception, e:
        #    print e

        self.createTmpDir()
        self.downloadInstall()
        self.extractInstall()
        self.deleteTmpDir()

        # add executable properties
        configure=Configuration()
        exe_filename=configure.exe_File()
        exe_path=os.path.normpath(os.path.join(LISICA_DIRECTORY,"bin",exe_filename))
        st = os.stat(exe_path)
        os.chmod(exe_path, st.st_mode | stat.S_IEXEC)

        sys.path.append(os.path.normpath(os.path.join(LISICA_DIRECTORY, "modules")))

        self.writeToVersionTxt(self.latestVersion)

        print("Upgrade finished successfully!")
        global running, status
        status = "start"
        running = False

    #
    # read current version of probis from version.txt file
    #
    def findCurrentVersion(self):

        if os.path.isfile(versionFile):
            with open(versionFile, 'r') as myFile:
                lines = myFile.readlines()
            if len(lines) == 1:
                self.currentVersion = lines[0].strip()
            else:
                date = lines[len(lines)-1].split('\t')[2]
                t = time.strftime("%d/%m/%Y")

                tmpTime1 = date.split('/')
                tmpTime2 = t.split('/')
                if int(tmpTime2[2]) > int(tmpTime1[2]) or int(tmpTime2[1]) > int(tmpTime1[1]) or int(tmpTime2[0]) > int(tmpTime1[0])+15:
                    self.currentVersion = lines[0].strip()
                else:
                    self.currentVersion = (lines[len(lines)-1].split('\t')[0]).strip()

    #
    # get info about latest version
    #
    def findLatestVersion(self):
        try:
            # from insilab git server
            versionFile = urllib.request.urlopen(self.firstVersionURL, timeout=5)
            self.latestVersion = versionFile.read().strip()

            if len(self.latestVersion) > 6:
                self.latestVersion = ""

            print("l1 = ", self.latestVersion)

        except HTTPError as e1:
            print("HTTP Error:", e1.code, e1.reason)
        except URLError as e2:
            print("URL Error:", e2.reason)
        except Exception as e:
            print("URL Error: Is Insilab webpage (http://insilab.org) down?")

    #
    # yes or no update window
    #
    def updateWindow(self):

        self.window=Tk()
        self.window.title("Software Update")

        frame = Frame(self.window)
        frame.pack()

        Label(frame, text="A new LiSiCA GUI version is available. Do you want to update?", anchor=CENTER).pack(pady=(20,10), padx=30, fill=BOTH, expand=1)

        versionFrame = Frame(self.window)
        versionFrame.pack(fill=BOTH, expand=1, padx=15, pady=(0,10))

        Label(versionFrame, text="Current version: ").grid(column=0, row=0, sticky=W, padx=(30,0), pady=(10,0))
        Label(versionFrame, text="Latest version: ").grid(column=0, row=1, sticky=W, padx=(30,0), pady=(0,10))

        Label(versionFrame, text=self.currentVersion).grid(column=1, row=0, sticky=W, padx=10, pady=(10,0))
        Label(versionFrame, text=self.latestVersion).grid(column=1, row=1, sticky=W, padx=10, pady=(0,10))
        Label(versionFrame, text="For more information about software update, go to:", font=("Times",10)).grid(column=0, columnspan=2, row=3, padx=30)
        urlLabel = Label(versionFrame, text="http://www.insilab.org/lisica", font=("Times",10),foreground="blue",underline=True)
        urlLabel.grid(row=4, column=0, columnspan=2, pady=(0, 10), padx=30, sticky=W)
        urlLabel.bind("<Button-1>", self.open_url)

        self.checkRemindMe = 0
        Checkbutton(self.window, command=self.setCheckRemindMe, text="Do not ask me again").pack(fill=BOTH, expand=1, padx=60)

        buttonsFrame = Frame(self.window)
        buttonsFrame.pack(fill=BOTH, expand=1, padx=30, pady=(10,20))
        Button(buttonsFrame, text='Cancel', command=self.cancelButton).grid(row=0, column=0, padx=(200, 20), pady=(0,10))
        Button(buttonsFrame, text='Update', command=self.updateButton).grid(row=0, column=1, pady=(0,10))

        self.window.bind('<Return>', self.updateButton)
        self.window.protocol('WM_DELETE_WINDOW', self.cancelButton)

        self.window.mainloop()

    def open_url(self, e):
        try:
            webbrowser.open_new(r"http://www.insilab.org/lisica")
        except:
            print("Error: Could not open the website.")

    def setCheckRemindMe(self):
        if self.checkRemindMe == 0:
            self.checkRemindMe = 1
        else:
            self.checkRemindMe = 0

    def cancelButton(self):
        if self.checkRemindMe  == 1:
            self.writeToVersionTxt(self.latestVersion, True)
        self.window.quit()

    def updateButton(self, event=None):
        global status
        status = "update"
        self.window.quit()

    #
    # write to version.txt file
    #
    def writeToVersionTxt(self, version, reminder=False):

        if reminder:
            with open(versionFile, 'a') as myfile:
                myfile.write(version+"\t later \t"+time.strftime("%d/%m/%Y")+"\n")

        else:
            with open(versionFile, 'w') as myfile:
                myfile.write(version+"\n")

def internetOn():
        try:
            urllib.request.urlopen('http://www.google.com',timeout=1)
            return True
        except:
            pass
        return False

def showManualDlInfo():
    tkinter.messagebox.showinfo("Installation failed.", "To download and manually install LiSiCA GUI please visit our website http://www.insilab.org/lisica/download.php .")
    #pass

def run():

    print("Initialising LiSiCA ...")

    global running, updateObj, status
    status = "start"

    try:
        sys.path.remove('')
    except:
        pass

    updateObj = UpdateCheck()

    if updateObj.firstUpgrade():
        if not internetOn():
            status = "no-internet"
        else:
            updateObj.findLatestVersion()
            updateObj.upgrade()
    else:
        updateObj.findCurrentVersion()

        if internetOn():
            updateObj.findLatestVersion()

            if updateObj.currentVersion == "UPDATE NOW":
                updateObj.upgrade()

            elif updateObj.latestVersion != updateObj.currentVersion:
                status = "check-update"

    running = False

class FuncThread(Thread):
    def __init__(self, target, *args):
        self._target = target
        self._args = args
        Thread.__init__(self)

    def run(self):
        self._target(*self._args)

class Logo(Frame):

    def __init__(self, parent, txt):
        Frame.__init__(self, parent)

        self.parent = parent

        # move window to center
        self.update_idletasks()
        w = self.winfo_screenwidth()
        h = self.winfo_screenheight()
        size = tuple(int(_) for _ in self.parent.geometry().split('+')[0].split('x'))
        x = w/2 - size[0]/2
        y = h/2 - size[1]/2
        self.parent.geometry("%dx%d+%d+%d" % (size + (x, y)))

        s = Style()
        s.configure("My.TFrame", background='#BFBFBF')

        frame=Frame(self.parent, style="My.TFrame")
        frame.pack(fill=BOTH, expand=1)

        raw_data = """R0lGODlhgACAAOf/ACUAAyoBABUAWDUCADwBAA0OCwoGZBcPB0cCABoPEDEKAzkMBB0UFVQGABYXFRUXJxcPdCkPQxoPgB0a
                      ElcKDRcVYBscGmIKAD0VBEMTCSQdFDMbEl0RAiUeK0gYCCEjIU0YEnAPD1MbCikcfiQcmywmIR4dpTAmGCcaqi4Ww2UZBSgl
                      TlkfCGEcFSkrKDMhcTcnKk8jDEQlGSoikmwdAywsLysmbi0rOFsiC0sjOzctHVMmEEkkR1EmHjMuKk8oFCsg0CgjxWUkClwn
                      FC4vTislujAyLy8mslUpLGwnBWUnIncmADgvZS4rrDw0KmYrFDY3M1IrYDouiVcxH0E3JXYrAEI2MkQ1Rks2Ki0t3GwvEnop
                      J3EuFGwwGW4xDqkeJHUxCTw9O3swBHUxEZolHbQeHmU1I38yAMAcIDgy33M1GNAaInw2B3k1GkQ9a4I1CkNDQX03EFs/MHc5
                      Gzs262A/K0c2zkhBZlZCO05FOjo493U8IoM8FU9JQ4A/HEVEoHRCKktMSYdAGIRCGHNGLfYhJ4xDHFBRTYNHIVNRVWhOQpFH
                      GZBHIF1USYlNJlhMwVtTc5VLI4ZPMGpWPlhZVn5SOpZNK5tQKHpZRF5gXYtXNF1an2pffGRlY4tdQnBkVJVdOWpnX35mWmNg
                      6mllv4ppU5RoRIZrWXZwZ3luhJZsU3V3dIt1W4h2Z5p1WZV6Z35/fYR+d4WAc5Z9b5mGbqOEZpWJZqSIdY6NipOKraCNfZqR
                      l6KTfJ2UhaeUeK+XfJublKebia6chqSau6udmq2jhKOkoamklrOhl7CkjLKmlK+ourSrkrerjLSumrStpq2vrLuunLyykrq0
                      oLy1p8K1o7q2tcC3ncK5n8S5msG6pr67rMS+qca9tsq9q8fBrcrBp8DCv8fBwMrEsMfGvdDHrdPGs8/JtNLMt9zMtNvNu9PO
                      ztjSvdbTxNXTyt/XvN/Yw9fZ097ay97Z19/bzN/f3OTg0d3j5ejk1e/o1Ojq5+/s3PDy7/fz5Pr8+f///yH+EUNyZWF0ZWQg
                      d2l0aCBHSU1QACH5BAEKAP8ALAAAAACAAIAAAAj+AP8JHEiwoMGDCBMqXMiwocOHECNKnEixosWLGDNq3Mixo8ePIEOKHEmy
                      pMmTKFOqXMmypcuXMGPKnEmzps2bOHPq3Mmzp8+fQIMKHUq0qNGjSJMqXcq0qdOnNuPwGcTTkCE+PvlcNcTIUqSaVgXxWSTI
                      ZxxNtTwh4mrJEkxHkRgZQmSqlqayPeNEisYN2StNhiJdusQykmFEkl4h83bNEda8fH6dQ4eO2y1PXAd/lehWIqNLVj350kbZ
                      3C0+b36+MTVOnbt27boJM+Vo0eDOCdtaGsy7N2GFbRnRDdYN9mtypt6A+QlG0LV28OjBg9fOXDJVtW8bbNt7t+/v2y3+CVel
                      zBz06NSvoQYKRkwtdNHpyZN3XJmr7L8N796v+/Yl799tFokliyCiCjLjtOPOfPRIh04tYiwHlBiOJChPg9JRh0431/HmHXff
                      XTKgV/8B6N8ljriiDDfoQHehPQ22w40kYlQRVBVi/IKOO/FpOI43ybgCymf9tSWYYUgi6dWAR4r4XySg1JKMNuTABs989KEj
                      TI1DLQHKNy3C1s6Gs13SFXeMJKnmmnGJyGYki1hiijAsWjkmN5pwKRSOwoxDDjrndDONK4sYsggjiKap5iJxIclomooaFqma
                      cjHiyjTf/InOOMKAsURRS5hCDTfcUCOMJloZWmiirCIK5yL+hcZ6KCOHwkprq7SSJYgmxWhDKjWmLJFEUUmwEYwzzvCCyBuC
                      WOVsrbcaKq2z1D5rla20ViuIIG8goguyvnh61BKeJENLHGy8wQcfzVZbaLXUDmKVvO7Ca8i226LrBy3JeLIEDeOywUocYrDB
                      xrrsbntvswwLMsggWkVsiLypprrwvfeuKxYf6YrhBytsfIqUGCSTbLBU7CaMb8JTXYXwyxFHjO/ML7PRXskiH1WyyQfD7PPP
                      6v4sNMJvGMxGjSTnDOrOBRtc9NCoRf3G1FNLHTTQqBnNtNJELVEjjmAY/UYcUx9ctNMGo0b2IOnyQfbYqI1dNNVxn330zmcM
                      axT+yTjynC7VRceBiCaeaIJIuk6XbfbbZyPiiSeSIILu2EaH3fcZXAt1Bt88o/s2G5IEI846pIsTjCRoH5w42WBIosvopFuj
                      C+pG28y0jaBuXnLtcscxyzr3BC/8PeSo8je6apPNhiviDC/8Oq/UfjPOR+nuNxtkizHLPM7r4/0965QC+BttlK3KOt6nP/w8
                      rWg9vZ5FiWE99k6L4Qn6wosDDC6xPHOPPuJAHeOm5glx6GMdz+gFKnCBv/+tg0aVkx/8iCJBkoHhDNiLAxiIkT59GCMW4hCH
                      EzTQCHHwgxjjm9ozAAiMdXRDBxpwgjH4kT5dhM1gJcPcUaqAwabJrVv+JtQHP54BDH7MIw8n0EAMm+eJt6GrFPewxgzdgUQY
                      luAZNORHN+agtbslxWRNM9gZJDEPfvDjHrgQYix0QAUdwBAL80DG31S4DlQIERVspIIPTtAHIfLjgU0L2+a+eLSToYsNnriH
                      GZ8RC3/MQw5UiCQVkhiLdSzrDeSaxydiYcQ8SNKNJbCGP4xIo0OSDClVSGUY0eaJevDDH8DwASqC0UY2+sAHffAB9M5QtFmI
                      owQ+iAUwasnGRpQAGKOcR57QVTC+4e4nSehbyW5WOzFIwh6vBIYSNXCCbnKTGHXEhRzfMIZqxOIA2+zmCXRwjHks0B/+WAcg
                      cHi3naUSKNL+nGbtzrAHccDTGBPYpkCB4Q5U9KEb5eODOPqAToEqsYWfMMYou0GwQnLua11iWjPTBQZkvNIaE5jAAUZ6gAL4
                      IA9WKEAo+bAERIC0ACQdaQGc0AcnTMCf/AhG08TgtSos4Z5FGQRPNUoyU7iyHiWAqQZK4AQqoCIWfVDEJ64xC1fUAhmNyCoW
                      sOCEEkyACk5QqSuV2TevLcFrSJFGLRDBU596jaeDeEY7yNGLXiDjGtXwRjfM4Q10pCMd3egGZYqTjsGOQxvPIEYvYjELesxj
                      GpJAl0/PEAdT/IIZRvFGORjzC1MgYhCDU8UvmpHX1qjDSux4x3mmw1oesXY6sGH+BzzYwQ51dMMb2tDGNYTxi18IoxncGIc5
                      pkEUb/wVHebgq261odlyoEMdsn2tdKZL3QbFB0PoyRBr36GOdJgDuX397l/LMZRq/PW86VAHZZ6rDnW8lrUYim+D8CHf+qLn
                      te+YLW3be97uakMoxvWuOdLbXtrS9r3ZrW996StfBL/WwPDobjrKcVzi/kQZuiVuOfj7jnSk9sPRfS+MsGsPeMBoxPYo8XTy
                      q+J3pFa/tD0vef9xjWtIoyjgQO95DQzh91bXxNeVDjtSbGIex1jHE57wNZCCjXI4+clJJrCREYyhFGP3vUbmr4wn/ORsMNnJ
                      4ABHOcL8ZCf71cM9fq/+PBw8W/3KuMzNLXM5mmGUZIQZG9nIczP2LI08k5nC0E0zm/Nr4O6COcx5zkaNs4GNMIf5xkXhhTB8
                      QemDULoZ2RAzZQrcZjbzWL1jzkYzKn2QZiSjGcoQBkns8RJaNEPMzkWzbA8cXSOn4xxjbgYvbKGSfQxkH6z+Rz7wMZ2WeGAS
                      xWj0OGKNDiPz+K+4Bgc2ilGKIaAEHvjYh6/3kY9+aNvb+8CHsTGggDoUoxrjEPNk2CFrdjwXUOgIdTEw4QERWLsk9tC2vsG9
                      D34Pm9gpYQELRJCBBSAbG8v+RjnOwfDjFvYc6QbHNJpRCoE/wQtaWLW+N87xb/eDHim5+BP+cPAERSjiFM1o9DfAoXCGM3wc
                      4/jGyrHRjFYoQhSA8EIc4uAFkWS7Hh3neD7yAWyVjGEMXvDDK2zRik+4utEsd/Q3Ih7midMCE63QBS80wQY/DGIMH6HH0Ike
                      dI7jY9gpGcPO+XCLZCAjGLrIOjOwQXepg0MbdJfGqEVxCl0ggxm/cIzbOmKPbOPj8EPX9+HDrfjDwwMlY2jDzl3hjGhMIxrK
                      iHsxmCENbEyD7qDHhjSkUQxbfEIXyrB8NGiBsDZoRB6Hj73sZR/u2dM3JTqPAyiYMY1q5HYawZiFLYox+uIbvxmlxwQtgjGN
                      3zvDFeri+UWwbfvqVz/FuN/5IHz+0Xtf5TYaurDF8JvB+eIzA/m+YIUodBGN3GqjGtNIhiXcFgeLDFk+KcZH4fVv/djDCB0p
                      AQYapAqWl1vecIDaoAy00AqSJgqKUAd1oAitUAy+YHqzgAzMhYDVEA2vIBVxoDcSwQ7SkWLykGImeIIoaIIglxJJoC/JQA58
                      cYDe8CPVIAyt0AoyAAAHAAA8CAB1YAui8ArBcA3c4A3RQA7foA3ToAyOgD0SEhHcwFryQFslWGImaGImWIIXQh3ngHtHYwrz
                      EA+woA0w5w3m8CPRcAtYAAAK0IYBoAA8OAmsEAzRMIPfAAvxUA/vFw2uYDQg6BCEMA3s0A7jQAu0cCX+awZkCIYl08EOJIEG
                      BQEGAkgLwBAO/GAMygBzyWUO2hAMZvCGbRiKAKAIdKhZ0TBD4kAMv1cMbAMGwwKJDgEIwUULgPAE0sBmDgYdjjgShYAGITAQ
                      SRAhiJAMznAM4QANYYAKZBgPz9AXihCKbTgAbYgL7rAN04AKYQAN4fAMefV+zpAnbJAEIYAGhdAQT4AJt0AIWvAEryAmrAUd
                      qwVb7eBuJVEGvgiMkmgKzuB7lBAGLmABlGCJH6QNtEBu0BgAVjBD4UAJFuACYZAJZfh+g4Ij4ogGZcAQXbAHe6AGaqAFgCCI
                      gygmIikmBgaAG8EP4YAQIUABFDAQVQAGVfD+Cs2nDYfgAjVQAH0QC7CQCc5QDtNwCgapAAuABaeQCbAAVQVQAy5wCArnDdyg
                      hLxwNFXAARTwiwdhif8ACHOwlVupBbTgcs1GW/PobICyEfoADPEQDoeAEF9AEKnEBrwgDb6CCh/gAsHwXTGnXocVDKIwCScn
                      DNVQDQOGDsHgAx+ACmWIW9NQDH6QSjTQlgdxCOEQD8CgD57AlXNQCd/ADLwAJgZGDu62Xi+3EdBQD+GwCpSQED7gllUQB8Iw
                      k4lgBOXxXezFX8p1DWJGYPwVDUaQCGe4WbqlDIiQSjGwmghBCasQDvXwCnOwB22wB7zgCpUwDS53DuRQnS73DR3+AQtwQAlG
                      gBCBEAYf4JJV4AfK0HzLoAc2IFzrVWD7xWMuVmjqZQN6sAy35ZTT8I2pVAJhEAgI4QOUAAeigJmVQAhmoAxIKHPYeQ7fcA7/
                      5RGBYAQOcBBhAAdQYAEu2VK8NwxpAASpsImbBl3vMKIkSqKFVlipAAR0MAwH+JTfuAQsYAFQAAdhYBA/4ABGEAhy0Jx7MAdq
                      sAevWQyswAwK2qAM+g3O8BGHYAQ10JAdQBB/AAcu8AEOMKX/4FOIwAzDQAd6QAJuwJ5+9VyzRaIrBg8jul/q5QYkoAcrip/O
                      UAkb4AIOUJdw8AcEAQP/WANGgAdb2QbNyQqsQAhPwAr+3CBzhrpyIGGaFlAABfABNmACaRAEaZAFT8qoH6CUcGAEWHAHdBAE
                      RYACTJBc7cluqTWiZmqi+1VYTIACRRAEdHAHoWAE/lgDJYABBfAPHZAFkZoGJmADJbABDGAB4RANlcCVe6AFWiCT0zAq31Co
                      SfoR/AAMmVAQJqAHRQABBlAQBeACEWoBNfACnFABEjAD1CCq6YVmJWqq8dle6kANMyABFZAKL9CkOeoCGEADKjAQBgABRaAH
                      JsADXeCjXUAJReQKxuoKtOAJxUANyzp6IAEN0IALBlEERxAE2WoQRuACLpAAqDANw5ALmzADgaANtPlX8VmqZyqf3xAIM7D+
                      CbnAorJQly7gA0nwh/9gAEFwBFLQBRypBnNgBrgADbOwlT9qBmagC9PweZglEnCAEBIAAQnBAAkwBXSYgS5gBFCACuZwDu7w
                      DOVgYCaKDs/gDrWFClCQsWf4I96ACg5gAYSwBPlKED0AASPAsxzpo3NQB3Lgp1vZBYTwLfm5tCuRBSmQEFZQAkLAfbnVC6EQ
                      oQ4QkPUADb3gngbWC6W5kDgaCKEQDGrLDb1gBHAwBjTAAQTxBEOQAkfQBXbrs2rQBj5LtIDAd6f2EkSwAoZbAiygrNrAuBmb
                      AHCwCrCAC8rAroHGDs6AC7CwCnCQAFcbCr0QkZ8LB0kwugPxBKb+SwRX0LPaS7Q+2wXIagvJABNQ4AIJEQY+4AGV4AzNxwyB
                      8AFQcJecSBrqRbztxVyUEQxQ8AGBwAxq6wyyIKsqELf/YL1aMAQuYAXam8AcqbpagAkxAQeBAAUTahAQbARTGwy7QAqjIAWh
                      AHOauF7rda7HVRrmEApSMAqkQAzcELM5CgekOwRD8ATrqAFQEAh4YLc4zLNmgKwzEQZhYAS3ahA/LKFG0ASPQAdZQALTcFua
                      KKog/MTIlVzcQAJZQAeP0ARELKs9EMMELAMFIKthoLpizMA8HBNlsAZbYAQW4AAOUAMjMBB64AZyWgAK0AGQSgckcAekMoMz
                      uIkgSpv+yeXBMHcHJEAHvHoDh2ABDOACbmAHPBAFOWADNcDGFuADW/AFZEAG65hxM9GLFLAGBPEAreqvQCABA9EAAYwCqgwJ
                      GahX5bBswuXHmwjLHgwJqowCysAMwSAEDSACEAAE1eqpHbADMTwEaEAB5GgT9njMBzGpKCAABcEBF4AETAAJvtfKB9jEsZy2
                      goyAnMAEu4B5mNAADRDDEYACupoD1lvM/4DMFmkTK4kQJCABplwQDSDNpVB51+wrRZjNgvzPnfuU2hANzvAKHNDLpju3EjAC
                      MGwQVSkUQVDP9swBKvAKzBAN17zHMvgjZai2TinQShgNzKALLUDOBCEBQdD+FE0AtQdxzyowC8ygvvssgx9N06QC0pfnDLrw
                      BA2AAAUBAU3QFBeaEOTcAq2gDJU3k973lKTCz+4nkdFwDLTQAj5tEDLKFDRKvgmBAPeMCcEQ00mr1E/tfmHtDMyQDKXQAASw
                      AAfhkE2rFIEQCFd7ECKwAANAAFz9BK0QDMdQeZYX1r0Hf89A0MeQDK1gBgSw1hkgAgL8Dxkb10cRufrQCeMbkBJLEEkgBARn
                      13jdAEpQCrpADEiNLASNLM6gDMnQC6dgBggwAAuQASCgAkLABXqDCwvpAlDQCfpQmkNxicYAC4waCPEQrQIhBE/ABVwgBEMg
                      Ah7A2Z1tBphwCsvpFwzUHXeYYAYgQACuvdhDMNvIzQVdUETxEAiMCgvGMENDgQurYBAQO8BHd3TI/QSaDQIFpwADcNd4DQL6
                      Td/aHQADgAH1Ztxc0AbI3QZjYAbtXRCrcNlL8QRH1wYQHuFqwAXyvdkBcOEYjuE9uAAgIOAR/uFtMAV18ARQUbptwAcnjuIS
                      PnIZAIcAoOE8eOEvHgBsmAEk17ofvi4QDnYlLhBDgOMQ3gXWiwMeMAA9GOMzTuMZ/uI9OACLbdwB+5yuS+I9PhBD0AL3BhIt
                      gOVV3uVe/uVgHuZiPuZkXuZmfuZonuZqvuYVERAAOw=="""

        photo=PhotoImage(master=self, data=raw_data)
        display=Label(frame, image=photo, background="#BFBFBF")
        display.image=photo
        display.pack(ipady=10, ipadx=50, fill=BOTH)

        Label(frame, text=txt, anchor=E, font = "Fixedsys 10 bold").pack(ipady=0, ipadx=0, fill=BOTH)

        global running
        running = True

        if txt == "Starting Software ":
            t = FuncThread(run)
        else:
            global updateObj
            #shutil.rmtree(LISICA_DIRECTORY)
            t = FuncThread(updateObj.upgrade)
        t.daemon = True
        t.start()

        while running:
            self.parent.update_idletasks()
            self.parent.update()

        self.parent.destroy()

def main():
    root = Tk()
    root.overrideredirect(1)
    root.geometry("250x170")
    Logo(root, "Starting Software ")

    global updateObj, status

    if status == "no-internet":
        #pass
        tkinter.messagebox.showinfo("Communication Error", "No Internet connection available. Please make sure that your device is connected to the Internet.")

    if status == "check-update":
        status = "start"
        updateObj.updateWindow()
        updateObj.window.destroy()
        if status == "update":
            root = Tk()
            root.overrideredirect(1)
            root.geometry("250x170")
            Logo(root, "Updating Software ")

    if status == "start":
        print("Python version: "+platform.architecture()[0])
        sys.path.append(os.path.normpath(os.path.join(LISICA_DIRECTORY, "modules")))
        del status, updateObj # remove global variables
        import LisicaGUI
        LisicaGUI.main()

    elif status == "failed":
        showManualDlInfo()

def __init__(self):
    self.menuBar.addmenuitem('Plugin', 'command', 'LiSiCA', label='LiSiCA', command=lambda s=self: main())


import os
import glob
import random

#        1  2  3  4  5  6  7  8  9 10
MD = (0, 1, 0, 0, 2, 1, 1, 3, 2, 0, 0)

while 1:
    dates = [list() for _ in range(11)]
    for image in glob.glob('*.jpg'):
        dates[random.randint(1, 10)].append(image)
    if all(len(images) >= MD[date] for date, images in enumerate(dates)):
        break

for date, images in enumerate(dates):
    for rank, image in enumerate(images):
        newname = f'OCT_200001{date:02}_0000{rank:02}.jpg'
        print(date, rank, image, newname)
        os.rename(image, newname)


from config import connection_string
import pyodbc
from data import DeepLearning

connection = pyodbc.connect(connection_string)
sql = connection.cursor()

def GetAll():
    try:
        sql.execute("SELECT * FROM DeepLearning")
        rows = sql.fetchall()
        data = []
        for row in rows:
            deep_learning = DeepLearning(DeepID=row.DeepID.lower(), DeepName=row.DeepName)
            data.append(deep_learning.dict())
        return data
    except Exception as e:
        print("An error occurred while executing GetAll:", str(e))
        return None

def GetByID(id):
    try:
        sql.execute(f"SELECT * FROM DeepLearning WHERE DeepID = '{id}'")
        row = sql.fetchone()
        if row:
            machine_learning = DeepLearning(DeepID=row.DeepID.lower(), DeepName=row.DeepName)
            data = machine_learning.dict()
        else:
            data = None
        return data
    except Exception as e:
        print("An error occurred while executing GetByID:", str(e))
        return None

def Create(name):
    try:
        query = "INSERT INTO DeepLearning (DeepName) VALUES (?)"
        values = (name,)
        sql.execute(query, values)
        connection.commit()
        count = sql.rowcount
        if count > 0:
            return True
        else:
            return False
    except Exception as e:
        print("An error occurred while executing Create:", str(e))
        return False

def Update(id, name):
    try:
        query = "UPDATE DeepLearning SET DeepName = ? WHERE DeepID = ?"
        values = (name, id)
        sql.execute(query, values)
        connection.commit()
        count = sql.rowcount
        if count > 0:
            return True
        else:
            return False
    except Exception as e:
        print("An error occurred while executing Update:", str(e))
        return False

def Delete(id):
    try:
        query = "DELETE FROM DeepLearning WHERE DeepID = ?"
        values = (id,)
        sql.execute(query, values)
        connection.commit()
        count = sql.rowcount
        if count > 0:
            return True
        else:
            return False
    except Exception as e:
        print("An error occurred while executing Delete:", str(e))
        return False


# -*- coding: utf8 -*-
import sys
import os
from enum import Enum

#Tags = Enum('tags','index syl begin end accent lf0')
class Tags(Enum):
	index = 0
	syl = 1
	begin = 2
	end = 3
	accent = 4
	lf0 = 5
#Usage: filename log
def check_toks(toks):

	if len(toks) != 6:
		return -1
	if float(toks[2]) == float(toks[3]) == 0.0:
		return -1

def check_F0_exist(F0s):

	for F0 in F0s:
		if F0.isnumeric() == False:
			return -1
	return 0

def get_dur(toks):

	dur = float(toks[Tags.end.value]) - float(toks[Tags.begin.value])
	return dur

def get_lf0s_avg(toks):

	lf0s = toks[Tags.lf0.value].split("-")
	lf0s_avg = 0

	for lf0 in lf0s:
		lf0s_avg += float(lf0)
	return float(lf0s_avg)/float(len(lf0s))

def get_lf0s_slope_avg(toks):

	lf0s = toks[Tags.lf0.value].split("-")
	lf0s_slopes = []
	lf0s_slope_avg = 0

	for lf0 in lf0s:
		if lf0s.index(lf0) + 1 < len(lf0s):
			lf0_slope = abs(int(lf0) - int(lf0s[lf0s.index(lf0) + 1]))
			lf0s_slopes.append(lf0_slope)
			lf0s_slope_avg += lf0_slope

	return float(lf0s_slope_avg)/float(len(lf0s_slopes))

def cal_avg_dur(durs):

	avg_dur = 0
	for phone_dur in durs:
		avg_dur += phone_dur

	return float(avg_dur)/float(len(durs))

def cal_avg_lf0s_avg(lf0s_avgs):

	avg_lf0s_avg = 0
	for phone_lf0_avg in lf0s_avgs:
		avg_lf0s_avg += phone_lf0_avg

	return float(avg_lf0s_avg)/float(len(lf0s_avgs))

def cal_avg_lf0s_slope_avg(lf0s_slope_avgs):

	avg_lf0s_slope_avg = 0
	for phone_lf0s_slope_avg in lf0s_slope_avgs:
		avg_lf0s_slope_avg += phone_lf0s_slope_avg

	return float(avg_lf0s_slope_avg)/float(len(lf0s_slope_avgs))

if __name__ == '__main__':

	#out = open('test.txt', mode='w', encoding='utf8')
	with open('Utt_00001.SylF0', mode='r', encoding='utf-16-le') as file:
		syls = []
		lf0s_avg = []
		durs = []
		lf0s_slope_avg = []
		avg_dur = 0
		avg_lf0s_avg = 0
		avg_lf0s_slope_avg = 0
		i = 0
		emotion = 0
		lines = file.readlines()
		lines[0] = lines[0][1:] # remove BOM
		while i < len(lines):

			line = lines[i].strip()
			toks = [x for x in line.split(" ") if x != '']
			if check_toks(toks) == -1:
				break
			syls.append(toks[Tags.syl.value])
			durs.append(get_dur(toks))
			lf0s_avg.append(get_lf0s_avg(toks))
			lf0s_slope_avg.append(get_lf0s_slope_avg(toks))
			i += 1

		avg_dur = cal_avg_dur(durs)
		avg_lf0s_avg = cal_avg_lf0s_avg(lf0s_avg)
		avg_lf0s_slope_avg = cal_avg_lf0s_slope_avg(lf0s_slope_avg)
		i = 0
		print('syls' + '\t \t' + 'durs' + '\t' + 'lf0s_avg[i]'  + '\t' + 'lf0s_slope_avg')
		while i < len(lines):

			#if durs[i] > avg_dur * 1.25 or durs[i] < avg_dur * 0.75:
			#	emotion = 1

			if lf0s_avg[i] > (avg_lf0s_avg * 1.25):
				emotion = 1

			if lf0s_slope_avg[i] > (avg_lf0s_slope_avg * 1.25):
				emotion = 1

			if emotion == 1:
				print(syls[i] + '\t*\t' + str(round(durs[i],4)) + '\t' + str(round(lf0s_avg[i],4))  + '\t' +  str(round(lf0s_slope_avg[i],4)))
				emotion = 0
			else:
				print(syls[i] + '\t \t' + str(round(durs[i],4)) + '\t' + str(round(lf0s_avg[i],4))  + '\t' +  str(round(lf0s_slope_avg[i],4)))

			i += 1


from bs4 import BeautifulSoup
import datetime
import time
import requests
import json

"""
Get initial count of potential valid listing for reference before running main scrapper parse_watch_data.py
"""

start_time = time.time()
date_today = datetime.date.today().isoformat() # YYYY-MM-DD date object format for our Watch Model
scrap_list = ['126200', '126300', '126234', '126334']
total_scrap_count = 0

for ref_num in scrap_list:
    listing_scrap_count = 0

    with open(f'{ref_num}.html') as html_file:
        soup = BeautifulSoup(html_file, 'lxml')
        # Grab each listing on search result page
        for listing in soup.find_all('div', class_='media-flex-body d-flex flex-column justify-content-between'):
            # Find price
            price = None
            price_text = listing.find('div', class_='text-xlg text-bold').text.strip().replace('$', '').replace(',', '')
            if not price_text.isdigit(): # Check is here in case the seller puts "Price on request" and skips the listing
                continue
            price = price_text

            # Find production_year
            production_year = None
            divs = listing.find_all('div', class_='row-direct')
            for div in divs:
                if 'Year of production' in div.text:
                    production_year = div.find('strong').text.strip()
                    break

            # Find condition
            condition = None
            divs = listing.find_all('div', class_='row-direct')
            for div in divs:
                if 'Condition:' in div.text:
                    condition = div.find('strong').text.strip()
                    break

            # Box_and_Papers will be True by default as those are the only listings we'll filter for on scrapped website
            # Seller_location will be United States by default as those are the only listings we'll filter for on scrapped website

            listing_title = listing.find('div', class_='text-lg text-ellipsis p-r-5 m-b-2').text.strip().lower()
            if 'diamond' in listing_title or 'pearl' in listing_title: # Skip listings with diamond or pearl dials/bezels as prices heavily skew intended scrapped data
                continue

            if price == None or production_year == None or condition == None: # Skip listing if these fields were not found
                continue

            listing_scrap_count += 1

            scrap_data = {
            'ref_num': ref_num,
            'price': price,
            'production_year': production_year,
            'condition': condition,
            'box_and_papers': True,
            'seller_location': 'United States',
            'date_scrapped': date_today
            }

    total_scrap_count += listing_scrap_count
    print(str(listing_scrap_count) + f' listings scrapped for reference number: {ref_num}.')
    print()

end_time = time.time()
elapsed_time = end_time - start_time

print(f"Total parsing & POST elapsed time: {int(elapsed_time // 60)} minutes, {int(elapsed_time % 60)} seconds. \nTotal scrapped count: {total_scrap_count}.")


#!/usr/bin/python
import os
import sys

def path_up_to_last(a_last, a_inclusive=True, a_path=os.path.dirname(os.path.realpath(__file__)), a_sep=os.path.sep):
    return a_path[:a_path.rindex(a_sep + a_last + a_sep) + (len(a_sep)+len(a_last) if a_inclusive else 0)]

components_dir = path_up_to_last("components")

sys.path.append(os.path.join(components_dir, "utils"))
from imports import *

for imp in ["args", "get_token", "rdm_traits"]:
    exec(import_cmd(components_dir, imp))

session = requests.Session()

def create_region(a_region_name, a_site_id, a_server_config, a_verticies_file, a_headers, a_discoverable=False, a_color="#ff00ff", a_coordinate_system="wgs84", a_opacity=50, a_haul_mixin=None):
    with open(a_verticies_file) as json_file:
        region_verticies = RegionRdmTraits.Vertices(a_data=json.load(json_file))

    region_rdm_bean = RegionRdmTraits.post_bean_json(a_region_name=a_region_name, a_id=str(uuid.uuid4()), a_verticies=region_verticies, a_discoverable=a_discoverable, a_color=a_color, a_coordinate_system=a_coordinate_system, a_opacity=a_opacity, a_haul_mixin=a_haul_mixin)

    url = "{0}/rdm_log/v1/site/{1}/domain/sitelink/events".format(a_server_config.to_url(), a_site_id)
    logging.debug ("Upload RDM to {}".format(url))

    data_encoded_json = { "data_b64" : base64.b64encode(json.dumps(region_rdm_bean).encode('utf-8')).decode('utf-8') }
    logging.debug("Region RDM payload: {}".format(json.dumps(region_rdm_bean, indent=4)))

    response = session.post(url, headers=a_headers, data=json.dumps(data_encoded_json))
    response.raise_for_status()
    if response.status_code == 200:
        logging.info("Region created.")
        logging.debug ("create region returned {0}\n{1}".format(response.status_code, json.dumps(response.json(), indent=4)))
    else:
        logging.info("Region creation unsuccessful. Status code {}: '{}'".format(response.status_code, response.text))

def main():
    script_name = os.path.basename(os.path.realpath(__file__))

    # >> Argument handling
    args = handle_arguments(a_description=script_name, a_arg_list=[arg_log_level, arg_site_id, arg_rdm_region_name, arg_rdm_region_verticies_file])
    # << Argument handling

    # >> Server & logging configuration
    server = ServerConfig(a_environment=args.env, a_data_center=args.dc)
    logging.basicConfig(format=args.log_format, level=int(args.log_level))
    logging.info("Running {0} for server={1} dc={2} site={3}".format(script_name, server.to_url(), args.dc, args.site_id))
    # << Server & logging configuration

    headers = headers_from_jwt_or_oauth(a_jwt=args.jwt, a_client_id=args.oauth_id, a_client_secret=args.oauth_secret, a_scope=args.oauth_scope, a_server_config=server)

    create_region(a_region_name=args.rdm_region_name, a_site_id=args.site_id, a_server_config=server, a_verticies_file=args.rdm_region_verticies_file, a_headers=headers)

if __name__ == "__main__":
    main()


#!/usr/bin/python3
import random
from sys import stdout

W, H = 1920, 1080

B = W * H

def variables(x, y):
    rotr = lambda y: x >> y | x << B - y & (1 << B) - 1
    p, q = rotr(y), rotr(B - y)
    return p ^ q, p & q

def transform(x):
    A, B = variables(x, 1)
    C, D = variables(x, W - 1)
    E, F = variables(x, W)
    G, H = variables(x, W + 1)

    I = B | D
    J = F | H
    K = A ^ C

    x |= K ^ E ^ G
    x &= (I | J) ^ (K & (E | G) | (A & C ^ E & G) | (I | F & H) & (B & D | J))

    return x

header = bytes(f"P4\n{W} {H}\n", "ascii")
data = random.randint(0, 2**B)

while True:
    stdout.buffer.write(header)
    stdout.buffer.write(data.to_bytes(B // 8, "big"))
    data = transform(data)


"""

Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.

Example 1:

Input: nums = [1,2,3,1]
Output: true
Example 2:

Input: nums = [1,2,3,4]
Output: false
Example 3:

Input: nums = [1,1,1,3,3,4,3,2,4,2]
Output: true

Constraints:

1 <= nums.length <= 10^5
-10^9 <= nums[i] <= 10^9
Accepted
1,782,462
Submissions
2,919,757

"""

class Solution:
    def containsDuplicate(self, nums: list) -> bool:
        d = dict()
        for num in nums:
            if num in d:
                return True
            d[num] = 1

        return False


""" Create a Spotify playlist with the tracks from A3.30"""
from dotenv import load_dotenv
import bs4
import requests
import spotipy
from spotipy.oauth2 import SpotifyOAuth

def get_a3_30():
    """Get the tracks and artists from the Antena 3 website."""
    url = "https://media.rtp.pt/antena3/"
    result = requests.get(url, timeout=5)
    soup = bs4.BeautifulSoup(result.content, "html.parser")
    a330_url = soup.find("a", "results-right").get("href")

    result = requests.get(a330_url, timeout=5)
    soup = bs4.BeautifulSoup(result.content, "html.parser")

    tracks = [p.text for p in soup.find_all("p", "vote-track-name")]
    artists = [span.text for span in soup.find_all("span", "vote-band-title")]

    return tracks, artists

def create_playlist(tracks, artists):
    """Create a playlist on Spotify with the given tracks and artists."""
    scope = [
        "playlist-read-private",
        "playlist-modify-private",
        "playlist-read-collaborative",
        "playlist-modify-public",
    ]
    auth_manager = SpotifyOAuth(scope=scope)
    sp = spotipy.Spotify(auth_manager=auth_manager)

    playlists = sp.current_user_playlists()
    for playlist in playlists["items"]:
        if playlist["name"] == "A3.30":
            break

    track_ids = []
    for track, artist in zip(tracks, artists):
        print(f"Searching for {track} - {artist}")
        new_track = sp.search(q=f"{artist} {track}")["tracks"]["items"][0]
        track_ids.append(new_track["id"])

    sp.playlist_add_items(playlist["id"], items=track_ids)

def main():
    load_dotenv()
    tracks, artists = get_a3_30()
    create_playlist(tracks, artists)

if __name__ == "__main__":
    main()


import re

CYRYLICA ='абвгдеёжзийклмнопрстуфхцчшщъыьэюяєіїґ'
LATINICA =("a", "b", "v", "g", "d", "e", "e", "j", "z", "y", "j", "k", "l", "m", "n", "o", "p", "r", "s", "t", "u",
               "f", "h", "ts", "ch", "sh", "sch", "", "y", "", "e", "yu", "ja", "je", 'i', "ji", "g")

TRANS = {}
for c, l in zip(CYRYLICA, LATINICA):
    TRANS[ord(c)] = l
    TRANS[ord(c.upper())] = l.upper()

def normalize(name):
    t_name = name.translate(TRANS)
    return re.sub(r'[^\w.]', '_', t_name)


hall_capacity = int(input())
tickets_profit = 0
command = input()

while command != 'Movie time!':

    people = int(command)
    if people > hall_capacity:
        print('The cinema is full.')
        break

    tickets_profit += people * 5

    if people % 3 == 0:
        tickets_profit -= 5

    hall_capacity -= people

    command = input()

else:
    print(f'There are {hall_capacity} seats left in the cinema.')

print(f'Cinema income - {tickets_profit} lv.')


from collections import OrderedDict

import numpy as np
import pylab as plt
import h5py
from mne.viz import plot_topomap
from scipy.signal import hilbert, firwin2, filtfilt
from scipy.fftpack import rfft, irfft, fftfreq

from pynfb.serializers.xml_ import get_lsl_info_from_xml
from pynfb.signals.rejections import Rejections
from pynfb.signal_processing.filters import SpatialRejection
import seaborn as sns

from pynfb.widgets.helpers import ch_names_to_2d_pos

def dc_blocker(x, r=0.99):
    # DC Blocker https://ccrma.stanford.edu/~jos/fp/DC_Blocker.html
    y = np.zeros_like(x)
    for n in range(1, x.shape[0]):
        y[n] = x[n] - x[n-1] + r * y[n-1]
    return y

def fft_filter(x, fs, band=(9, 14)):
    w = fftfreq(x.shape[0], d=1. / fs * 2)
    f_signal = rfft(x, axis=0)
    cut_f_signal = f_signal.copy()
    cut_f_signal[(w < band[0]) | (w > band[1])] = 0
    cut_signal = irfft(cut_f_signal, axis=0)
    return cut_signal

def get_power2(x, fs, band, n_sec=5):
    n_steps = n_sec * fs
    w = fftfreq(n_steps, d=1. / fs * 2)
    print(len(range(0, x.shape[0] - n_steps, n_steps)))
    pows = [2*np.sum(rfft(x[k:k+n_steps])[(w > band[0]) & (w < band[1])]**2)/n_steps
            for k in range(0, x.shape[0] - n_steps, n_steps)]
    return np.array(pows)

def get_power(x, fs, band):
    #w = 0.
    #taps = firwin2(1000, [0, band[0]-w, band[0], band[1], band[1]+w, fs/2], [0, 0, 1, 1, 0, 0], nyq=fs/2)
    #x = filtfilt(taps, [1.], x)
    x = fft_filter(x, fs, band)
    return x**2

def load_rejections(f, reject_alpha=True):
    rejections = [f['protocol1/signals_stats/left/rejections/rejection{}'.format(j + 1)][:] for j in range(2)]
    alpha = f['protocol1/signals_stats/left/rejections/rejection2_topographies'][:]
    ica = f['protocol1/signals_stats/left/rejections/rejection1_topographies'][:]
    rejection = rejections[0]
    if reject_alpha:
        rejection = np.dot(rejection, rejections[1])
    return rejection, alpha, ica

def get_info(f, drop_channels):
    labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
    print('fs: {}\nall labels {}: {}'.format(fs, len(labels), labels))
    channels = [label for label in labels if label not in drop_channels]
    print('selected channels {}: {}'.format(len(channels), channels))
    n_protocols = len([k for k in f.keys() if ('protocol' in k and k != 'protocol0')])
    protocol_names = [f['protocol{}'.format(j+1)].attrs['name'] for j in range(n_protocols)]
    print('protocol_names:', protocol_names)
    return fs, channels, protocol_names

def get_protocol_power(f, i_protocol, fs, rejection, ch, band=(9, 14), dc=False):
    raw = f['protocol{}/raw_data'.format(i_protocol + 1)][:]
    x = np.dot(raw, rejection)[:, ch]
    if dc:
        x = dc_blocker(x)
    return get_power2(x, fs, band)

def get_colors():
    p_names = [ 'Right', 'Left',  'Rest', 'FB', 'Closed', 'Opened', 'Baseline']
    cm = sns.color_palette('Paired', n_colors=len(p_names))
    c = dict(zip(p_names, [cm[j] for j in range(len(p_names))]))
    return c

if __name__ == '__main__':
    import h5py

    pilot_dir = ['C:\\Users\\Nikolai\\Downloads', 'D:\\Mu'][1]
    subjs = [
        ['pilot_5Days_Rakhmankulov_Day1_02-27_17-27-34',
         'pilot5days_Rakhmankulov_Day2_02-28_14-45-36',
         'pilot5days_Rakhmankulov_Day3_03-01_12-51-41',
         'pilot5days_Rakhmankulov_Day4_03-02_17-26-28',
         'pilot5days_Rakhmankulov_Day5_03-04_09-24-16'],

        ['pilot_Cherlenok_Day1_02-27_12-51-56',
         'pilot5days_Cherlenok_Day2_02-28_15-50-08',
         'pilot5days_Cherlenok_Day3_03-01_16-24-03',
         'pilot5days_Cherlenok_Day4_03-02_16-45-43',
         'pilot5days_Cherlenok_Day5_03-03_12-35-46'],

        ['pilot5Days_Plackhin_Day1_02-27_16-04-08',
         'pilot5days_Plackhin_Day2_02-28_11-43-07',
         'pilot5days_Plackhin_Day3_03-01_11-45-35',
         'pilot5days_Plackhin_Day4_03-02_11-20-43',
         'pilot5days_Plackhin_Day5_03-03_14-29-52'],

        ['pilot5days_Skotnikova_Day1_02-27_15-15-18',
         'pilot5days_Skotnikova_Day2_02-28_14-06-40',
         'pilot5days_Skotnikova_Day3_03-01_10-44-28',
         'pilot5days_Skotnikova_Day4_03-02_13-33-55',
         'pilot5days_Skotnikova_Day5_03-03_13-42-04'],

        ['Dasha1_02-20_09-01-29',
        'Dasha2_02-22_15-53-52',
        'Dasha3_02-23_14-21-42',
        'Dasha4_02-24_16-59-08'],
        ['Andrey1_03-07_19-05-02']][-1:]
    drop_channels = [['AUX', 'A1', 'A2'], ['M_left', 'M_right']][1]
    channel = 'C4'
    alpha_band = (9, 14)
    theta_band = (3, 6)
    cm = get_colors()

    for subj in subjs[:]:
        fg = plt.figure(figsize=(30, 6))
        for j_s, experiment in enumerate(subj):
            with h5py.File('{}\\{}\\{}'.format(pilot_dir, experiment, 'experiment_data.h5')) as f:
                rejections, top_alpha, top_ica = load_rejections(f, reject_alpha=True)
                fs, channels, p_names = get_info(f, drop_channels)
                ch = channels.index(channel)

                # collect powers
                powers = OrderedDict()
                pow_theta = []
                for j, name in enumerate(p_names):
                    pow = get_protocol_power(f, j, fs, rejections, ch, alpha_band, dc=True)
                    if name == 'FB':
                        pow_theta.append(get_protocol_power(f, j, fs, rejections, ch, theta_band, dc=True).mean())
                    if name == 'Filters':
                        powers['{}. Closed'.format(j+1)] = pow[:len(pow)//2]
                        powers['{}. Opened'.format(j+1)] = pow[len(pow)//2:]
                    elif name == 'Rotate':
                        powers['{}. Right'.format(j+1)] = pow[:len(pow)//2]
                        powers['{}. Left'.format(j+1)] = pow[len(pow)//2:]
                    else:
                        powers['{}. {}'.format(j+1, name)] = pow

                # plot rejections
                for j_t in range(top_ica.shape[1]):
                    ax = fg.add_subplot(5, top_ica.shape[1]*len(subj), top_ica.shape[1]*len(subj)*3 + top_ica.shape[1]*j_s + j_t + 1)
                    ax.set_xlabel('ICA{}'.format(j_t+1))
                    labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                    channels = [label for label in labels if label not in drop_channels]
                    pos = ch_names_to_2d_pos(channels)
                    plot_topomap(data=top_ica[:, j_t], pos=pos, axes=ax, show=False)
                for j_t in range(top_alpha.shape[1]):
                    ax = fg.add_subplot(5, top_alpha.shape[1]*len(subj), top_alpha.shape[1]*len(subj)*4 + top_alpha.shape[1]*j_s + j_t + 1)
                    ax.set_xlabel('CSP{}'.format(j_t+1))
                    labels, fs = get_lsl_info_from_xml(f['stream_info.xml'][0])
                    channels = [label for label in labels if label not in drop_channels]
                    pos = ch_names_to_2d_pos(channels)
                    plot_topomap(data=top_alpha[:, j_t], pos=pos, axes=ax, show=False)

                # plot powers
                norm = powers['{}. Baseline'.format(p_names.index('Baseline') + 1)].mean()
                #norm = np.mean(pow_theta)
                print('norm', norm)
                ax = fg.add_subplot(2, len(subj), j_s + 1)
                for j_p, (name, pow) in enumerate(powers.items()):
                    print(name)
                    ax.plot([j_p], [pow.mean()/norm], 'o', c=cm[name.split()[1]], markersize=10)
                    c = cm[name.split()[1]]
                    ax.errorbar([j_p], [pow.mean()/norm], yerr=pow.std()/norm,  c=c, ecolor=c)
                plt.setp(ax.xaxis.get_majorticklabels(), rotation=70)
                ax.set_xticks(range(len(powers)))
                ax.set_xticklabels(powers.keys())
                ax.set_ylim(0, 2)
                ax.set_xlim(-1, len(powers))
                ax.set_title('Day {}'.format(j_s+1))

        fg.savefig(' '.join(subj[-1].split('_')[:2])+channel+'.png', dpi=300)
        plt.show()


# V0
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        wordset = set(wordList)
        bfs = collections.deque()
        bfs.append((beginWord, 1))
        while bfs:
            word, length = bfs.popleft()
            if word == endWord:
                return length
            for i in range(len(word)):
                for c in "abcdefghijklmnopqrstuvwxyz":
                    newWord = word[:i] + c + word[i + 1:]
                    if newWord in wordset and newWord != word:
                        wordset.remove(newWord)
                        bfs.append((newWord, length + 1))
        return 0

# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82903681
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        wordset = set(wordList)
        bfs = collections.deque()
        bfs.append((beginWord, 1))
        while bfs:
            word, length = bfs.popleft()
            if word == endWord:
                return length
            for i in range(len(word)):
                for c in "abcdefghijklmnopqrstuvwxyz":
                    newWord = word[:i] + c + word[i + 1:]
                    if newWord in wordset and newWord != word:
                        wordset.remove(newWord)
                        bfs.append((newWord, length + 1))
        return 0

### Test case : dev

# V1'
# https://leetcode.com/problems/word-ladder/discuss/40729/Compact-Python-solution
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        wordList = set(wordList)
        queue = collections.deque([[beginWord, 1]])
        while queue:
            word, length = queue.popleft()
            if word == endWord:
                return length
            for i in range(len(word)):
                for c in 'abcdefghijklmnopqrstuvwxyz':
                    next_word = word[:i] + c + word[i+1:]
                    if next_word in wordList:
                        wordList.remove(next_word)
                        queue.append([next_word, length + 1])
        return 0

# V1''
# https://leetcode.com/problems/word-ladder/discuss/157376/Python-(BFS)-tm
class Solution(object):
    def ladderLength(self, start, end, arr):
        arr = set(arr) #avoid TLE
        q = collections.deque([(start, 1)])
        visted = set()
        alpha = string.ascii_lowercase  #'abcd...z'
        while q:
            word, length = q.popleft()
            if word == end:
                return length

            for i in range(len(word)):
                for ch in alpha:
                    new_word = word[:i] + ch + word[i+1:]
                    if new_word in arr and new_word not in visted:
                        q.append((new_word, length + 1))
                        visted.add(new_word)
        return 0

# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/82903681
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        wordset = set(wordList)
        if endWord not in wordset:
            return 0
        visited = set([beginWord])
        chrs = [chr(ord('a') + i) for i in range(26)]
        bfs = collections.deque([beginWord])
        res = 1
        while bfs:
            len_bfs = len(bfs)
            for _ in range(len_bfs):
                origin = bfs.popleft()
                for i in range(len(origin)):
                    originlist = list(origin)
                    for c in chrs:
                        originlist[i] = c
                        transword = "".join(originlist)
                        if transword not in visited:
                            if transword == endWord:
                                return res + 1
                            elif transword in wordset:
                                bfs.append(transword)
                                visited.add(transword)
            res += 1
        return 0

# V1'
# https://leetcode.com/problems/word-ladder/solution/
# IDEA : BFS
# time complexity : O(M**2 * N)
# space complexity : O(M**2 * N)
from collections import defaultdict
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """

        if endWord not in wordList or not endWord or not beginWord or not wordList:
            return 0

        # Since all words are of same length.
        L = len(beginWord)

        # Dictionary to hold combination of words that can be formed,
        # from any given word. By changing one letter at a time.
        all_combo_dict = defaultdict(list)
        for word in wordList:
            for i in range(L):
                # Key is the generic word
                # Value is a list of words which have the same intermediate generic word.
                all_combo_dict[word[:i] + "*" + word[i+1:]].append(word)

        # Queue for BFS
        queue = collections.deque([(beginWord, 1)])
        # Visited to make sure we don't repeat processing same word.
        visited = {beginWord: True}
        while queue:
            current_word, level = queue.popleft()
            for i in range(L):
                # Intermediate words for current word
                intermediate_word = current_word[:i] + "*" + current_word[i+1:]

                # Next states are all the words which share the same intermediate state.
                for word in all_combo_dict[intermediate_word]:
                    # If at any point if we find what we are looking for
                    # i.e. the end word - we can return with the answer.
                    if word == endWord:
                        return level + 1
                    # Otherwise, add it to the BFS Queue. Also mark it visited
                    if word not in visited:
                        visited[word] = True
                        queue.append((word, level + 1))
                all_combo_dict[intermediate_word] = []
        return 0

# V1''
# https://leetcode.com/problems/word-ladder/solution/
# IDEA : Bidirectional Breadth First Search
# time complexity : O(M**2 * N)
# space complexity : O(M**2 * N)
from collections import defaultdict
class Solution(object):
    def __init__(self):
        self.length = 0
        # Dictionary to hold combination of words that can be formed,
        # from any given word. By changing one letter at a time.
        self.all_combo_dict = defaultdict(list)

    def visitWordNode(self, queue, visited, others_visited):
        current_word, level = queue.popleft()
        for i in range(self.length):
            # Intermediate words for current word
            intermediate_word = current_word[:i] + "*" + current_word[i+1:]

            # Next states are all the words which share the same intermediate state.
            for word in self.all_combo_dict[intermediate_word]:
                # If the intermediate state/word has already been visited from the
                # other parallel traversal this means we have found the answer.
                if word in others_visited:
                    return level + others_visited[word]
                if word not in visited:
                    # Save the level as the value of the dictionary, to save number of hops.
                    visited[word] = level + 1
                    queue.append((word, level + 1))
        return None

    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """

        if endWord not in wordList or not endWord or not beginWord or not wordList:
            return 0

        # Since all words are of same length.
        self.length = len(beginWord)

        for word in wordList:
            for i in range(self.length):
                # Key is the generic word
                # Value is a list of words which have the same intermediate generic word.
                self.all_combo_dict[word[:i] + "*" + word[i+1:]].append(word)

        # Queues for birdirectional BFS
        queue_begin = collections.deque([(beginWord, 1)]) # BFS starting from beginWord
        queue_end = collections.deque([(endWord, 1)]) # BFS starting from endWord

        # Visited to make sure we don't repeat processing same word
        visited_begin = {beginWord: 1}
        visited_end = {endWord: 1}
        ans = None

        # We do a birdirectional search starting one pointer from begin
        # word and one pointer from end word. Hopping one by one.
        while queue_begin and queue_end:

            # One hop from begin word
            ans = self.visitWordNode(queue_begin, visited_begin, visited_end)
            if ans:
                return ans
            # One hop from end word
            ans = self.visitWordNode(queue_end, visited_end, visited_begin)
            if ans:
                return ans

        return 0

# V2
# Time:  O(n * d), n is length of string, d is size of dictionary
# Space: O(d)
from string import ascii_lowercase
class Solution(object):
    def ladderLength(self, beginWord, endWord, wordList):
        """
        :type beginWord: str
        :type endWord: str
        :type wordList: List[str]
        :rtype: int
        """
        distance, cur, visited, lookup = 0, [beginWord], set([beginWord]), set(wordList)

        while cur:
            next_queue = []

            for word in cur:
                if word == endWord:
                    return distance + 1
                for i in range(len(word)):
                    for j in ascii_lowercase:
                        candidate = word[:i] + j + word[i+1:]
                        if candidate not in visited and candidate in lookup:
                            next_queue.append(candidate)
                            visited.add(candidate)
            distance += 1
            cur = next_queue

        return 0


# Из двух случайных чисел, одно из которых четное, а другое нечетное,
# определить и вывести на экран нечетное число.

a = 11
b = 12
message = None

if b % 2 == 0 and a % 2 == 0:
    message = 'Both numbers are even'
elif b % 2 == 0:
    message = f'{b} is even'
elif a % 2 == 0:
    message = f'{a} is even'
else:
    message = "There aren't any even numbers"
print(message)


import pygame
import random
import sys

# Initialize Pygame
pygame.init()

# Set up the screen
screen_width, screen_height = 800, 400
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Dino Jump")

# Colors
white = (255, 255, 255)
black = (0, 0, 0)

# Dino attributes
dino_width, dino_height = 50, 50
dino_x, dino_y = 100, screen_height - dino_height
dino_y_velocity = 0

# Obstacle attributes
obstacle_width, obstacle_height = 20, 40
obstacle_x = screen_width
obstacle_y = screen_height - obstacle_height
obstacle_speed = 2

# Gravity
gravity = 0.5

# Game variables
score = 0
game_over = False

# Fonts
font = pygame.font.Font(None, 36)
game_over_font = pygame.font.Font(None, 72)

def draw_dino(x, y):
    pygame.draw.rect(screen, black, [x, y, dino_width, dino_height])

def draw_obstacle(x, y):
    pygame.draw.rect(screen, black, [x, y, obstacle_width, obstacle_height])

def display_score(score):
    score_text = font.render("Score: " + str(score), True, black)
    screen.blit(score_text, (10, 10))

def display_game_over():
    game_over_text = game_over_font.render("Game Over", True, black)
    screen.blit(game_over_text, (screen_width // 2 - 150, screen_height // 2 - 36))

# Function to generate a random obstacle position
def random_obstacle_y():
    return random.randint(screen_height - obstacle_height - 20, screen_height - obstacle_height)

# Game loop
while not game_over:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE] and dino_y == screen_height - dino_height:
        dino_y_velocity = -10

    dino_y += dino_y_velocity

    # Apply gravity
    dino_y_velocity += gravity

    # Collision with ground
    if dino_y >= screen_height - dino_height:
        dino_y = screen_height - dino_height
        dino_y_velocity = 0

    # Move the obstacle and reset if it goes off-screen
    obstacle_x -= obstacle_speed

    if obstacle_x < 0:
        obstacle_x = screen_width
        obstacle_y = random_obstacle_y()
        score += 1

    # Check for collision
    if dino_x + dino_width > obstacle_x and dino_x < obstacle_x + obstacle_width:
        if dino_y + dino_height > obstacle_y:
            game_over = True

    # Clear the screen
    screen.fill(white)

    draw_dino(dino_x, dino_y)
    draw_obstacle(obstacle_x, obstacle_y)
    display_score(score)

    if game_over:
        display_game_over()

    pygame.display.update()

# Quit Pygame
pygame.quit()
sys.exit()