from tkinter import *
from matplotlib import pyplot as plt
from pylab import plot,show,xlabel, ylabel
x=0
window =Tk()
window.geometry("300x300")
window.title("bar graph")

firstVar =StringVar()
secondVar=StringVar()
thirdVar=StringVar()
fourVar=StringVar()
fiveVar=StringVar()
sixVar=StringVar()

firstInput =Entry(window,textvariable=firstVar)
firstInput.grid(row=0,column=0,padx=5,pady=5,ipady=5)
firstBtn = Button(window,text="Thiba",command=lambda:LoadFirstGraph())
firstBtn.grid(row=0,column=1,pady=5,padx=5)

secondInput =Entry(window,textvariable=secondVar)
secondInput.grid(row=2,column=0,padx=5,pady=5,ipady=5)
secondBtn = Button(window,text="Karaba",command=lambda:LoadSecondGraph())
secondBtn.grid(row=2,column=1,pady=5,padx=5)

thirdInput =Entry(window,textvariable=thirdVar)
thirdInput.grid(row=3,column=0,padx=5,pady=5,ipady=5)
thirdBtn = Button(window,text="Wamumu",command=lambda:LoadThirdGraph())
thirdBtn.grid(row=3,column=1,pady=5,padx=5)

fourInput =Entry(window,textvariable=fourVar)
fourInput.grid(row=4,column=0,padx=5,pady=5,ipady=5)
fourBtn = Button(window,text="Nderwa",command=lambda:LoadFourGraph())
fourBtn.grid(row=4,column=1,pady=5,padx=5)

fiveInput =Entry(window,textvariable=fiveVar)
fiveInput.grid(row=5,column=0,padx=5,pady=5,ipady=5)
fiveBtn = Button(window,text="T3-T9",command=lambda:LoadFiveGraph())
fiveBtn.grid(row=5,column=1,pady=5,padx=5)

sixInput =Entry(window,textvariable=sixVar)
sixInput.grid(row=6,column=0,padx=5,pady=5,ipady=5)
sixBtn = Button(window,text="W3-W5",command=lambda:LoadSixGraph())
sixBtn.grid(row=6,column=1,pady=5,padx=5)

def LoadFirstGraph():
    global firstVar
    global x
    y=float(firstVar.get())
    x+=1
    plt.bar(x,y,label="Thiba",color="red")
    plt.xlabel("x-axis")
    plt.ylabel("y-axis")
    plt.legend()
    plt.show()

def LoadSecondGraph():
    global secondVar
    global x
    y=float(firstVar.get())
    x+=1
    plt.bar(x,y,label="Karaba",color="green")
    plt.xlabel("x-axis")
    plt.ylabel("y-axis")
    plt.legend()
    plt.show()

def LoadThirdGraph():
    global thirdVar
    global x
    y=float(thirdVar.get())
    x+=1
    plt.bar(x,y,label="Wamumu",color="blue")
    plt.xlabel("x-axis")
    plt.ylabel("y-axis")
    plt.legend()
    plt.show()

def LoadFourGraph():
    global fourVar
    global x
    y=float(fourVar.get())
    x+=1
    plt.bar(x,y,label="Nderwa",color="black")
    plt.xlabel("x-axis")
    plt.ylabel("y-axis")
    plt.legend()
    plt.show()

def LoadFiveGraph():
    global fiveVar
    global x
    y=float(fiveVar.get())
    x+=1
    plt.bar(x,y,label="T3-T9",color="yellow")
    plt.xlabel("x-axis")
    plt.ylabel("y-axis")
    plt.legend()
    plt.show()

def LoadSixGraph():
    global sixVar
    global x
    y=float(sixVar.get())
    x+=1
    plt.bar(x,y,label="W3-W5",color="brown")
    plt.xlabel("x-axis")
    plt.ylabel("y-axis")
    plt.legend()
    plt.show()

window.mainloop()


"""
A self-dividing number is a number that is divisible by every digit it contains.

For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0.

Also, a self-dividing number is not allowed to contain the digit zero.

Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible.

Example 1:
Input:
left = 1, right = 22
Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
Note:

The boundaries of each input argument are 1 <= left <= right <= 10000.
"""

class Solution:
    def selfDividingNumbers(self, left, right):
        """
        :type left: int
        :type right: int
        :rtype: List[int]
        """
        result = []
        while left <= right:
            flag = True
            l = [int(i) for i in list(str(left))]
            for i in range(len(l)):
                if l[i] == 0:
                    flag = False
                    break
                if left % l[i] == 0:
                    l[i] = 0
            if sum(l) == 0 and flag == True:
                result.append(left)
            left +=1
        return result


from math import sqrt
from random import randrange

# test de primalité naif
def prime(n):
  if n <= 1 or not n & 1:
    return False

  f = 3
  while f <= int(sqrt(n)):
    if n % f == 0:
      return False
    f += 2

  return True

# test de primalité évolué (Fermat)
# primes : bases à tester (supposés premiers)
# example : fermatPrime(1267650600228402790082356974917)
# 1267650600228402790082356974917 = 1125899906842679 * 1125899906842723
def fermatPrime(n, primes = (2, 3)):

  #fermat
  if n in primes:
    return True

  if n <= 1 or not n & 1:
    return False

  for p in primes:
    if pow(p, n - 1, n) != 1:
      return False

  f = 3
  while f <= int(sqrt(n)):
    if n % f == 0:
      return False
    f += 2

  return True

# miller rabin, _mrpt_num_trials ; number of bases to test
def MillerRabinPrime(n, _mrpt_num_trials = 5):
    assert n >= 2
    # special case 2
    if n == 2:
        return True
    # ensure n is odd
    if n % 2 == 0:
        return False
    # write n-1 as 2**s * d
    # repeatedly try to divide n-1 by 2
    s = 0
    d = n-1
    while True:
        quotient, remainder = divmod(d, 2)
        if remainder == 1:
            break
        s += 1
        d = quotient
    assert(2**s * d == n-1)

    # test the base a to see whether it is a witness for the compositeness of n
    def try_composite(a):
        if pow(a, d, n) == 1:
            return False
        for i in range(s):
            if pow(a, 2**i * d, n) == n-1:
                return False
        return True # n is definitely composite

    for i in range(_mrpt_num_trials):
        a = randrange(2, n)
        if try_composite(a):
            return False

    return True # no base tested showed n as composite


from PIL import Image
import os, glob
import numpy as np
import random, math
import keras
from keras.utils.np_utils import to_categorical
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D

image_dir = "10types"
size = 200
data_augmentation = True
batch_size = 32
epochs = 200

'''
- X_train(image)
- Y_train(label)
- X_test(image)
- Y_test(label)
- categories
'''

categories = []

dir_list = os.listdir(image_dir)
for index, dir_name in enumerate(dir_list):
  if dir_name == '.DS_Store' :
    continue
  categories.append(dir_name)

num_classes = len(categories)
print(num_classes)

train_data = []

for idx, category in enumerate(categories):
  try :
    print("---", category)
    each_dir = image_dir + "/" + category
    files = glob.glob(each_dir + "/*")
    for i, f in enumerate(files):
      img = Image.open(f)
      img = img.convert("RGB")
      img = img.resize((size, size))
      data = np.asarray(img)
      train_data.append([data, idx])

  except:
    print("SKIP : " + category)

random.shuffle(train_data)
X, Y = [],[]
for data in train_data:
  X.append(data[0])
  Y.append(data[1])

test_idx = math.floor(len(X) * 0.8)
xy = (np.array(X[0:test_idx]), np.array(X[test_idx:]),
      np.array(Y[0:test_idx]), np.array(Y[test_idx:]))

x_train, x_test, y_train, y_test = xy

X_train = x_train.reshape([-1, size, size, 3])
X_test = x_test.reshape([-1, size, size, 3])

# convert integer RGB values (0-255) to float values (0-1)
X_train = X_train.astype('float32') / 255
X_test = X_test.astype('float32') / 255

# convert class labels to one-hot encodings
Y_train = to_categorical(y_train, num_classes)
Y_test = to_categorical(y_test, num_classes)

'''

class model_definition:

    def __init__(self):
        self.num_classes = len(categories)
        self.X_train = X_train
        self.X_test = X_test
        self.Y_train = Y_train
        self.Y_test = Y_test

def model_train(self, input=None):
'''

model = Sequential()
model.add(Conv2D(32, (3, 3), padding='same',
                 input_shape=X_train.shape[1:]))
model.add(Activation('relu'))
model.add(Conv2D(32, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Conv2D(64, (3, 3), padding='same'))
model.add(Activation('relu'))
model.add(Conv2D(64, (3, 3)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes))
model.add(Activation('softmax'))

opt = keras.optimizers.rmsprop(lr=0.0001, decay=1e-6)

model.compile(loss='categorical_crossentropy',
              optimizer=opt,
              metrics=['accuracy'])

if not data_augmentation:
    print('Not using data augmentation.')
    model.fit(X_train, Y_train,
              batch_size=batch_size,
              epochs=epochs,
              validation_data=(X_test, Y_test),
              shuffle=True)
else:
    print('Using real-time data augmentation.')
    datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=0,  # randomly rotate images in the range (degrees, 0 to 180)
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=True,  # randomly flip images
        vertical_flip=False)  # randomly flip images

    # Compute quantities required for feature-wise normalization
    # (std, mean, and principal components if ZCA whitening is applied).
    datagen.fit(X_train)

    # Fit the model on the batches generated by datagen.flow().
    model.fit_generator(datagen.flow(X_train, Y_train,
                        batch_size=batch_size),
                        epochs=epochs,
                        validation_data=(X_test, Y_test),
                        workers=4)

score = model.evaluate(X_test, Y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])

json_string = model.to_json()
open('model_structure.json', 'w').write(json_string)
model.save(os.path.join('model.h5'))


class Isis:
    '''
        proposeSeq
        Input:
            p: Receiving process
        Output:
            Proposed Sequence Num
        Description:
            Receiving processes choose the maximum observed sequence number + 1
    '''
    counter = 0.0
    @staticmethod
    def proposeSeq(p):

        if p.proposedSeq is None:
            print("New Test: p.proposedSeq is None")
        if p.agreedSeq is None:
            print("New Test: p.agreedSeq is None")

        if p.proposedSeq is None or p.agreedSeq is None :
            print("p.proposeSeq is None. Proposing" + str("0.")+ str(p.pid))
            pNum = Isis.counter + (float(p.pid) * 0.1)
            p.proposedSeq = pNum
            p.agreedSeq = pNum
            Isis.counter += 1.0
            return pNum
        Isis.counter += 1.0
        p.proposedSeq += Isis.counter
        p.agreedSeq += Isis.counter
        return max(p.proposedSeq, p.agreedSeq) + Isis.counter

    '''
        chooseAgreedNum
        Inputs:
            arg1: Instance of Message class
            arg2: Instance of Message class
            *args: Instance of Message classes (3rd msg, 4th msg, ... 8th msg)
        Output:
            Agreed Number = maximum proposed number + 1  appended with process Num. eg) 3.1, 4.2
        Description:
            Sender chooses agreed priority. Append process num at the end
    '''
    @staticmethod
    # def chooseAgreedNum(arg1, arg2, *args):
    #     max = arg1.proposedSeq
    #     minSource = arg1.source
    #     for msg in args:
    #         if msg.proposedSeq > max:
    #             max = msg.proposedSeq
    #             minSource = msg.source
    #         elif msg.proposedSeq == max:
    #             max = msg.proposedSeq
    #             if msg.source < minSource:
    #                 minSource = msg.source
    #     result = float(str(max) + "." + str(minSource))

    #     return result + 1
    def chooseAgreedNum(l):
        arg1 = l[0]
        max = arg1.proposedSeq
        for msg in l[1:]:
            if msg.proposedSeq > max:
                max = msg.proposedSeq

        return max + 1.0

    '''
    storeMsg
        Inputs:
            p: Instance of process
            msg: instance of message
        Output:
            None
        Description:
            Store message in Queue(holdback)
    '''
    @staticmethod
    def storeMsg(p, msg):
        num = float(str(msg.proposedSeq) + "." + str(msg.source))
        p.holdback.append((num, msg))

    @staticmethod
    def printHoldback(p):
        result = list()
        for m in p.holdback:
            result.append(str(m.proposedSeq) + " " + str(m.source) +" "+str(m.amount))
        print("My Process #: " + str(p.pid) + "\n" + str(result))

    '''
    reorderMessages
        Inputs:
            p: Instance of process
            agreedMsg: agreedMsg
        Output:
            None
        Description:
            Upon receiving agreed priority, reorder messages
    '''
    # Not Used
    @staticmethod
    def reorderMessages(p, agreedMsg):
        if len(p.holdback) > 1:
            # Isis.printHoldback(p)
            tempHoldback = p.holdback
            sortedHoldback = []
            while tempHoldback:
                minimum = tempHoldback[0]  # arbitrary number in list
                for x in tempHoldback:
                    if x.proposedSeq == None:
                        """
                        """
                    elif minimum.proposedSeq == None:
                        """
                        """
                    elif x.proposedSeq < minimum.proposedSeq:
                        minimum = x
                sortedHoldback.append(minimum)
                tempHoldback.remove(minimum)
            p.holdback = sortedHoldback

            for msg in p.holdback:
                if msg.messageId == agreedMsg.messageId:
                    msg.isDeliverable = True

    '''
    deliverableMsgs
        Inputs:
            p: Instance of process
        Output:
            msgs: list of deliverable messages
        Description:
            Return deliverable messages. They are already reordered by agreed priority
    '''
    @staticmethod
    def deliverableMsgs(p):
        msgs = list()
        for msg in p.holdback:
            if msg[1].isDeliverable is True:
                msgs.append(p.holdback.pop(0)) # Pop from the front of the list
                continue
            break
        return msgs


# coding=utf-8
import socket

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(('0.0.0.0', 8000))
server.listen(10)
sock, addr = server.accept()
while True:
    data = sock.recv(1024)
    data = str(addr) + ':' + str(data)
    print(data.decode('utf-8'))
    returnData = raw_input()
    sock.send(returnData.encode('utf-8'))


from paraview.simple import *
#### disable automatic camera reset on 'Show'
paraview.simple._DisableFirstRenderCameraReset()

# create a new 'XML Structured Grid Reader'
filename1 = '/home/zetison/results/simra/Sula/ideal/M0/hist-1.vts'
filename2 = '/home/zetison/results/simra/Sula/ideal/init.vts'
filename1 = '/home/zetison/results/simra/Sula/met/M0/cont.vts'
filename2 = '/home/zetison/results/simra/Sula/met/init.vts'
#filename1 = '/home/zetison/results/simra/HuntHill_test_hx100_M0_DNS_uniRef/M0/hist-1.vts'
#filename2 = '/home/zetison/results/simra/HuntHill_test_hx100_M0_DNS_uniRef/init.vts'
#filename1 = '/home/zetison/results/simra/HuntHill_test_hx100_M0_DNS_uniRef/M0/boun-1.vts'
#filename2 = '/home/zetison/results/simra/HuntHill_test_hx100_M0_DNS_uniRef/boun-1.vts'
#filename1 = '/home/zetison/results/simra/HuntHill_test_hx100_M0_DNS_uniRef/M0/boun-1.vts'
#filename2 = '/home/zetison/results/simra/HuntHill_test_hx100_M0_DNS_uniRef/M0/hist-1.vts'

input1 = XMLStructuredGridReader(registrationName=filename1, FileName=[filename1])
input2 = XMLStructuredGridReader(registrationName=filename2, FileName=[filename2])

# create a new 'Append Attributes'
calculators = [AppendAttributes(registrationName='AppendAttributes1', Input=[input1, input2])]
counter = 0
for arr in input1.CellArrayStatus:
    counter += 1
    calculators.append(Calculator(registrationName='Calculator_'+arr, Input=calculators[counter-1]))
    calculators[counter].ResultArrayName = 'error_'+arr
    calculators[counter].AttributeType = 'Cell Data'
    calculators[counter].Function = 'abs('+arr+'-'+arr+'_input_1)'

for arr in input1.PointArrayStatus:
    counter += 1
    calculators.append(Calculator(registrationName='Calculator_'+arr, Input=calculators[counter-1]))
    calculators[counter].ResultArrayName = 'error_'+arr
    try:
        calculators[counter].Function = 'abs('+arr+'-'+arr+'_input_1)'
    except:#Assume vector input
        calculators[counter].Function = 'abs('+arr+'_X-'+arr+'_input_1_X)*iHat + '\
                                       +'abs('+arr+'_Y-'+arr+'_input_1_Y)*jHat + '\
                                       +'abs('+arr+'_Z-'+arr+'_input_1_Z)*kHat'

CreateLayout('Layout #2')
integrateVariables1 = IntegrateVariables(registrationName='IntegrateVariables1', Input=calculators[counter])
spreadSheetView1 = CreateView('SpreadSheetView')
integrateVariables1Display = Show(integrateVariables1, spreadSheetView1, 'SpreadSheetRepresentation')
layout2 = GetLayoutByName("Layout #2")
AssignViewToLayout(view=spreadSheetView1, layout=layout2, hint=0)


import time
import unittest
from selenium import webdriver
from selenium.webdriver.common.by import By
"""This module provides functionality to check multiple data from a web page."""

class OpenStreetMap(unittest.TestCase):
    """ acest modul are ca scop testarea functionaliatii dupa cautare a adreselor """
    SEARCH_BOX = By.XPATH, "/html/body/div/div[1]/div[1]/form[1]/div/div[1]/div/div[1]/input"
    SEARCH_BUTTON = By.XPATH, "/html/body/div/div[1]/div[1]/form[1]/div/div[1]/div/div[2]/input"
    FROM_BUTTON = By.XPATH, "/html/body/div/div[1]/div[1]/form[2]/div[2]/div[2]/input"
    TO_BUTTON = By.XPATH, "/html/body/div/div[1]/div[1]/form[1]/div/div[2]/a/img"
    ROUTE_BUTTON = By.XPATH, "/html/body/div/div[1]/div[1]/form[2]/div[4]/div[2]/input"
    ROUTE_CALC = By.XPATH, "/html/body/div/div[1]/div[1]/form[1]/div/div[2]/a"
    DISTANCE = By.XPATH, "/html/body/div/div[1]/div[5]/p[1]"
    FROM = (By.XPATH, "/html/body/div[1]/div[1]/div[1]/form[2]/div[2]/div[2]/input")
    TO = (By.XPATH, "/html/body/div[1]/div[1]/div[1]/form[2]/div[3]/div[2]/input")
    START = (By.XPATH, "/html/body/div[1]/div[1]/div[1]/form[2]/div[4]/div[2]/input")
    DISTANCE1 = (By.XPATH, "//*[@id='sidebar_content']/p[1]")

    def setUp(self) -> None:
        self.driver = webdriver.Chrome()
        self.driver.get('https://www.openstreetmap.org')
        self.driver.maximize_window()

    def test1_search_city(self):
        """testez cautarea unui oras"""
        self.driver.find_element(*self. SEARCH_BOX).send_keys("search_city")
        self.driver.find_element(*self.SEARCH_BUTTON).click()
        time.sleep(3)
        result = self.driver.find_element(By.XPATH, '//div/ul/li/a[@data-id="2077868"]')
        assert result.text, 'Suceava, România'

    def test2_city_street(self):
        """testez cautarea unei strazi, oras"""
        self.driver.find_element(*self. SEARCH_BOX).send_keys("city_street")
        self.driver.find_element(*self.SEARCH_BUTTON).click()
        time.sleep(3)
        res = self.driver.find_element(By.XPATH, '//div/ul/li/a[@data-id="25853887"]')
        assert res, 'Strada Narciselor, Zamca, Suceava, 720176, România'

    def test3_city_street_nr(self):
        """testez cautarea unei adrese dupa strada, nr, oras"""
        self.driver.find_element(*self. SEARCH_BOX).send_keys("city_street_nr")
        self.driver.find_element(*self.SEARCH_BUTTON).click()
        time.sleep(3)
        rezultat = self.driver.find_element(By.XPATH, '//div/ul/li/a[@data-id="209362627"]')
        assert rezultat.text, 'Bulevardul 1 Mai, George Enescu, Suceava, 720238, România'

    def test4_distance_between_cities(self):
        """testez distanta dintre doua orase"""
        self.driver.find_element(*self.ROUTE_CALC).click()
        time.sleep(3)
        self.driver.find_element(*self.FROM).send_keys("from")
        self.driver.find_element(*self.TO).send_keys("to")
        self.driver.find_element(*self.START).click()
        time.sleep(3)
        distance = self.driver.find_element(*self.DISTANCE1).text
        assert distance, 'Distanță: 418km. Durată: 8:12.'

    def tearDown(self) -> None:
        """inchid browserul"""
        self.driver.quit()


import random

class bcolors:
    ENDC = '\033[0m'
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

# TODO: Make separate ENEMY and PLAYER classes that inherits from main Person class
class Person:
    def __init__(self, name, hp, mp, atk, df, magic, items):
        self.name = name
        self.maxhp = hp
        self.hp = hp
        self.maxmp = mp
        self.mp = mp
        self.atkl = atk - 10
        self.atkh = atk + 10
        self.df = df
        self.magic = magic
        self.items = items
        self.actions = ["Attack", "Magic", "Items"]

    def generate_damage(self):
        return random.randrange(self.atkl, self.atkh)

    def take_damage(self, dmg):
        self.hp -= dmg
        if self.hp < 0:
            self.hp = 0
        return self.hp

    def heal(self, dmg):
        self.hp += dmg
        if self.hp > self.maxhp:
            self.hp = self.maxhp

    def get_hp(self):
        return self.hp

    def get_max_hp(self):
        return self.maxhp

    def get_mp(self):
        return self.mp

    def get_max_mp(self):
        return self.maxmp

    def reduce_mp(self, cost):
        self.mp -= cost

    def choose_action(self):
        print("\n\t" + bcolors.BOLD + self.name + bcolors.ENDC)
        print("\t" + bcolors.OKBLUE + bcolors.BOLD + "ACTIONS:" + bcolors.ENDC)
        i = 1
        for item in self.actions:
            print("\t\t" + str(i) + ":" + item)
            i += 1

    def choose_magic(self):
        print("\n\t" + bcolors.OKBLUE + bcolors.BOLD + "MAGIC:" + bcolors.ENDC)
        i = 1
        for spell in self.magic:
            print("\t\t" + str(i) + "." + spell.name + "(Cost: " + str(spell.cost) + ")")
            i += 1

    def choose_item(self):
        print("\n\t" + bcolors.OKGREEN + bcolors.BOLD + "ITEM:" + bcolors.ENDC)
        i = 1
        for item in self.items:
            print("\t\t" + str(i) + ".", item["item"].name, ":", item["item"].description,
                  "(x" + str(item["quantity"]) + ")")
            i += 1

    def choose_target(self, enemies):
        print("\n\t" + bcolors.FAIL + bcolors.BOLD + "TARGET:" + bcolors.ENDC)
        i = 1
        for enemy in enemies:
            print("\t\t" + str(i) + ".", enemy.name)
            i += 1
        choice = int(input("\tChoose target: ")) - 1
        return choice

    # Purely For UI/UX: START #
    def get_enemy_stats(self):
        # Creating Enemy HP Bar: START #
        hp_bar = ""
        hp_ticks = (self.hp / self.maxhp) * 100 / 2

        while hp_ticks > 0:
            hp_bar += "█"
            hp_ticks -= 1

        while len(hp_bar) < 50:
            hp_bar += " "
        # Creating Enemy HP Bar: END #

        # Catering For Enemy HP Chars White Space: START #
        hp_string = str(self.hp) + "/" + str(self.maxhp)
        current_hp = ""

        if len(hp_string) < 11:
            decreased = 11 - len(hp_string)

            while decreased > 0:
                current_hp += " "
                decreased -= 1

            current_hp += hp_string
        else:
            current_hp = hp_string
        # Catering For Enemy HP Chars White Space: END #

        print("                       __________________________________________________")
        print(bcolors.BOLD + self.name + ":    " +
              current_hp + " |" + bcolors.FAIL + hp_bar + bcolors.ENDC + bcolors.BOLD + "|")

    def get_stats(self):
        # Creating HP Bar: START #
        hp_bar = ""
        hp_ticks = (self.hp / self.maxhp) * 100 / 4

        while hp_ticks > 0:
            hp_bar += "█"
            hp_ticks -= 1

        while len(hp_bar) < 25:
            hp_bar += " "
        # Creating HP Bar: END #

        # Catering For HP Chars White Space: START #
        hp_string = str(self.hp) + "/" + str(self.maxhp)
        current_hp = ""

        if len(hp_string) < 9:
            decreased = 9 - len(hp_string)

            while decreased > 0:
                current_hp += " "
                decreased -= 1

            current_hp += hp_string
        else:
            current_hp = hp_string
        # Catering For HP Chars White Space: END #

        # Creating MP Bar: START #
        mp_bar = ""
        mp_ticks = (self.mp / self.maxmp) * 100 / 10

        while mp_ticks > 0:
            mp_bar += "█"
            mp_ticks -= 1

        while len(mp_bar) < 10:
            mp_bar += " "
        # Creating MP Bar: END #

        # Catering For MP Chars White Space: START #
        mp_string = str(self.mp) + "/" + str(self.maxmp)
        current_mp = ""

        if len(mp_string) < 7:
            decreased = 7 - len(mp_string)

            while decreased > 0:
                current_mp += " "
                decreased -= 1

            current_mp += mp_string
        else:
            current_mp = mp_string
        # Catering For MP Chars White Space: START #

        print("                        _________________________              __________")
        print(bcolors.BOLD + self.name + ":       " +
              current_hp + " |" + bcolors.OKGREEN + hp_bar + bcolors.ENDC + bcolors.BOLD + "|    " +
              current_mp + " |" + bcolors.OKBLUE + mp_bar + bcolors.ENDC + "|")

    # Determines what spell the enemy uses
    def choose_enemy_spell(self):
        # TODO: Counteract when enemy's MP is less than the cost of all it's spells
        while True:
            magic_choice = random.randrange(0, len(self.magic))
            spell = self.magic[magic_choice]
            magic_dmg = spell.generate_damage()

            pct = self.hp / self.maxhp * 100

            if self.mp < spell.cost or spell.type == "white" and pct > 50:
                continue
            else:
                return spell, magic_dmg


from django.db import models

class Student(models.Model):
    name = models.CharField(max_length=150, verbose_name='Имя')
    surname = models.CharField(max_length=150, verbose_name='Фамилия')
    age = models.IntegerField(blank=False)
    is_studying = models.BooleanField(default=False)
    photo = models.ImageField(upload_to='students/',verbose_name='Фото', blank=True)

    class Meta:
        verbose_name = 'Студент'
        verbose_name_plural = 'Студенты'

    def __str__(self):
        return self.name + self.surname

# Create your models here.


def countDivisor(n):
    count = 0

    for i in range(1, n+1):
        if n % i == 0:
            count += 1

    return count

def solution(left, right):
    answer = 0

    for i in range(left, right+1):
        if countDivisor(i) % 2 == 0:
            answer += i
        elif countDivisor(i) % 2 == 1:
            answer -= i

    return answer

프로그래머스/lv1/77884. 약수의 개수와 덧셈/약수의 개수와 덧셈.py

약수의 개수와 덧셈.py


#!/usr/bin/env python3

from db import get_class_pair, update_guess, update_upvote
from io import TextIOWrapper
import sys
import json

def cors():
    print("Access-Control-Allow-Origin: http://localhost:3000")
    print("Access-Control-Allow-Headers: Content-Type")
    print("Access-Control-Allow-Methods: POST,OPTIONS")
    print("Access-Control-Allow-Credentials: true")

def exit(status, payload=""):
    print("Content-Type: application/json")
    print()
    response = {
        "status": status,
        "payload": payload,
    }
    print(json.dumps(response))
    sys.exit(0)

def get(request, key):
    result = request.get(key, None)
    if result is None:
        exit("error", "can't parse %s: %s" % (key, result))
    return result

def main():
    sys.stdin = TextIOWrapper(sys.stdin.detach(), encoding="utf8")
    sys.stdout = TextIOWrapper(sys.stdout.detach(), encoding="utf8")
    cors()

    try:
        request = json.load(sys.stdin)
    except Exception as e:
        exit("error", "can't parse json: %s" % str(e))

    type_ = request.get("type", None)

    if type_ == "get":
        real, fake = get_class_pair()
        exit("success", {"real": real, "fake": fake})

    elif type_ == "guess":
        real_rowid = get(request, "real_rowid")
        fake_rowid = get(request, "fake_rowid")
        correct = get(request, "correct")
        update_guess(real_rowid, fake_rowid, correct)
        exit("success")

    elif type_ == "upvote":
        rowid = get(request, "rowid")
        update_upvote(rowid)
        exit("success")

    else:
        exit("error", "can't parse type %s" % str(type_))

if __name__ == "__main__":
    main()


from django.conf.urls import url
from django.views.generic import TemplateView
from . import views

app_name = 'jobs'
urlpatterns = [
    url(r"^$", views.home, name="home"),
    url(r"^jobs/(?P<href>[\d]+)/$",views.content,name="content"),
    url(r"^company/(?P<href>[\d]+)/$",views.company,name="company"),
    url(r"internship$",views.internship,name="internship"),
    url(r"fulltime$",views.fulltime,name="fulltime"),
    url(r"^status$",views.status,name="status"),
    url(r"^post$", TemplateView.as_view(template_name="jobs/post.html"), name="post"),
    #url(r"^post$", views.postjob, name="postjob"),
    url(r"^postmeetings$", TemplateView.as_view(template_name="jobs/postmeeting.html"), name="postmeetings"),
    url(r"^postcontests$", TemplateView.as_view(template_name="jobs/postcontest.html"), name="postcontests"),
    url(r"^search$",views.search,name="search"),
    url(r"^meetings$",views.meetingShow,name="meetings"),
    url(r"^meetings/(?P<href>[\d]+)/$",views.meetingcontent,name="meetingcontent"),
    url(r"^meetingpoststatus$",views.meetingpoststatus,name="meetingpoststatus"),
    url(r"^contests$",views.contestShow,name="contests"),
    url(r"^contests/(?P<href>[\d]+)/$",views.contestcontent,name="contestcontent"),
    url(r"^contestpoststatus$",views.contestpoststatus,name="contestpoststatus"),
]


import os
import platform
from avocado import Test
from avocado.utils import archive, build, distro
from avocado.utils.software_manager.manager import SoftwareManager

class Perftool(Test):

    """
    perftool-testsuite
    :avocado: tags=perf,testsuite
    """

    def setUp(self):
        '''
        Install the basic packages to support perf
        '''

        # Check for basic utilities
        smm = SoftwareManager()
        detected_distro = distro.detect()
        deps = ['gcc', 'make']
        if 'Ubuntu' in detected_distro.name:
            deps.extend(['linux-tools-common', 'linux-tools-%s' %
                         platform.uname()[2]])
        elif 'debian' in detected_distro.name:
            deps.extend(['linux-tools-%s' % platform.uname()[2][3]])
        elif detected_distro.name in ['rhel', 'SuSE', 'fedora',
                                      'centos']:
            deps.extend(['perf', 'gcc-c++'])
        else:
            self.cancel("Install the package for perf supported\
                      by %s" % detected_distro.name)
        for package in deps:
            if not smm.check_installed(package) and not smm.install(package):
                self.cancel('%s is needed for the test to be run' % package)

        locations = ["https://github.com/rfmvh/perftool-testsuite/archive/"
                     "master.zip"]
        tarball = self.fetch_asset("perftool.zip", locations=locations,
                                   expire='7d')
        archive.extract(tarball, self.workdir)
        self.sourcedir = os.path.join(self.workdir,
                                      'perftool-testsuite-master')

    def test_perf_testsuite(self):
        '''
        Build perftool Test
        Source: https://github.com/rfmvh/perftool-testsuite
        '''
        count = 0
        for line in build.run_make(self.sourcedir, extra_args='check',
                                   process_kwargs={'ignore_status': True}
                                   ).stdout.decode("utf-8", "ignore").\
                splitlines():
            if '-- [ FAIL ] --' in line:
                count += 1
                self.log.info(line)
        if count > 0:
            self.fail("%s Test failed" % count)


#takes in inputs
x = int(input())
bricks = list(map(int, input().split()))
count = 1

#loops through to find a new tower
for i in range (x-1):
    if (bricks[i] < bricks[i+1]):
        count = count + 1

#prints answer
print (count)


import cv2

face_cascade_db = cv2.CascadeClassifier(
    cv2.data.haarcascades
    + 'haarcascade_frontalface_default.xml'
)  # подгружает файл в память

capture_vid = cv2.VideoCapture(0)

# img = cv2.imread("img.png")

while True:
    success, img = capture_vid.read()
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = face_cascade_db.detectMultiScale(img_gray, 1.1, 19)

    for (x, y, w, h) in faces:
        cv2.rectangle(
            img,
            (x, y),  # верхняя левая координата
            (x + w, y + h),  # нижняя правая координата
            (0, 0, 255),  # цвет прямоугольника
            2  # толщина линии
        )

    cv2.imshow("rez", img)
    cv2.waitKey()

    if cv2.waitKey(1) & 0xff == ord("q"):
        break

capture_vid.release()
cv2.destroyAllWindows()


import json
from concept_formation.continuous_value import ContinuousValue
from pprint import pprint

radical_dict = {
    0:"no_radical",
    1:"singlet",
    2:"doublet",
    3:"triplet"
}

charge_dict = {
    0:"outside_limits",
    1:"+3",
    2:"+2",
    3:"+1",
    4:"doublet_radical",
    5:"-1",
    6:"-2",
    7:"-3"
}

stereo_parity_dict = {
    0:"not_stereo",
    1:"odd",
    2:"even",
    3:"unmarked"
}

h_count_dict = {
    0:"H0",
    1:"H0",
    2:"H1",
    3:"H2",
    4:"H3",
    5:"H4"
}

bond_type_dict = {
    1:"Single",
    2:"Double",
    3:"Triple",
    4:"Aromatic",
    5:"Single_or_Double",
    6:"Single_or_Aromatic",
    7:"Double_or_Aromatic",
    8:"Any"
}

single_bond_stereo_dict = {
    0:"Not_stereo",
    1:"Up",
    4:"Either",
    6:"Down"
}

double_bond_stereo_dict = {
    0:"Use_coordinates",
    3:"Cis_or_trans"
}

def parse_counts_line(line):
    """
    Parses the counts line of a molecule and returns it asd a dictionary

    aaabbblllfffcccsssxxxrrrpppiiimmmvvvvvv
    aaa = number of atoms (current max 255)*
    bbb = number of bonds (current max 255)*
    lll = number of atom lists (max 30)*
    fff = (obsolete)
    ccc = chiral flag: 0=not chiral, 1=chiral
    sss = number of stext entries
    xxx = (obsolete)
    rrr = (obsolete)
    ppp = (obsolete)
    iii = (obsolete)
    mmm = number of lines of additional properties,
    vvvvv = version for the format
    """
    ret = {}
    ret["aaa"] = int(float(line[0:3]))
    ret["bbb"] = int(float(line[3:6]))
    ret["lll"] = int(float(line[6:9]))
    ret["ccc"] = int(float(line[12:15]))
    ret["sss"] = int(float(line[15:18]))
    ret["mmm"] = int(float(line[18:21]))
    ret["vvvvv"] = line[-5:]
    return ret

def parse_atom_line(line):
    """
    Parses a line from the atom block and returns it as a dictionary

    xxxxx.xxxxyyyyy.yyyyzzzzz.zzzz aaaddcccssshhhbbbvvvHHHrrriiimmmnnneee
    [0:10] xxxxx.xxxx = x-coordinate
    [10:20] yyyyy.yyyy = y-coordinate
    [20:30] zzzzz.zzzz = z-coordinate
    [31:34] aaa = atomic symbol
    [34:36] dd = mass difference, i.e. difference from standard mass
    [36:39] ccc = charge 0 = uncharged or value other than these, 1 = +3, 2 = +2, 3 = +1, 4 = doublet radical, 5 = -1, 6 = -2, 7 = -3
    [39:42] sss = atom stereo parity 0 = not stereo, 1 = odd, 2 = even, 3 = either or unmarked stereo center
    [42:45] hhh = INGORED hydrogen count +1
    [45:48] bbb = IGNORED stereo care box
    [48:51] vvv = valence
    [51:54] HHH = IGNORED H0 designator
    [54:57] rrr = Not used
    [57:60] iii = Not used
    [60:63] mmm = IGNORED atom-atom mapping number 1 - number of atoms
    [63:66] nnn = IGNORED inversion/retention flag g 0 = property not applied 1 = configuration is inverted,2 = configuration is retained
    [66:69] eee = IGNORED 0 = property not applied, 1 = change on atom must be exactly as shown
    """
    ret = {}
    ret["xxx"] = float(line[0:10])
    ret["yyy"] = float(line[10:20])
    ret["zzz"] = float(line[20:30])
    ret["aaa"] = line[31:34].strip()
    ret["dd"] =  int(float(line[34:36]))
    ret["ccc"] = int(float(line[36:39]))
    ret["sss"] = int(float(line[39:42]))
    ret["hhh"] = int(float(line[42:45]))
    ret["bbb"] = int(float(line[45:48]))
    ret["vvv"] = int(float(line[48:51]))
    ret["HHH"] = int(float(line[51:54]))
    ret["mmm"] = int(float(line[60:63]))
    ret["nnn"] = int(float(line[63:66]))
    ret["eee"] = int(float(line[66:69]))
    return ret

def parse_bond_line(line):
    """
    Parses a line from a bondblock and turns it into a dict

    111222tttsssxxxrrrccc
    111 = number of atom 1
    222 = number of atom 2
    ttt = bond type
    sss = bond stereo
    xxx = not used
    rrr = bond topology
    ccc = reacting center status
    """
    ret = {}
    ret["111"] = int(float(line[0:3]))
    ret["222"] = int(float(line[3:6]))
    ret["ttt"] = int(float(line[6:9]))
    ret["sss"] = int(float(line[9:12]))
    ret["xxx"] = int(float(line[12:15]))
    ret["rrr"] = int(float(line[15:18]))
    ret["ccc"] = int(float(line[18:21]))
    return ret

def parse_data_name(line):
    """
    Parses the name of a data item line, which will be used as an attribute name
    """
    first = line.index("<")+1
    last = line.rindex(">")
    return line[first:last]

def apply_m_chg(line,mol):
    """
    Parses a CHG line from the property block.

    This will 0-out the charge on any atom that is not listed.
    0123456789
    M CHGnn8 aaa vvv ...
    aaa An atom number to alter the charge for
    vvv The ammount of charge on the target atom
    """
    if len(line) == 0:
        return mol
    for k in mol:
        if isinstance(k,str) and k.startswith('?atom'):
            mol[k]["charge"] = "0"
    line = line.rsplit(r'\s+')[3:]
    for i in range(0,len(line),2):
        aaa = int(line[i])
        vvv = line[i+1]
        if vvv[0] == "-":
            mol["?atom%04d"%aaa]["charge"] = vvv
        else:
            mol["?atom%04d"%aaa]["charge"] = "+"+vvv
    return mol

def apply_m_rad(line,mol):
    """
    Parses a RAD line from the property block

    M RADnn8 aaa vvv ...
    aaa An atom number to alter the radical value of
    vvv A key into the radical_dict to set the radical value to
    """
    if len(line) == 0:
        return mol
    for k in mol:
        if isinstance(k,str) and k.startswith('?atom'):
            mol[k]["charge"] = "0"
            mol[k]["radical"] = "no radical"

    line = line.rsplit(r'\s+')[3:]
    for i in range(0,len(line),2):
        aaa = int(line[i])
        vvv = int(line[i+1])
        mol["?atom%04d"%aaa]["radical"] = radical_dict[vvv]
    return mol

def apply_m_iso(line,mol):
    """
    Parses and applies an ISO line from the property block

    M ISOnn8 aaa vvv ...
    aaa An atom numer to alter the mass_dif of
    vvv The mass_diff value to set
    """
    if len(line) == 0:
        return mol
    for k in mol:
        if isinstance(k,str) and k.startswith('?atom'):
            mol[k]["mass_diff"] = "0"

    line = line.rsplit(r'\s+')[3:]
    for i in range(0,len(line),2):
        aaa = int(line[i])
        vvv = int(line[i]+1)
        mol["?atom%04d"%aaa]["mass_diff"] = "+"+radical_dict[vvv]
    return mol

def merge_m_lines(lines):
    if len(lines) == 0:
        return ''
    line0 = lines[0]
    for l in lines[1:]:
        line0 += l[8:]
    return line0

def parse_mol(lines, verbose = False, data_items=False, tuple_realtions=False):
    """
    Parse the provided molfile and return a structured object representation
    that can be read by TRESTLE.
    """
    mol = {}
    num_atoms = 0
    num_bonds = 0
    num_lists = 0

    mol["name"] = lines[0]
    mol["software"] = lines[1].strip()
    if lines[2]:
        mol["comment"] = lines[2].strip()

    ### COUNTS LINE ###
    c_line = parse_counts_line(lines[3])
    num_atoms = c_line["aaa"]
    num_bonds = c_line["bbb"]
    num_lists = c_line["lll"]

    atom_dex = 4 + num_atoms
    bond_dex = atom_dex + num_bonds

    if verbose:
        if c_line["ccc"] == 1:
            mol["chiral"] = True
        elif c_line["ccc"] == 0:
            mol["chiral"] = False

    mol["version"] = c_line["vvvvv"]

    ### ATOM BLOCK ###
    for l,line in enumerate(lines[4:atom_dex]):
        atom = {}
        a_line = parse_atom_line(line)
        atom["x"] = a_line["xxx"]
        atom["y"] = a_line["yyy"]
        atom["z"] = a_line["zzz"]

        atom["symbol"] = a_line["aaa"]
        #stringify mass difference or leave numeric?
        atom["mass_diff"] = str(a_line["dd"])
        atom["charge"] = charge_dict[a_line["ccc"]]
        atom["stereo_parity"] = stereo_parity_dict[a_line["sss"]]

        if a_line["vvv"] == 0:
            atom["valence"] = "no marking"
        if a_line["vvv"] > 0 and a_line["vvv"] < 15:
            atom["valence"] = str(a_line["vvv"])
        if a_line["vvv"] == 15:
            atom["valence"] = "zero valence"

        if verbose:
            atom["hydrogen_count"] = h_count_dict[a_line["hhh"]]

        mol["?atom%04d"%(l+1)] = atom

    ### BOND BLOCK ###
    for l,line in enumerate(lines[atom_dex:bond_dex]):
        bond = ['bond']
        b_line = parse_bond_line(line)

        bond.append(bond_type_dict[b_line["ttt"]])
        if bond_type_dict[b_line["ttt"]] == "Single":
            bond.append(single_bond_stereo_dict[b_line["sss"]])
        elif bond_type_dict[b_line["ttt"]] == "Double":
            bond.append(double_bond_stereo_dict[b_line["sss"]])
        bond.append("?atom%04d"%b_line["111"])
        bond.append("?atom%04d"%b_line["222"])

        if tuple_realtions:
            mol[tuple(bond)] = True
        else:
            mol['('+' '.join(bond)+')'] = True

    ### PROPERTIES BLOCK ###

    Ms = []
    for line in lines[bond_dex:]:
        if line == 'M  END':
            break
        if line[0] == "M":
            Ms.append(line)
        else:
            break

    if len(Ms) > 0:
        apply_m_chg(merge_m_lines([l for l in Ms if l.startswith('M  CHG')]),mol)
        apply_m_rad(merge_m_lines([l for l in Ms if l.startswith('M  RAD')]),mol)
        apply_m_iso(merge_m_lines([l for l in Ms if l.startswith('M  ISO')]),mol)

    ### DATA ITEMS ###
    if data_items:
        data_dex = bond_dex + len(Ms)
        opened = False
        data_header = ""
        data_list = []
        for line in lines[data_dex:]:
            if line:
                if not opened and line[0] == ">":
                    opened = True
                    data_header = parse_data_name(line)
                    data_list = []
                    continue
                elif opened:
                    data_list.append(line)
            elif opened:
                mol[data_header] = '\n'.join(data_list)
                opened = False

    return mol

def parse_sdf_file(filename,verbose = False,data_items=False,tuple_realtions=False,n=-1):
    ret = []
    curr = []
    count = 0
    with open(filename,"r") as molefile:
        for line in molefile:
            line = line.rstrip('\r\n')
            if not line == "$$$$":
                curr.append(line)
            else:
                if len(curr) > 0:
                    ret.append(parse_mol(curr,verbose,data_items,tuple_realtions))
                    count += 1
                    if n > 0 and count > n:
                        break
                curr = []
    return ret

if __name__ == '__main__':
    # mols = parse_sdf_file("./example.mol",True,True,True,n=100)
    mols = parse_sdf_file("./testSDFs/Compound_000000001_000025000.sdf",True,True,True,n=25000)
    pprint(mols[0])


import logging
import time
from typing import Any, Dict, List, Optional

# https://github.com/gateio/gateapi-python
import gate_api

from .api import API, time_ms_to_str
from .errors import NotConnectedError
from .objects import AssetPair, Order
from .ticker import Ticker

class GateIOAPI(API):
    gate: Optional[gate_api.SpotApi] = None

    # pair -> list of open order IDs
    open_order_ids: Dict[str, List[str]] = {}

    def __init__(self, key="", secret="", logger=None):
        self.key = key
        self.secret = secret
        self.gate = None
        if logger is not None:
            self.logger = logger
        else:
            self.logger = logging.getLogger("GateIOAPI")
            self.logger.setLevel(logging.INFO)

    def cancel_orders(self) -> None:
        """
        GTC orders are used on gate.io, so they must be cancelled.
        """
        if self.gate is None:
            raise NotConnectedError()
        for market in self.cfg["markets"]:
            pair = self.real_pair(market["pair"])
            if (
                pair not in self.open_order_ids
                or len(self.open_order_ids[pair]) == 0
            ):
                self.logger.info("No orders to cancel for %s", pair)
                continue
            self.logger.info(
                "Cancelling orders for %s: [%s]",
                pair,
                ", ".join(self.open_order_ids[pair]),
            )
            cancel_orders = [
                gate_api.CancelOrder(
                    currency_pair=pair,
                    id=order_id,
                )
                for order_id in self.open_order_ids[pair]
            ]
            self.gate.cancel_batch_orders(cancel_orders)
            self.open_order_ids[pair] = []

    def connect(self) -> None:
        conf = gate_api.Configuration(
            host="https://api.gateio.ws/api/v4",
            key=self.key,
            secret=self.secret,
        )
        cli = gate_api.ApiClient(conf)
        self.gate = gate_api.SpotApi(cli)

    def get_asset_pairs(self) -> None:
        if self.gate is None:
            raise NotConnectedError()
        self.asset_pairs = {
            pair.id: AssetPair.from_gateio(pair)
            for pair in self.gate.list_currency_pairs()
        }

    def get_balances(self) -> None:
        if self.gate is None:
            raise NotConnectedError()
        self.balances = {
            acc.currency: {
                "total": float(acc.available),
                "unencumbered": float(acc.available) - float(acc.locked),
            }
            for acc in self.gate.list_spot_accounts()
        }

    def get_open_orders(self) -> None:
        if self.gate is None:
            raise NotConnectedError()
        open_orders: Dict[str, gate_api.Order] = {}
        for market in self.cfg["markets"]:
            open_orders[market["pair"]] = []
            for order in self.gate.list_orders(market["pair"], "open"):
                open_orders[market["pair"]].append(order)
                vol = float(order.left)  # remaining to be filled
                if order.side == "buy":
                    # encumber quote
                    asset_quote = self.asset_pairs[order.currency_pair].quote
                    amt_quote = vol * float(order.price)
                    # self.balances[asset_quote]["unencumbered"] -= amt_quote
                    self.logger.debug(
                        "Quote is encumbered for BUY %10.3f %s for %s",
                        amt_quote,
                        asset_quote,
                        order.currency_pair,
                    )
                elif order.side == "sell":
                    # encumber base
                    asset_base = self.asset_pairs[order.currency_pair].base
                    # self.balances[asset_base]["unencumbered"] -= vol
                    self.logger.debug(
                        "Base is encumbered for SELL %10.3f %s for %s",
                        vol,
                        asset_base,
                        order.currency_pair,
                    )

        for pair, orders in open_orders.items():
            self.logger.debug("Open orders for %s: %d", pair, len(orders))
            for order in orders:
                self.logger.debug(
                    "    %s: %s (%s)",
                    time_ms_to_str(order.create_time),
                    order.id,
                    order_info(order),
                )

    def get_ticker(self, pair: str) -> Ticker:
        if self.gate is None:
            raise NotConnectedError()
        results = self.gate.list_tickers(currency_pair=pair)[0]
        return Ticker.from_gateio(results)

    def place_orders(self, pair: str, orders: List[Order]) -> int:
        if self.gate is None:
            raise NotConnectedError()
        if pair not in self.open_order_ids:
            self.open_order_ids[pair] = []
        asset_pair = self.asset_pairs[pair]

        count = 0
        for order in orders:
            ope, clo = order.to_gateio(
                pair,
                asset_pair,
                self.cfg["order_lifespan_seconds"],
            )
            ope_resp = self.gate.create_order(ope)
            self.open_order_ids[pair].append(str(ope_resp.id))
            self.logger.info(
                "Created Open  order ID %s: %s %s %s @%s %s",
                ope_resp.id,
                ope.side,
                ope.amount,
                asset_pair.base,
                ope.price,
                asset_pair.quote,
            )
            time.sleep(self.cfg["inter_apireq_sleep_seconds"])
            if clo is not None:
                clo_resp = self.gate.create_spot_price_triggered_order(clo)
                # no need to add the closing order to the open_order_ids list,
                # since the closing orders expire.
                # self.open_order_ids[pair].append(str(clo_resp.id))
                self.logger.info(
                    "Created Close order ID %s: %s %s %s @%s %s "
                    "[if price %s %s %s]",
                    clo_resp.id,
                    clo.put.side,
                    clo.put.amount,
                    asset_pair.base,
                    clo.put.price,
                    asset_pair.quote,
                    clo.trigger.rule,
                    clo.trigger.price,
                    asset_pair.quote,
                )
                time.sleep(self.cfg["inter_apireq_sleep_seconds"])
                count += 1

        return count

def order_info(order: Any) -> str:
    return (
        f"{order.side} {order.left} {order.currency_pair} "
        f"@ {order.type} {order.price}"
    )


import pandas

def out_correlation(data: pandas.DataFrame,index,datatype):
    src = './TestSet By Group{0}/{1}_correlation.csv'.format(index,datatype)
    pandas.DataFrame({'AU': data.corr().label.index, 'correlation': data.corr().label.values}).to_csv(src, index=False)

testsrc = './TestSet By Group{0}/average/Au_XX_R_TestSet.csv'
trainsrc = './TestSet By Group{0}/average/Au_XX_R_TrainSet.csv'
for i in range(1,6):
    testdata = pandas.read_csv(testsrc.format(i))
    traindata = pandas.read_csv(trainsrc.format(i))
    out_correlation(testdata,i,'test')
    out_correlation(traindata,i,'train')


'''Given an input string s, reverse the order of the words.

A word is defined as a sequence of non-space characters. The words in s
will be separated by at least one space.

Return a string of the words in reverse order concatenated by a single
space.

Note that s may contain leading or trailing spaces or multiple spaces
between two words. The returned string should only have a single space
separating the words. Do not include any extra spaces.'''

import re
class Solution:
    def reverseWords(self, s: str) -> str:
        ans = s.split(' ')
        ans = ans[::-1]
        ans = [re.sub('\W+', '', s) for s in ans]
        ans_str = ''
        for word in ans:
            if len(word)>0:
                ans_str += word + ' '
        ans_str = ans_str.strip()
        return ans_str


from dash import dash, html, dcc, Input, Output, dash_table
import dash_bootstrap_components as dbc
import altair as alt
import pandas as pd

IMG_DIR = "assets/img/drivers/"
drivers_df = pd.read_csv("data/formula1_2021season_drivers.csv")
laps_df = pd.read_csv("data/2021_all_laps_info.csv")
table_cols = [
    'Abbreviation',
    'Number',
    'Team',
    'Country',
    'Podiums',
    'Points',
    'Grands Prix Entered',
    'World Championships',
    'Highest Grid Position',
    'Place of Birth'
]

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX])
server = app.server

app.layout = html.Div([
    dbc.Row([
        html.H1("2021 Formula 1 Statistics", style={"text-align": "center"}),
    ]),
    dbc.Row([
        dbc.Col([
            'View driver information:',
            dcc.Dropdown(
                id = 'driverinfo-select',
                options = [driver for driver in drivers_df['Driver']],
                value = 'Max Verstappen',
                multi = False,
                clearable = False),
        ], width=2),
        dbc.Row([
            dbc.Col([
                html.Img(id = 'image')
            ]),
            dbc.Col([
                dash_table.DataTable(
                    id = 'table',
                    data = []
                )
            ], width=10),
        ], justify='center'),
        dbc.Row([
            dbc.Col([
                'Rank by:',
                dcc.Dropdown(
                    id = 'ranking-criteria',
                    options = ['Podiums', 'Points', 'World Championships'],
                    value = 'Podiums',
                    multi = False,
                    clearable = False)
            ], width=1),
            dbc.Col([
                html.Iframe(
                    id='ranking-plot',
                    style={'border-width': '0', 'width': '100%', 'height': '500px'})
            ]),
            dbc.Col([
                dbc.Row([
                    dcc.Dropdown(
                        id = 'gp-select',
                        options = laps_df['GP'].unique().tolist(),
                        value = 'Bahrain Grand Prix',
                        multi = False,
                        clearable = False)
                ]),
                dbc.Row([
                    dcc.Checklist(
                        id = 'driver-select',
                        options = laps_df['name'].unique().tolist(),
                        value=['Max Verstappen', 'Lance Stroll', 'Lando Norris'],
                        labelStyle={'display': 'block'})
                ])
            ], width=2),
            dbc.Col([
                html.Iframe(
                    id='laptime-boxplot',
                    style={'border-width': '0', 'width': '100%', 'height': '500px'})
            ])
        ]),
    ])
])

@app.callback(
    Output('table', 'columns'),
    Output('table', 'data'),
    Input('driverinfo-select', 'value')
)
def render_driver_table(driverinfo_select):
    df = drivers_df.query("Driver == @driverinfo_select")
    df = df[table_cols]
    return [{'name': col, 'id': col} for col in df.columns], df.to_dict('records')

@app.callback(
    Output('image', 'src'),
    Input('driverinfo-select', 'value')
)
def display_image(driverinfo_select):
    img_path = IMG_DIR + driverinfo_select+ ".png"
    return img_path

@app.callback(
    Output('ranking-plot', 'srcDoc'),
    Input('ranking-criteria', 'value')
)
def plot_ranking(ranking):
    chart = alt.Chart(drivers_df, title="Ranking by number of " + ranking).mark_bar().encode(
        x = ranking,
        y = alt.Y('Driver', sort="-x")
    )
    return chart.to_html()

@app.callback(
    Output('laptime-boxplot', 'srcDoc'),
    Input('driver-select', 'value'),
    Input('gp-select', 'value')
)
def plot_laptime_boxplot(driver_select, gp_select):
    df = laps_df.query("GP == @gp_select")
    df = df.query("name in @driver_select")
    chart = alt.Chart(df, title="Laptime distribution of each driver").mark_boxplot(size=30).encode(
        y = alt.Y("lap_time_ms", title='Laptime', scale=alt.Scale(zero=False)),
        x = alt.X("name", title='Driver', axis=alt.Axis(labelAngle=-45)),
        color = alt.Color("name", legend=None)
    ).properties(
        width=400
    )
    return chart.to_html()

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


import os

from fastapi import APIRouter
from fastapi.responses import FileResponse

from api.models import User, Wallet, User_Pydantic, Wallet_Pydantic
from api.types import Withdraw_Pydantic
from api.settings import settings

from providers.ton_provider import TON_Provider
from utils import encode

router = APIRouter(prefix=settings.API_PREFIX)

TON_API_KEY = [settings.TON_API_KEY_MAINNET,
               settings.TON_API_KEY_TESTNET][settings.TESTNET]

@router.get("/users", tags=['users'])
async def get_all_users():
    response = await User_Pydantic.from_queryset(User.all())
    return {'status': 'ok', 'data': response}

@router.get("/users/{user_id}", tags=['users'])
async def get_user(user_id: int):
    response = await User_Pydantic.from_queryset_single(User.get_or_none(id=user_id))
    return {'status': 'ok', 'data': response}

@router.get("/users/{user_id}/wallets", tags=['users'])
async def get_user_wallets(user_id: int | None = None):
    response = await Wallet_Pydantic.from_queryset(Wallet.filter(user=user_id, is_active=True))
    return {'status': 'ok', 'data': response}

@router.get("/wallets", tags=['wallets'])
async def get_all_wallets():
    response = await Wallet_Pydantic.from_queryset(Wallet.all())
    return {'status': 'ok', 'data': response}

@router.get("/wallets/{wallet_address}", tags=['wallets'])
async def get_wallet(wallet_address: str | None = None):
    response = await Wallet_Pydantic.from_queryset_single(Wallet.get_or_none(address=wallet_address, is_active=True))
    return {'status': 'ok', 'data': response}

@router.get("/images/{image_name}", tags=['images'])
def image_endpoint(image_name: str):
    file_path = f"images/{image_name}"
    if os.path.exists(file_path):
        return FileResponse(file_path, media_type="image/svg+xml")
    return {"error": "File not found!"}

@router.post("/withdraw", tags=['transactions'])
async def withdraw(trans: Withdraw_Pydantic):
    trans_dict = trans.dict()

    ton_client = TON_Provider(api_key=TON_API_KEY,
                              testnet=settings.TESTNET)
    from_wallet_address = trans_dict['source']
    # destination_address = await ton_client.get_wallet_info(trans_dict['destination'])
    # if not destination_address.get('wallet'):
    #     return {'error': 'Incorrect address'}

    user_id = trans_dict['user_id']
    user_wallet = await Wallet.get(user=user_id,
                                   address=from_wallet_address,
                                   coin__short_name=trans_dict['coin'],
                                   network__short_name=trans_dict['network'],
                                   )
    if not trans_dict['query_id'] or not user_id:
        return {'error': 'Something was wrong'}

    total_amount = trans_dict['amount'] + trans_dict['gas_fee']
    trans_dict.update({'total': total_amount})

    mnemonic = settings.HOT_WALLET_MNEMONICS.split(',')

    [mnemonics, pub_key, priv_key,
        hot_wallet] = ton_client.get_wallet(mnemonic, version='v3r2')

    if trans_dict['total'] > user_wallet.balance:
        return {'error': 'Not enough money'}
    elif trans_dict['total'] <= user_wallet.min_withdraw_limit:
        return {'error': 'The amount must be more than min withdrawal limit'}

    try:
        msg = f"{from_wallet_address};{trans_dict['total']};{user_id}"

        encoded_msg = encode(msg)
        dest = ton_client.non_bounceable_address(trans_dict['destination'])
        await ton_client.send_tons(hot_wallet,
                                   dest,
                                   trans_dict['amount'],
                                   payload=encoded_msg
                                   )
        user_wallet.balance = user_wallet.balance-total_amount

        await user_wallet.save(update_fields=['balance'])
    except Exception as e:
        return {'error': 'Something was wrong. Try again later'}

    return {'status': 'ok', 'detail': 'Withdraw successful!'}


"""
Compute area of circle using all possible function prototypes.
"""
import math

def area_circle(r):
    area = math.pi * r ** 2
    return area

input_radius = float(input())
print(area_circle(input_radius))

explore/Python/VIT SEM 1/Session 21/area_circle.py


# -*- coding: utf-8 -*-
"""
Created on Thu Dec  3 07:36:23 2020

@author: Marysia

Puzzle 3 part 1 from https://adventofcode.com/2020/day/3

Starting at the top-left corner of your map and following
a slope of right 3 and down 1, how many trees would you encounter?
"""

with open('map.txt', 'r') as file:
    MAP = file.readlines()

MAP = [x.strip() for x in MAP]
ROW_LENGTH = len(MAP[0])
COLUMN = 0
STEP_RIGHT = 3
STEP_DOWN = 1
COUNTER = 0

i = 0
while i < len(MAP):
    if COLUMN < (ROW_LENGTH):
        ENTRY = MAP[i][COLUMN % (ROW_LENGTH)]
        print(ENTRY, i, COLUMN)
        i += STEP_DOWN
        COLUMN += STEP_RIGHT
    else:
        COLUMN -= ROW_LENGTH
        #i -= STEP_DOWN
        ENTRY = MAP[i][COLUMN % (ROW_LENGTH)]
        print(ENTRY, i, COLUMN)
        i += STEP_DOWN
        COLUMN += STEP_RIGHT
    if ENTRY == '#':
        COUNTER += 1

print("The number of trees encountered is {}.".format(COUNTER))


import nltk
from nltk import CFG

# Define a context-free grammar
grammar_rules = """
    S -> NP VP
    NP -> Det N | Det N PP
    VP -> V NP | V NP PP
    PP -> P NP
    Det -> 'the' | 'a'
    N -> 'cat' | 'dog' | 'man' | 'park'
    V -> 'chased' | 'saw'
    P -> 'in' | 'on'
"""

# Create a CFG object
grammar = CFG.fromstring(grammar_rules)

# Create a parser using the Earley parser from NLTK
parser = nltk.ChartParser(grammar)

# Function to generate a parse tree for a given sentence
def generate_parse_tree(sentence):
    words = sentence.split()
    try:
        trees = list(parser.parse(words))
        if len(trees) == 1:
            return trees[0]
        else:
            print("Ambiguous parsing. Multiple parse trees found.")
    except ValueError as e:
        print(f"Error parsing sentence: {e}")

# Example usage
sentence = "the cat chased the dog in the park"
parse_tree = generate_parse_tree(sentence)

# Display the parse tree
if parse_tree:
    parse_tree.pretty_print()


import sys
import os
import json

try:
    from multienv_common import VolConst
except ImportError:
    from openquakeplatform_ipt.multienv_common import VolConst

GDAL2_AVAILABLE = False
try:
    from osgeo import gdal
    if int(gdal.VersionInfo("VERSION_NUM")) > 2000000:
        import re
        import gc
        import csv
        import numpy
        from osgeo import ogr, osr
        from pyproj import Proj, transform

        GDAL2_AVAILABLE = True

        def gem_raster2polyg(hea, epsg_in, raster, csv_filepath):
            driver = dst_ds = sourceBand = srs_in = transform = outband = None
            sourceBand = outDatasource = outLayer = newField = multi = None
            geom = wkt = None

            try:
                dst_filename = 'rast_gen_out.vrt'

                driver = gdal.GetDriverByName("MEM")

                dst_ds = driver.Create(dst_filename,
                                       xsize=hea['ncols'],
                                       ysize=hea['nrows'],
                                       bands=1, eType=gdal.GDT_Float32)

                srs_in = osr.SpatialReference()
                srs_in.ImportFromEPSG(int(epsg_in))

                epsg = 4326
                srs = osr.SpatialReference()
                if int(gdal.VersionInfo("VERSION_NUM")[0]) >= 3:
                    # GDAL 3 changes axis order:
                    #          https://github.com/OSGeo/gdal/issues/1546
                    srs.SetAxisMappingStrategy(osr.OAMS_TRADITIONAL_GIS_ORDER)
                srs.ImportFromEPSG(epsg)

                transform = None
                if not srs_in.IsSame(srs) or (
                        int(gdal.VersionInfo("VERSION_NUM")[0]) >= 3):
                    transform = osr.CoordinateTransformation(
                        srs_in, srs)

                pixw = hea['cellsize']

                dst_ds.SetGeoTransform((
                    hea['xllcorner'],
                    pixw, 0,
                    hea['yllcorner'] + float(pixw * hea['nrows']),
                    0, -pixw))

                dst_ds.SetProjection(srs_in.ExportToWkt())
                outband = dst_ds.GetRasterBand(1)
                outband.WriteArray(raster)
                outband.FlushCache()

                # Once we're done, close properly the dataset

                sourceBand = dst_ds.GetRasterBand(1)
                sourceBand.SetNoDataValue(0.0)
                sourceBand.WriteRaster(
                    0, 0, hea['ncols'], hea['nrows'],
                    sourceBand.ReadRaster())

                driver = ogr.GetDriverByName("Memory")
                outDatasource = driver.CreateDataSource('poly_ds')
                outLayer = outDatasource.CreateLayer("polygonized", srs=srs)

                newField = ogr.FieldDefn('poly', ogr.OFTReal)
                outLayer.CreateField(newField)

                gdal.Polygonize(sourceBand, sourceBand, outLayer, -1, [],
                                callback=None)

                multi = ogr.Geometry(ogr.wkbMultiPolygon)
                for feature in outLayer:
                    geom = feature.GetGeometryRef()
                    if transform:
                        geom.Transform(transform)

                    geom.FlattenTo2D()
                    wkt = geom.ExportToWkt()
                    multi.AddGeometryDirectly(ogr.CreateGeometryFromWkt(wkt))

                with open(csv_filepath, 'w', newline='') as f_out:
                    f_out.write('geom\n"')
                    f_out.write(str(multi))
                    f_out.write('"\n')
            finally:
                driver = dst_ds = sourceBand = srs_in = transform = None
                sourceBand = outDatasource = outLayer = newField = multi = None
                outband = geom = wkt = None
                gc.collect()

        class TransToWGS84(object):
            def __init__(self, epsg_in):
                self.proj_in = Proj(init='epsg:%s' % epsg_in)
                self.proj_out = Proj(init='epsg:%s' % VolConst.epsg_out)

            def coord(self, x_in, y_in):
                x_out, y_out = transform(self.proj_in, self.proj_out,
                                         x_in, y_in)
                return (x_out, y_out)

        def gem_esritxt2wkt_coreconv_exec(input_filepath, csv_filepath,
                                          epsg_in, density, nodata_extra_in):
            if nodata_extra_in is None:
                nodata_extra = []
            else:
                nodata_extra = nodata_extra_in

            hea = {'ncols': None,
                   'nrows': None,
                   'xllcorner': None,
                   'yllcorner': None,
                   'cellsize': None,
                   'nodata_value': None}

            is_head = True
            row_ct = 0
            with open(input_filepath, "r") as f:
                for row_s in f:
                    row = re.split(r'[\s]\s*', row_s)
                    if is_head:
                        if row[0].lower() in hea:
                            hea[row[0].lower()] = row[1]
                            continue
                        else:
                            raster = numpy.zeros(
                                (
                                    int(hea['nrows']),
                                    int(hea['ncols'])
                                ),
                                dtype=numpy.float32)

                            hea['xllcorner'] = float(hea['xllcorner'])
                            hea['yllcorner'] = float(hea['yllcorner'])
                            hea['cellsize'] = float(hea['cellsize'])
                            hea['ncols'] = int(hea['ncols'])
                            hea['nrows'] = int(hea['nrows'])
                            hea['nodata_value'] = float(
                                hea['nodata_value'])
                            is_head = False

                    if not is_head:
                        for i in range(0, len(row)):
                            if row[i].strip() == "":
                                continue
                            row[i] = (1.0 if (
                                float(row[i]) != hea['nodata_value']
                                and row[i] not in nodata_extra) else 0.0)
                        raster[row_ct] = row[0:hea['ncols']]
                        row_ct += 1
                        if row_ct >= hea['nrows']:
                            break

            gem_raster2polyg(hea, epsg_in, raster, csv_filepath)

        def gem_esritxt_coreconv_exec(input_filepath, csv_filepath, epsg_in,
                                      density):
            raster = gdal.Open(input_filepath)
            rasterArray = raster.ReadAsArray()
            lon, lon_delta, _, lat, _, lat_delta = raster.GetGeoTransform()

            if epsg_in is not VolConst.epsg_out:
                trans = TransToWGS84(epsg_in)

            with open(csv_filepath, 'w', newline='') as csv_fout:
                csv_out = csv.writer(csv_fout)
                csv_out.writerow(['lon', 'lat', 'intensity'])

                lat_out = lat + (lat_delta / 2.0)
                for row in rasterArray:
                    lon_out = lon + (lon_delta / 2.0)
                    for el in row:
                        if float(el) <= 0.0:
                            continue
                        if epsg_in is not VolConst.epsg_out:
                            # original coordinates
                            # transformed to EPGS:4326 using pyproj
                            lon_out, lat_out = trans.coord(lon_out, lat_out)

                        if not (density is None):
                            el = ((float(density) * VolConst.g *
                                   (float(el) / 1000.)) / 1000.)

                        row_out = ["%.5f" % lon_out, "%.5f" % lat_out,
                                   "%.5f" % el]
                        csv_out.writerow(row_out)

                        lon_out += lon_delta
                    lat_out += lat_delta

        def gem_titan2_coreconv_exec(input_filepath, csv_filepath, epsg_in):
            if epsg_in is not VolConst.epsg_out:
                trans = TransToWGS84(epsg_in)

            with open(input_filepath, 'r', newline='') as file_in, open(
                    csv_filepath, 'w', newline='') as csv_fout:
                csv_out = csv.writer(csv_fout)
                csv_out.writerow(['lon', 'lat', 'intensity'])

                line1 = file_in.readline()
                ret = re.search(
                    '^Nx=([0-9]+): X={[ 	]*([0-9]+),[ 	]*([0-9]+)',
                    line1)

                ret1_grp = ret.groups()
                if len(ret1_grp) != 3:
                    raise ValueError(
                        'Malformed Titan2 first line header [%s]' % line1)
                cols_n = int(ret1_grp[0])
                x_min = float(ret1_grp[1])
                x_max = float(ret1_grp[2])

                line2 = file_in.readline()
                ret = re.search(
                    '^Ny=([0-9]+): Y={[ 	]*([0-9]+),[ 	]*([0-9]+)',
                    line2)

                ret2_grp = ret.groups()
                if len(ret2_grp) != 3:
                    raise ValueError(
                        'Malformed Titan2 second line header [%s]' % line2)
                rows_n = int(ret1_grp[0])
                y_min = float(ret1_grp[1])
                y_max = float(ret1_grp[2])

                x_step = float((x_max - x_min) / float(cols_n))
                y_step = float((y_max - y_min) / float(rows_n))

                line3 = file_in.readline()
                ret = re.search('^(Pileheight=)\s*', line3)

                ret3_grp = ret.groups()
                if len(ret3_grp) != 1:
                    raise ValueError(
                        'Malformed Titan2 third line header [%s]' % line3)

                x_cur = 0
                y_cur = 0
                for row in file_in:
                    for el in re.split(r'\s+', row.strip()):
                        if float(el) <= 0.0:
                            x_cur += 1
                            if x_cur == cols_n:
                                x_cur = 0
                                y_cur += 1
                            continue
                        x = x_min + (x_step / 2.0) + x_cur * x_step
                        y = y_min + (y_step / 2.0) + y_cur * y_step
                        lon, lat = trans.coord(x, y)
                        # This is necessary ONLY for converted geo coordinates
                        if lon > 180.0:
                            lon = lon - 360.0
                        # Writing .csv file with EPGS:4326 coordinates

                        csv_out.writerow(["%.5f" % lon, "%.5f" % lat,
                                          "%.5f" % float(el)])

                        x_cur += 1
                        if x_cur == cols_n:
                            x_cur = 0
                            y_cur += 1

        def gem_titan2wkt_coreconv_exec(input_filepath, csv_filepath, epsg_in):
            if epsg_in is not VolConst.epsg_out:
                trans = TransToWGS84(epsg_in)

            with open(input_filepath, 'r', newline='') as file_in, open(
                    csv_filepath, 'w', newline='') as csv_fout:
                csv_out = csv.writer(csv_fout)
                csv_out.writerow(['lon', 'lat', 'intensity'])

                line1 = file_in.readline()
                ret = re.search(
                    '^Nx=([0-9]+): X={[ 	]*([0-9]+),[ 	]*([0-9]+)',
                    line1)

                ret1_grp = ret.groups()
                if len(ret1_grp) != 3:
                    raise ValueError(
                        'Malformed Titan2 first line header [%s]' % line1)
                cols_n = int(ret1_grp[0])
                x_min = float(ret1_grp[1])
                x_max = float(ret1_grp[2])

                line2 = file_in.readline()
                ret = re.search(
                    '^Ny=([0-9]+): Y={[ 	]*([0-9]+),[ 	]*([0-9]+)',
                    line2)

                ret2_grp = ret.groups()
                if len(ret2_grp) != 3:
                    raise ValueError(
                        'Malformed Titan2 second line header [%s]' % line2)
                rows_n = int(ret1_grp[0])
                y_min = float(ret1_grp[1])
                y_max = float(ret1_grp[2])

                x_step = float((x_max - x_min) / float(cols_n))
                y_step = float((y_max - y_min) / float(rows_n))

                line3 = file_in.readline()
                ret = re.search('^(Pileheight=)\s*', line3)

                ret3_grp = ret.groups()
                if len(ret3_grp) != 1:
                    raise ValueError(
                        'Malformed Titan2 third line header [%s]' % line3)

                if x_step != y_step:
                    raise ValueError(
                        'Malformed Titan2 x and y distance'
                        ' are different [%f, %f]' % (x_step, y_step))

                x_cur = 0
                y_cur = 0
                for row in file_in:
                    for el in re.split(r'\s+', row.strip()):
                        if float(el) <= 0.0:
                            x_cur += 1
                            if x_cur == cols_n:
                                x_cur = 0
                                y_cur += 1
                            continue
                        x = x_min + (x_step / 2.0) + x_cur * x_step
                        y = y_min + (y_step / 2.0) + y_cur * y_step
                        lon, lat = trans.coord(x, y)
                        # This is necessary ONLY for converted geo coordinates
                        if lon > 180.0:
                            lon = lon - 360.0
                        # Writing .csv file with EPGS:4326 coordinates

                        csv_out.writerow(["%.5f" % lon, "%.5f" % lat,
                                          "%.5f" % float(el)])

                        x_cur += 1
                        if x_cur == cols_n:
                            x_cur = 0
                            y_cur += 1

        def gem_shape_coreconv_exec(input_filepath, csv_filepath,
                                    attrib, p_size, density):
            try:
                tmp_path = os.path.dirname(input_filepath)
                shp_filename = os.path.basename(input_filepath)
                tif_filename = shp_filename[:-4] + ".tif"
                xyz_filename = shp_filename[:-4] + ".xyz"
                csv_filename = shp_filename[:-4] + "__shp.csv"
                ogr_drv = ogr.GetDriverByName('ESRI Shapefile')
                s_ds = ogr_drv.Open(input_filepath)
                s_layer = s_ds.GetLayer()
                l_name = s_layer.GetName()
                x_min, x_max, y_min, y_max = s_layer.GetExtent()

                InDS = gdal.OpenEx(input_filepath,
                                   nOpenFlags=(gdal.OF_VECTOR |
                                               gdal.OF_VERBOSE_ERROR))

                rast_opts_s = (
                    "-l {0} -a {1} -tr {2} {2} -te {3} {4} {5} {6}"
                    " -of GTiff -ot Float16 -a_srs EPSG:4326".format(
                        l_name,
                        attrib, p_size,
                        x_min, y_min, x_max, y_max))
                rast_opts = gdal.RasterizeOptions(options=rast_opts_s)

                RetDS = gdal.Rasterize(os.path.join(tmp_path, tif_filename),
                                       InDS, options=rast_opts)

                trans_opts_s = ("-of XYZ -tr {0} {0} -r bilinear"
                                " -co COLUMN_SEPARATOR=,".format(p_size))
                trans_opts = gdal.TranslateOptions(options=trans_opts_s)
                gdal.Translate(os.path.join(tmp_path, xyz_filename),
                               RetDS, options=trans_opts)

                csv_filepath = os.path.join(tmp_path, csv_filename)
                with open(os.path.join(tmp_path, xyz_filename),
                          "r") as f_in, open(
                              csv_filepath, 'w', newline='') as f_out:
                    csv_in = csv.reader(f_in)
                    csv_out = csv.writer(f_out)
                    csv_out.writerow(['lon', 'lat', 'intensity'])
                    for r in csv_in:
                        if float(r[2]) <= 0.0:
                            continue
                        if density is None:
                            intens = r[2].strip()
                        else:
                            load_kpa = ((float(density) * VolConst.g *
                                         (float(r[2]) / 1000.)) / 1000.)
                            intens = "%.5f" % load_kpa
                        csv_out.writerow(
                            ["%.5f" % float(r[0]), "%.5f" % float(r[1]),
                             intens])
            finally:
                del RetDS
                del s_ds
                del InDS
                del ogr_drv
                gc.collect()

        def gem_shape2wkt_coreconv_exec(input_filepath, wkt_filepath):
            try:
                ogr_drv = ogr.GetDriverByName('ESRI Shapefile')
                shp_ds = ogr_drv.Open(input_filepath, 0)
                shp_layer = shp_ds.GetLayerByIndex(0)

                if shp_layer.GetFeatureCount() != 1:
                    raise ValueError('1 feature only layers are supported')

                target_prj = osr.SpatialReference()
                if int(gdal.VersionInfo("VERSION_NUM")[0]) >= 3:
                    # GDAL 3 changes axis order:
                    #          https://github.com/OSGeo/gdal/issues/1546
                    target_prj.SetAxisMappingStrategy(
                        osr.OAMS_TRADITIONAL_GIS_ORDER)

                target_prj.ImportFromEPSG(4326)
                source_prj = shp_layer.GetSpatialRef()

                transform = None
                if not source_prj.IsSame(target_prj) or (
                        int(gdal.VersionInfo("VERSION_NUM")[0]) >= 3):
                    transform = osr.CoordinateTransformation(
                        source_prj, target_prj)

                for shp_fea in shp_layer:
                    geom = shp_fea.GetGeometryRef()

                    if transform:
                        geom.Transform(transform)
                    # Excluding Z dimension
                    geom.FlattenTo2D()
                    geom_wkt = geom.ExportToWkt()
                    break

                with open(wkt_filepath, 'w', newline='') as f_out:
                    f_out.write('geom\n"')
                    f_out.write(geom_wkt)
                    f_out.write('"\n')
            finally:
                del shp_ds
                del ogr_drv
                gc.collect()

        def gem_shapefile_get_fields_exec(input_filepath, tmp_path):
            with ZipFile(input_filepath, 'r') as zip:
                zip.extractall(path=tmp_path)

            shp_files = [f for f in os.listdir(tmp_path) if (
                f.endswith('.shp') or f.endswith('.SHP'))]

            if len(shp_files) != 1:
                raise ValueError(
                    'Not uniq .shp file not found in [%s] file.' %
                    input_filepath)

            shp_filename = shp_files[0]
            shp_filepath = os.path.join(tmp_path, shp_filename)

            ogr_drv = ogr.GetDriverByName('ESRI Shapefile')
            s_ds = ogr_drv.Open(shp_filepath)
            s_layer = s_ds.GetLayer()
            # here the layer name l_name = s_layer.GetName()
            ldefn = s_layer.GetLayerDefn()
            schema = []
            for n in range(ldefn.GetFieldCount()):
                fdefn = ldefn.GetFieldDefn(n)
                schema.append(fdefn.name)
            return schema

        if __name__ == '__main__':
            from zipfile import ZipFile

            if sys.argv[1] == 'esritxt':
                if len(sys.argv) < 5 or len(sys.argv) > 6:
                    sys.exit(2)
                input_filepath = sys.argv[2]
                csv_filepath = sys.argv[3]
                epsg_in = sys.argv[4]
                if len(sys.argv) > 5:
                    density = sys.argv[5]
                else:
                    density = None

                gem_esritxt_coreconv_exec(input_filepath, csv_filepath,
                                          epsg_in, density)
            elif sys.argv[1] == 'esritxt-to-wkt':
                if len(sys.argv) < 5 or len(sys.argv) > 7:
                    sys.exit(2)
                input_filepath = sys.argv[2]
                csv_filepath = sys.argv[3]
                epsg = int(sys.argv[4])
                if sys.argv[5] != '':
                    density = float(sys.argv[5])
                else:
                    density = None
                if len(sys.argv) > 6:
                    nodata_extra = sys.argv[6]
                else:
                    nodata_extra = None

                gem_esritxt2wkt_coreconv_exec(
                    input_filepath, csv_filepath,
                    epsg, density, nodata_extra)
            elif sys.argv[1] == 'shape':
                if len(sys.argv) < 6 or len(sys.argv) > 7:
                    sys.exit(2)
                input_filepath = sys.argv[2]
                csv_filepath = sys.argv[3]
                attrib = sys.argv[4]
                p_size = sys.argv[5]
                if len(sys.argv) > 6:
                    density = sys.argv[6]
                else:
                    density = None

                gem_shape_coreconv_exec(input_filepath, csv_filepath,
                                        attrib, p_size, density)
            elif sys.argv[1] == 'shapefile-get-fields':
                if len(sys.argv) != 4:
                    sys.exit(2)
                input_filepath = sys.argv[2]
                tmp_path = sys.argv[3]

                schema = gem_shapefile_get_fields_exec(input_filepath,
                                                       tmp_path)
                for i in schema:
                    print(i)
            elif sys.argv[1] == 'shape-to-wkt':
                if len(sys.argv) != 4:
                    sys.exit(2)
                input_filepath = sys.argv[2]
                wkt_filepath = sys.argv[3]

                gem_shape2wkt_coreconv_exec(input_filepath, wkt_filepath)
            elif sys.argv[1] == 'titan2':
                if len(sys.argv) != 5:
                    sys.exit(2)
                input_filepath = sys.argv[2]
                csv_filepath = sys.argv[3]
                epsg_in = sys.argv[4]

                gem_titan2_coreconv_exec(input_filepath, csv_filepath,
                                         epsg_in)
            else:
                sys.exit(1)
            sys.exit(0)

except ImportError:
    # if gdal 2 not available delegate to external environment
    # geo-related operations
    pass

if not GDAL2_AVAILABLE:
    def gem_esritxt_coreconv_exec(input_filepath, csv_filepath, epsg_in,
                                  density):
        raise NotImplementedError(
            '"gem_esritxt_coreconv_exec" not implemented'
            ' with this environment')

    def gem_esritxt2wkt_coreconv_exec(input_filepath, csv_filepath,
                                      epsg_in, density, nodata_extra_in):
        raise NotImplementedError(
            '"gem_esritxt2wkt_coreconv_exec" not implemented'
            ' with this environment')

    def gem_shape_coreconv_exec(input_filepath, csv_filepath,
                                attrib, p_size, density):
        raise NotImplementedError(
            '"gem_shape_coreconv_exec" not implemented'
            ' with this environment')

    def gem_shape2wkt_coreconv_exec(input_filepath, wkt_filepath):
        raise NotImplementedError(
            '"gem_shape2wkt_coreconv_exec" not implemented'
            ' with this environment')

    def gem_titan2_coreconv_exec(input_filepath, csv_filepath, epsg_in):
        raise NotImplementedError(
            '"gem_titan2_coreconv_exec" not implemented'
            ' with this environment')

# I'm sorry, E402 of python linter appear for a good reason.
import tempfile
import shutil
import subprocess
from openquakeplatform_ipt.common import (
    get_full_path, get_tmp_path, zwrite_or_collect)
from zipfile import ZipFile

GEM_PYTHONPATH_BIN = '/opt/openquake/bin/python3'

def reexecute_with_engine_py3(args_in, out=None):
    py_name = (__file__[:-1] if __file__.endswith('.pyc') else __file__)
    args = [GEM_PYTHONPATH_BIN, py_name]
    args.extend(args_in)
    sp = subprocess.Popen(
        args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = sp.communicate()
    if sp.returncode != 0:
        raise ValueError("Return code: %d\nSTDOUT: %s\nSTDERR: %s" % (
            sp.returncode, output, err))
    if type(out) is list:
        out.append(output)
    return True

def gem_esritxt_coreconv_delegate(input_filepath, csv_filepath, epsg_in,
                                  density):
    params = ['esritxt', input_filepath, csv_filepath, epsg_in]
    if density:
        params.append(density)
    return reexecute_with_engine_py3(params)

def gem_esritxt_coreconv(input_filepath, csv_filepath, epsg_in, density):
    if GDAL2_AVAILABLE:
        method = gem_esritxt_coreconv_exec
    else:
        method = gem_esritxt_coreconv_delegate

    return method(input_filepath, csv_filepath, epsg_in, density)

def gem_esritxt2wkt_coreconv_delegate(input_filepath, csv_filepath,
                                      epsg_in, density, nodata_extra):
    params = ['esritxt-to-wkt', input_filepath, csv_filepath,
              epsg_in]
    if density:
        params.append(density)
    else:
        params.append('')

    if nodata_extra:
        params.append(json.dumps(nodata_extra))

    return reexecute_with_engine_py3(params)

def gem_esritxt2wkt_coreconv(input_filepath, csv_filepath, epsg_in, density,
                             nodata_extra):
    if GDAL2_AVAILABLE:
        method = gem_esritxt2wkt_coreconv_exec
    else:
        method = gem_esritxt2wkt_coreconv_delegate

    return method(input_filepath, csv_filepath, epsg_in, density, nodata_extra)

def gem_shape_coreconv_delegate(input_filepath, csv_filepath,
                                attrib, p_size, density):
    params = ['shape', input_filepath, csv_filepath, attrib, p_size]
    if density:
        params.append(density)

    return reexecute_with_engine_py3(params)

def gem_shape_coreconv(input_filepath, csv_filepath,
                       attrib, p_size, density):
    if GDAL2_AVAILABLE:
        method = gem_shape_coreconv_exec
    else:
        method = gem_shape_coreconv_delegate

    return method(input_filepath, csv_filepath,
                  attrib, p_size, density)

def gem_shape2wkt_coreconv_delegate(input_filepath, wkt_filepath):
    params = ['shape-to-wkt', input_filepath, wkt_filepath]

    return reexecute_with_engine_py3(params)

def gem_shape2wkt_coreconv(input_filepath, wkt_filepath):
    if GDAL2_AVAILABLE:
        method = gem_shape2wkt_coreconv_exec
    else:
        method = gem_shape2wkt_coreconv_delegate

    return method(input_filepath, wkt_filepath)

def gem_titan2_coreconv_delegate(input_filepath, csv_filepath, epsg_in):
    params = ['titan2', input_filepath, csv_filepath, epsg_in]
    return reexecute_with_engine_py3(params)

def gem_titan2_coreconv(input_filepath, csv_filepath, epsg_in):
    if GDAL2_AVAILABLE:
        method = gem_titan2_coreconv_exec
    else:
        method = gem_titan2_coreconv_delegate

    return method(input_filepath, csv_filepath, epsg_in)

def gem_shapefile_get_fields_delegate(input_filepath, tmp_path):
    params = ['shapefile-get-fields', input_filepath, tmp_path]
    out = []

    if reexecute_with_engine_py3(params, out):
        return out[0].strip().split('\n')
    else:
        return False

def gem_shapefile_get_fields(userid, namespace, filename):
    input_filepath = get_full_path(userid, namespace, filename)
    tmp_basepath = get_tmp_path(userid)
    tmp_path = tempfile.mkdtemp(prefix='shpin_', dir=tmp_basepath)

    if GDAL2_AVAILABLE:
        method = gem_shapefile_get_fields_exec
    else:
        method = gem_shapefile_get_fields_delegate

    try:
        ret = method(input_filepath, tmp_path)
    finally:
        if tmp_path and os.path.exists(tmp_path):
            shutil.rmtree(tmp_path)

    return ret

def gem_esritxt_converter(z, userid, namespace, filename, file_collect,
                          epsg_in, density):
    csv_filepath = None
    csv_filename = ""
    try:
        input_filepath = get_full_path(userid, namespace, filename)
        output_file = os.path.basename(filename)
        extension = os.path.splitext(output_file)[1][1:]
        if not extension:
            raise ValueError('extension of input file not found')

        csv_filename = output_file[:-4] + "__" + extension + ".csv"

        tmp_path = get_tmp_path(userid)
        csv_filepath = os.path.join(tmp_path, csv_filename)
        gem_esritxt_coreconv(input_filepath, csv_filepath, epsg_in, density)
        zwrite_or_collect(z, userid, 'tmp', csv_filename, file_collect)
    finally:
        if os.path.exists(csv_filepath):
            os.remove(csv_filepath)

    return csv_filename

def gem_esritext2wkt_converter(z, userid, namespace, filename, file_collect,
                               epsg_in, density, nodata_extra):
    csv_filepath = None
    csv_filename = ""
    try:
        input_filepath = get_full_path(userid, namespace, filename)
        output_file = os.path.basename(filename)
        extension = os.path.splitext(output_file)[1][1:]
        if not extension:
            raise ValueError('extension of input file not found')

        csv_filename = output_file[:-4] + "__" + extension + ".csv"

        tmp_path = get_tmp_path(userid)
        csv_filepath = os.path.join(tmp_path, csv_filename)
        gem_esritxt2wkt_coreconv(input_filepath, csv_filepath, epsg_in,
                                 density, nodata_extra)
        zwrite_or_collect(z, userid, 'tmp', csv_filename, file_collect)
    finally:
        if os.path.exists(csv_filepath):
            os.remove(csv_filepath)

    return csv_filename

def gem_titan2_converter(z, userid, namespace, filename, file_collect,
                         epsg_in):
    """
    Note: Only Pileheight!
    Nx=1024: X={              641941,              645559}
    Ny=1024: Y={             2154941,             2158559}
    Pileheight=
    """
    csv_filepath = None
    csv_filename = ""
    try:
        input_filepath = get_full_path(userid, namespace, filename)
        output_file = os.path.basename(filename)
        extension = os.path.splitext(output_file)[1][2:]
        if not extension:
            raise ValueError('extension of input file not found')

        csv_filename = output_file[:-7] + "__" + extension + ".csv"

        tmp_path = get_tmp_path(userid)
        csv_filepath = os.path.join(tmp_path, csv_filename)
        gem_titan2_coreconv(input_filepath, csv_filepath, epsg_in)
        zwrite_or_collect(z, userid, 'tmp', csv_filename,
                          file_collect)
    finally:
        if os.path.exists(csv_filepath):
            os.remove(csv_filepath)

    return csv_filename

def gem_shape_converter(z, userid, namespace, filename, file_collect,
                        p_size, attrib, density):
    if z is None:
        raise ValueError("Shapefile input format not yet supported for"
                         " hybridge QGIS integration")

    input_filepath = get_full_path(userid, namespace, filename)
    tmp_basepath = get_tmp_path(userid)
    tmp_path = tempfile.mkdtemp(prefix='shpin_', dir=tmp_basepath)
    try:
        with ZipFile(input_filepath, 'r') as zip:
            zip.extractall(path=tmp_path)

        shp_files = [f for f in os.listdir(tmp_path) if (
            f.endswith('.shp') or f.endswith('.SHP'))]

        if len(shp_files) != 1:
            raise ValueError('Not uniq .shp file not found in [%s] file.' %
                             filename)

        shp_filename = shp_files[0]
        csv_filename = shp_filename[:-4] + "__shp.csv"
        shp_filepath = os.path.join(tmp_path, shp_filename)
        csv_filepath = os.path.join(tmp_path, csv_filename)

        gem_shape_coreconv(shp_filepath, csv_filepath,
                           attrib, p_size, density)

        zwrite_or_collect(z, userid, 'tmp',
                          csv_filepath, file_collect)
        csv_name = os.path.basename(csv_filename)

    finally:
        if tmp_path and os.path.exists(tmp_path):
            shutil.rmtree(tmp_path)

    return csv_name

def gem_shape2wkt_converter(z, userid, namespace, filename, file_collect):
    if z is None:
        raise ValueError("Shapefile input format not yet supported for"
                         " hybridge QGIS integration")

    input_filepath = get_full_path(userid, namespace, filename)
    tmp_basepath = get_tmp_path(userid)
    tmp_path = tempfile.mkdtemp(prefix='shpin_', dir=tmp_basepath)
    try:
        with ZipFile(input_filepath, 'r') as zip:
            zip.extractall(path=tmp_path)

        shp_files = [f for f in os.listdir(tmp_path) if (
            f.endswith('.shp') or f.endswith('.SHP'))]

        if len(shp_files) != 1:
            raise ValueError('Not uniq .shp file not found in [%s] file.' %
                             filename)

        shp_filename = shp_files[0]
        wkt_filename = shp_filename[:-4] + "__shp.csv"
        shp_filepath = os.path.join(tmp_path, shp_filename)
        wkt_filepath = os.path.join(tmp_path, wkt_filename)

        gem_shape2wkt_coreconv(shp_filepath, wkt_filepath)

        zwrite_or_collect(z, userid, 'tmp',
                          wkt_filepath, file_collect)
        wkt_name = os.path.basename(wkt_filename)

    finally:
        if tmp_path and os.path.exists(tmp_path):
            shutil.rmtree(tmp_path)

    return wkt_name

def gem_input_converter(z, key, input_type, userid, namespace, filename,
                        file_collect, *args):
    """
    a part of mandatory fields, optional are managed as follow:
    input_type == VolConst.ty_shape:
        p_size = args[0]
        attrib = args[1]
        density = args[2] (value or None)

    input_type == VolConst.ty_text && key != pyro:
        epsg_in = arg[0]
        density = args[2] (value or None)
    input_type == VolConst.ty_text && key == pyro:
        epsg_in = arg[0]
    """
    if input_type == VolConst.ty_shap:
        p_size = args[0]
        attrib = args[1]
        density = args[2]
        return gem_shape_converter(z, userid, namespace, filename,
                                   file_collect, p_size, attrib, density)
    elif input_type == VolConst.ty_swkt:
        return gem_shape2wkt_converter(z, userid, namespace, filename,
                                       file_collect)
    elif input_type == VolConst.ty_text:
        epsg_in = args[0]
        density = args[1]

        if key in [VolConst.ph_ashf]:
            return gem_esritxt_converter(
                z, userid, namespace, filename, file_collect,
                epsg_in, density)
    elif input_type == VolConst.ty_twkt:
        epsg_in = args[0]
        density = args[1]
        nodata_extra = args[2]

        if key == VolConst.ph_lava:
            return gem_esritext2wkt_converter(
                z, userid, namespace, filename, file_collect,
                epsg_in, density, nodata_extra)
        elif key == VolConst.ph_laha:
            return gem_esritext2wkt_converter(
                z, userid, namespace, filename, file_collect,
                epsg_in, density, nodata_extra)
        else:  # pyro case
            return gem_titan2_converter(
                z, userid, namespace, filename, file_collect,
                epsg_in)