import pygame

from src.animation import Animation
from src.common import EventInfo, Position
from src.enums import EntityStates
from src.utils import reverse_animation

class Cat:
    def __init__(self, assets: dict):
        self.screen_size = pygame.display.get_window_size()
        self.animations = {
            "walk_left": Animation(assets["cat_walk"], 0.05),
            "idle_left": Animation(assets["cat_idle"], 0.005),
            "jump_left": Animation(assets["cat_jump"], 1),
        }
        self.animations |= {
            "walk_right": reverse_animation(self.animations["walk_left"]),
            "idle_right": reverse_animation(self.animations["idle_left"]),
            "jump_right": reverse_animation(self.animations["jump_left"]),
        }
        self.pos = pygame.Vector2()
        self.vel = pygame.Vector2(1)
        self.gravity = 0.25
        self.rect = self.animations["jump_left"].frames[0].get_rect()

        self.state = EntityStates.WALK
        self.facing = "right"

    def move_dnd(self, event_info: EventInfo):
        """Drag-and-drop cat movement"""
        self.rect.center = event_info["mouse_pos"]
        self.pos.xy = self.rect.topleft
        self.vel.y = max(event_info["mouse_vel"].y, -8)
        self.vel.x = max(min(event_info["mouse_vel"].x, 20), -20)

    def move(self, event_info: EventInfo):
        dt = event_info["dt"]
        self.pos += self.vel * dt
        self.rect.topleft = self.pos
        self.vel.y += self.gravity * dt

        if self.vel.x not in (-1, 1):
            self.vel.x = round(pygame.Vector2(self.vel.x).move_towards((1, 0), round(1 * dt)).x)

        if self.vel.x > 0:
            self.facing = "right"
        elif self.vel.x < 0:
            self.facing = "left"

    def update(self, event_info: EventInfo):
        if event_info["mouse_btn"][0]:
            self.move_dnd(event_info)
        else:
            self.move(event_info)

        if self.rect.bottom >= self.screen_size[1]:
            self.vel.y = 0
            self.rect.bottom = self.screen_size[1]
            self.pos.y = self.rect.top
        elif self.rect.top < 0:
            self.vel.y = 0
            self.rect.top = 0
            self.pos.y = self.rect.top

        if self.rect.left <= 0:
            self.vel.x *= -1
            self.rect.left = 0
            self.pos.x = self.rect.x
        elif self.rect.right >= self.screen_size[0]:
            self.vel.x *= -1
            self.rect.right = self.screen_size[0]
            self.pos.x = self.rect.x

    def draw(self, screen: pygame.Surface, event_info: EventInfo):
        self.animations[f"{self.state.value}_{self.facing}"].play(
            screen, self.pos, event_info["dt"]
        )


import frappe

def get_context(context):
	# --- OLD ---
	# Leaving here for reference

	# context.ebooks = frappe.get_all(
	# 	"eBook",
	# 	fields=[
	# 		"name",
	# 		"cover_image",
	# 		"route",
	# 		"creation",
	# 		"author.full_name as author_name",
	# 	],
	# 	filters={"is_published": True},
	# 	order_by="creation desc"
	# )

	from frappe.query_builder.functions import Count

	EBook = frappe.qb.DocType("eBook")
	Author = frappe.qb.DocType("Author")
	EBookOrder = frappe.qb.DocType("eBook Order")

	query = (
		frappe.qb.from_(EBook)
		.left_join(Author)
		.on(Author.name == EBook.author)
		.left_join(EBookOrder)
		.on((EBookOrder.ebook == EBook.name) & (EBookOrder.status == "Paid"))
		.where(EBook.is_published == True)
		.groupby(EBook.name)
		.select(
			EBook.route,
			EBook.cover_image,
			EBook.name,
			Author.full_name.as_("author_name"),
			Count(EBookOrder.name).as_("sales_count"),
		)
		.orderby(EBook.creation)
	)

	context.ebooks = query.run(as_dict=True)


import PIL.Image
import cv2 as cv
import pandas as pd
import base64
from sklearn.neighbors import NearestNeighbors
import numpy as np
import streamlit as st
import PIL
import torch
from torchvision.models import resnet50

def preprocessing2(img):
  return torch.FloatTensor(cv.resize(img, (224, 224))).permute(2, 0, 1).unsqueeze(0) / 255.

def neiron_emb(img_path, model):
  img = cv.imread(img_path, cv.IMREAD_COLOR)
  img = cv.cvtColor(img, cv.COLOR_BGR2RGB)
  inp = preprocessing2(img)
  with torch.no_grad():
      out = model(inp)
  emb = out[0].numpy()
  return emb

@st.cache(allow_output_mutation=True)
def loadBases():
    emb_db = './embedBaseDf11.csv'
    emb_base = pd.read_csv(emb_db, delimiter=',')
    emb_base['embed'] = emb_base['embed'].apply(
        lambda x: np.frombuffer(base64.b64decode(bytes(x[2:-1], encoding='ascii')), dtype=np.float32))
    return emb_base

def encodeImage(arr) -> np.ndarray:
    emds = []
    for i in arr:
        emb, _ = np.histogram(i, 2048)
        emds.append(emb)
    return emds

def workWithDb(img, classifier, db, db_neighbours):
    predhist = neiron_emb(img, classifier)
    distances, indices = db_neighbours.kneighbors(predhist.reshape(1, -1), return_distance=True)
    print(indices)
    return db.loc[indices[0], ['path']].values, distances[0]
    #return db.loc[indices[0]-2, ['path']].values, distances[0]

def main():
    loaded_model = resnet50(True).eval()
    database = loadBases()
    db_neighbours = NearestNeighbors(n_neighbors=5, metric='cosine')
    # print(type(database))
    emdbs = encodeImage(database['embed'].values)
    db_neighbours.fit(emdbs, y=list(range(len(database))))
    up_file = st.file_uploader('Choice file', type=['jpeg', 'jpg', 'webp', 'png', 'tiff'])
    if up_file is not None:
        try:
            img = PIL.Image.open(up_file)
            img = PIL.ImageOps.exif_transpose(img)
            img_paths, dists = workWithDb(np.array(img), loaded_model, database, db_neighbours)
            print(img_paths)
            for i in range(len(img_paths)):
                st.image(PIL.Image.open('C:'+img_paths[i][0]),
                         caption='Image {} with dist {}'.format(i + 1, f'{dists[i]:.3f}', width=580))
        except Exception as e:
            st.write('CRASHED:{}'.format(e))

# main()

if __name__ == '__main__':
    main()


from proctool import genID, currentTS, b64LSExtract, flatLSDic
from constrlts import get_RLT_id

def makeAC1(_cid, pa):
    if 'M7519' in pa['cfg']:
        theme = pa['cfg']['M7519']
    else:
        theme = 'default'
    if "M1507" in pa['cfg']: # 'Title'
        pagetitle = pa['cfg']['M1507']
    else:
        pagetitle = "TXkgRmFtaWx5"
    if "M1504" in pa['cfg']:
        loginpwd = pa['cfg']['M1504']['login'][0]
    else:
        loginpwd = '******'
    if "M1508" in pa['cfg']:
        lang = pa['cfg']['M1508']
    else:
        lang = 'en'
    if "M1502" in pa['cfg']:
        email = pa['cfg']['M1502']
    else:
        email = ''
    if "M7534" in pa['cfg']:
        trustees = pa['cfg']['M7534']
    else:
        trustees = []
    ac1 = {
        '_id': genID(_cid, "AC1"), # cat: AC1: user-account, no subcat
        'TS': currentTS,
        'cat': 'AC1',
        'subcat': '0000',
        'card': {
            'Name': 'user account',
            'Descr': {
                'LSS': ['PAGETITLE','NAME'],
                'NAME': 'en:dXNlciBhY2NvdW50', # user account
                'PAGETITLE': pagetitle,
                'LOGINPWD': loginpwd,
                'HASH': "sha256",
                'THEME': theme,
                'LANG': lang,
                'EMAIL': email,
                'TRUSTEES': trustees
            }
        },
        'rels': {
            get_RLT_id('OWNED_BY', 'AC1', 'PA1'): [pa['_id']] # RL_OWNED_BY
        }
    }
    return ac1

def transPa(pa, dics, idmap):
    _id = pa['_id']
    _cid = _id[:7]  #_id = 'TC6H8EU-PA-<6><ts>'
    _cat = 'PA1'
    _subcat = 'AUEA'
    _rels = {}
    sex = pa['sex']
    _rlt1 = get_RLT_id('OWNS', _cat,'DC2')      # PA1 owning doc
    _rlt2 = get_RLT_id('CHILD_OF', _cat, 'PA2') # PA1 child-of PA2
    if sex == 'male':
        _rlt3 = get_RLT_id('MALE_OF','PA1','PA2')  # PA1 male of marriage-bond
    else:
        _rlt3 = get_RLT_id('FEMALE_OF','PA1','PA2')   # PA1 female of PA2
    _rlt4 = get_RLT_id('OWNS','PA1','DC1')            # PA1 owns folder(DC1)
    _rlt5 = get_RLT_id('OWNS','PA1','AC1')            # PA1 owns account AC1
    for k, v in pa.get('iddict',{}).items():
        if k == "nutshell":
            _rels.setdefault(_rlt1, []).append(v) # RL_OWNING nutshell
        elif k == "parents":
            _rels[_rlt2] = v # RL_CHILD_OF
        elif k == "portrait":
            _rels.setdefault(_rlt1,[]).append(v) # RL_OWNING portrait
        elif k == "spouses":
            _rels[_rlt3] = v # RL_HAS_MARR_BOND
        elif k == "ips":
            _rels[_rlt4] = v # RL_OWNING info-pane/folder (DC1)
        else:
            print('pa has unknown iddict-key: ' + k)
    dic = {
        '_id': genID(_cid, _cat, _subcat),
        'TS': currentTS,
        'cat': _cat,
        'subcat': _subcat,
        'card': {
            'Name': b64LSExtract(pa['tname']),
            'Descr': {
                'LSS': ['NAME'],
                'NAME': flatLSDic(pa['tname']),
                'DOB': pa['dob'],
                'DOD': pa['dod'],
                'POB': flatLSDic(pa.get('pob','')),
                'POD': flatLSDic(pa.get('pod','')),
                'GENDER': pa.get('sex','male'),
                'ROLE': pa.get('role','1'),
                'MW_ID': pa['_id'],
            }
        },
        'rels': _rels
    }
    if _id == "TC6H8EU-PA-AFSmUA1408745022739":
        print('new id: '+dic['_id'])

    if 'cfg' in pa: # theme
        ac1 = makeAC1(_cid, pa)
        dic['rels'][_rlt5] = [ac1['_id']]
        dics[ac1['_id']] = ac1

    dics[dic['_id']] = dic
    idmap[pa['_id']] = dic['_id']


# -*- coding: utf-8 -*-
"""
Created on Wed Apr 27 11:51:21 2022

@author: Sanmars
"""

def carga_de_datos (nombre_archivo:str) -> dict: #1
    avistamientos = {}
    archivo = open(nombre_archivo,"r", encoding="utf-8")
    archivo.readline()

    linea = archivo.readline()
    while (len(linea) >0):
        datos = linea.strip("\n").split(",")
        avistamiento = {}
        avistamiento["datatime"]= datos[0]
        avistamiento["city"]= datos[1]
        avistamiento["state"]= datos[2]
        avistamiento["shape"]= datos[4]
        avistamiento["duration"]= float(datos[5])
        avistamiento["comments"]= datos[6]
        avistamiento["date posted"]= datos[7]
        avistamiento["latitude"]= float(datos[8])
        avistamiento["longitude"]= float(datos[9])
        if datos[3] not in avistamientos:
            avistamientos[datos[3]]=[avistamiento]
        else:
            avistamientos[datos[3]].append(avistamiento)
        linea=archivo.readline()
    archivo.close()
    return avistamientos

def avistamientos_en_fecha (avistamientos:dict, fecha:str) ->list:
    lista = []
    for pais in avistamientos:
        for avistamiento in avistamientos[pais]:
            if fecha in avistamiento["datatime"]:
                lista.append(avistamiento)
    return lista

def avistamientos_por_ciudad(avistamientos:dict) -> dict: #3
    ciudades = {}
    for pais in avistamientos:
        for ciudad in avistamientos[pais]:
            if ciudad["city"] not in ciudades:
                nombre_ciudad = []
            else:
                nombre_ciudad = ciudades[ciudad["city"]]
            ciudades[ciudad["city"]]=nombre_ciudad
            nombre_ciudad.append(ciudad)
    return ciudades

def avistamientos_mas_de_x_segundos (avistamientos:dict,segundos:float) -> dict:#4
    avistamiento_x_segundos = avistamientos
    for pais in avistamientos:
        for ciudad in avistamientos[pais]:
            if ciudad["duration"] < segundos:
                avistamientos[pais].remove(ciudad)
    return avistamiento_x_segundos

def avistamientos_por_rango_de_fechas (avistamientos:dict, inicio:str, final:str) -> str: #5
    lista = []
    for pais in avistamientos:
        for avistamiento in avistamientos[pais]:
            if avistamiento["datatime"] >= inicio and avistamiento["datatime"] <= final:
                lista.append(avistamiento)
    return lista

from math import radians, cos, sin, asin, sqrt
def distancia_entre_dos_puntos(lat1: float, lon1: float, lat2: float, lon2: float) -> float:
    lon1 = radians(lon1)
    lon2 = radians(lon2)
    lat1 = radians(lat1)
    lat2 = radians(lat2)

    dif_lon = lon2 - lon1
    dif_lat = lat2 - lat1
    a = sin(dif_lat / 2)**2 + cos(lat1) * cos(lat2) * sin(dif_lon / 2)**2
    c = 2 * asin(sqrt(a))
    return c * 6371

def avistamientos_en_radio_determinado (avistamientos:dict, lat:float,lon:float, radio:float) -> list: #6
    respuesta = []
    for pais in avistamientos:
        for avistamiento in avistamientos[pais]:
            if distancia_entre_dos_puntos(lat, lon, avistamiento["latitude"], avistamiento["longitude"]) < radio:
                respuesta.append(avistamiento)
    return respuesta

def minimo_x_avistamientos_en_mes(avistamientos:dict, cantidad:int,fecha:str) -> bool: #7
    cantidad_fecha = 0
    respuesta = False
    for pais in avistamientos:
        for avistamiento in avistamientos[pais]:
            if fecha in avistamiento["datatime"]:
                cantidad_fecha+=1
    if cantidad_fecha >= cantidad:
        respuesta = True
    return respuesta

def dar_avistamiento_mas_corto_y_largo_por_pais (avistamientos:dict,pais:str) -> dict: #8
    respuesta = {}
    respuesta["corto"] = 0
    respuesta ["largo"] = 0
    for avistamiento in avistamientos[pais]:
        if respuesta["corto"] == 0:
            corto = avistamiento["duration"]
            respuesta["corto"] = avistamiento
        if respuesta["largo"] == 0:
            respuesta["largo"] = avistamiento
            largo = avistamiento["duration"]
        elif largo < avistamiento["duration"]:
            largo = avistamiento["duration"]
            respuesta["largo"] = avistamiento
        elif avistamiento["duration"]< corto:
            corto = avistamiento["duration"]
            respuesta["corto"] = avistamiento
    return respuesta

def avistamientos_por_forma (avistamientos:dict) -> dict:#9.1
    avistamientos_forma = {}
    for pais in avistamientos:
        for ciudad in avistamientos[pais]:
            if ciudad["shape"] not in avistamientos_forma:
                forma = []
            else:
                forma = avistamientos_forma[ciudad["shape"]]
            avistamientos_forma[ciudad["shape"]]=forma
            forma.append(ciudad)
    return avistamientos_forma

def contar_avistamiento_por_forma (avistamientos:dict) -> dict:#9

    n_avistamientos_forma = {}
    avistamientos_forma = avistamientos_por_forma (avistamientos)
    for forma in avistamientos_forma:
        n_avistamientos_forma[forma] = len(avistamientos_forma[forma])
    return n_avistamientos_forma

def pais_con_mas_avistamientos_de_x_segundos (avistamientos:dict,segundos:float)->dict: #10
    pais_mas_de_x_segundos = {}
    pais_mas_de_x_segundos["pais"] =""
    pais_mas_de_x_segundos["avistamientos"] = 0
    mas_de_x_segundos = avistamientos_mas_de_x_segundos(avistamientos, segundos)
    for pais in mas_de_x_segundos:
        if len(mas_de_x_segundos[pais])> pais_mas_de_x_segundos["avistamientos"]:
            pais_mas_de_x_segundos["pais"] = pais
            pais_mas_de_x_segundos["avistamientos"] = len(mas_de_x_segundos[pais])
    return pais_mas_de_x_segundos

def avistamientos_que_contengan_cadena_en_comentarios (avistamientos:dict,cadena:str) -> list: #11
    lista = []
    for pais in avistamientos:
        for avistamiento in avistamientos[pais]:
            if cadena in avistamiento["comments"]:
                lista.append(avistamiento)
    return lista


import os
import numpy as np
import cv2
import json

class DataProvider():
    "this class creates machine-written text for a word list. TODO: change getNext() to return your samples."

    def __init__(self):
        words = os.listdir("HKR/ann")
        self.wordList = []
        for i in words:
            with open(f"/Users/alex/Documents/pythonProject/Terly/hw_recognition/HKR/ann/{i}") as f:
                if all(map(lambda x: not x.isalpha() or 1040 <= ord(x) <= 1103, json.loads(f.read())["description"])):
                    self.wordList.append(i)
        self.idx = 0

    def hasNext(self):
        "are there still samples to process?"
        return self.idx < len(self.wordList)

    def getNext(self):
        "TODO: return a sample from your data as a tuple containing the text and the image"
        word = self.wordList[self.idx]
        img = cv2.imread(f"/Users/alex/Documents/pythonProject/Terly/hw_recognition/HKR/img/{word.split('.')[0]}.jpg",
                         cv2.IMREAD_GRAYSCALE)
        with open(f"/Users/alex/Documents/pythonProject/Terly/hw_recognition/HKR/ann/{word}") as f:
            word = json.loads(f.read())["description"]
        self.idx += 1
        return (word, img)

def createIAMCompatibleDataset(dataProvider):
    "this function converts the passed dataset to an IAM compatible dataset"

    # create files and directories
    f = open('words.txt', 'w+')
    if not os.path.exists('sub'):
        os.makedirs('sub')
    if not os.path.exists('sub/sub-sub'):
        os.makedirs('sub/sub-sub')

    # go through data and convert it to IAM format
    ctr = 0
    while dataProvider.hasNext():
        sample = dataProvider.getNext()

        # write img
        cv2.imwrite('sub/sub-sub/sub-sub-%d.png' % ctr, sample[1])

        # write filename, dummy-values and text
        line = 'sub-sub-%d' % ctr + ' X X X X X X X ' + sample[0] + '\n'
        f.write(line)

        ctr += 1

if __name__ == '__main__':
    dataProvider = DataProvider()
    createIAMCompatibleDataset(dataProvider)


"""
From the file containing records of all posts, each line is like;

123456:the quick brown fox

Extract just the GUID and print the GUID to another file

"""

fid=open('posts-master','r')
fid2=open('postids-master','w')

lines=fid.read().split('\n')

for line in lines:
    # check if it is a valid line then print
    if line[:1] == '2':
        fid2.write(line[:7]+'\n')

fid2.close()
fid.close()


def check(a):
    if len(a)<2: return False
    if a!=a[::-1]: return False
    return True
a,b=map(int,input().split())
ds=[]
for i in range(a):
    ds.append(list(map(int,input().split())))
Max=0
ktra=0
for i in ds:
    for j in i:
        if check(str(j)):
            Max=max(Max,j)
            ktra=1
dem=0
if ktra==0:
    print("NOT FOUND")
else:
    print(Max)
    for i in ds:
        dem1=0
        for j in i:
            if j==Max:
                print("Vi tri ["+str(dem)+"]["+str(dem1)+"]")
            dem1 +=1
        dem +=1


'''
	A simple Flask app for making Stripe payments
	Author: Muneeb Ali | http://muneeb.org
	Modified from examples at http://stripe.com/docs/
	License: MIT (see LICENSE)
'''

from flask import Flask, render_template, request
import stripe

from config import stripe_keys
from config import DEFAULT_CHARGE_AMOUNT, DEFAULT_CHARGE_DESCRIPTION
from config import DB_NAME

stripe.api_key = stripe_keys['secret_key']

app = Flask(__name__)

#-----------------------------------
# MongoDB for stripe customers
from pymongo import MongoClient
c = MongoClient()
db = c[DB_NAME]
posts = db.posts

#-----------------------------------
@app.route('/')
def index():
	return render_template('index.html',
					key=stripe_keys['publishable_key'],
					amount_usd=get_amount_usd()
					)

#-----------------------------------
def get_amount_usd(amount=DEFAULT_CHARGE_AMOUNT):
		return float(amount) / 100

#-----------------------------------
def get_stripe_customer(customer_email):

	customer_info = posts.find_one({"customer_email":customer_email})

	if(customer_info == None):
		return False, customer_info
	else:
		return True, customer_info

#-----------------------------------
def save_stripe_customer(customer_email, customer_id):

	# If already have a customer by that email, delete old entry
	reply, entry = get_stripe_customer(customer_email)
	if(reply):
		posts.remove(entry)
	else:
		post = {"customer_email":customer_email,"customer_id":customer_id}
		posts.insert(post)

#-----------------------------------
def stripe_charge(customer_id,
			charge_amount=DEFAULT_CHARGE_AMOUNT,
			charge_descripton=DEFAULT_CHARGE_DESCRIPTION):

	try:
		charge = stripe.Charge.create(
			customer=customer_id,
			amount=charge_amount,
			currency='usd',
			description=charge_descripton
			)

	except stripe.CardError as e:

		# The card has been declined (or other error)
		return False, e

	return True, "successfully charged"

#-----------------------------------
@app.route('/charge', methods=['POST'])
def charge():

	customer_email = request.form['email']

	# Check if already have this customer
	customer_valid, customer_info = get_stripe_customer(customer_email)

	if(customer_valid):
		customer_id = customer_info['customer_id']
	else:

		customer = stripe.Customer.create(
					email=customer_email,
					card=request.form['stripeToken']
					)

		customer_id = customer.id

		# save the customer ID in DB for later use
		save_stripe_customer(customer_email, customer_id)

	# charge the customer (new or already present in DB)
	charge_valid, charge_msg = stripe_charge(customer_id)

	return render_template('charge.html',
					amount_usd=get_amount_usd(),
					customer_email=customer_email,
					charge_valid=charge_valid,
					charge_msg=charge_msg)

#-----------------------------------
@app.route('/recurring', methods=['POST'])
def recurring():

	customer_email = request.form['email']

	# Get customer_id from Mongo
	customer_valid, customer_info = get_stripe_customer(customer_email)

	if(customer_valid):
		customer_id = customer_info['customer_id']

		# Charge the customer (new or already present in DB)
		charge_valid, charge_msg = stripe_charge(customer_id)

	else:
		charge_valid = False
		charge_msg = "recurring customer doesn't exist"

	return render_template('charge.html',
					amount_usd=get_amount_usd(),
					customer_email=customer_email,
					charge_valid=charge_valid,
					charge_msg=charge_msg)

#-----------------------
if __name__ == '__main__':

	app.run(debug=True)


# -*- coding: utf-8 -*-
#!/usr/bin/python2
from lxml import etree
import sys
import os

from cobra.io import read_sbml_model, write_sbml_model
from cobra.io.sbml import create_cobra_model_from_sbml_file
from cobra import *

def without_metabo(file_draft,metabo,outFile) :

	parser = etree.XMLParser(remove_blank_text=True)

	with open(file_draft,"r") as file :
		line0 = file.readlines()[0]

	draft = etree.parse(file_draft,parser)
	root = "}".join(draft.getroot().tag.split("}")[:-1])+"}"

	listR = draft.getroot().find(root+'model/'+root+"listOfReactions")
	for reaction in listR :
		remove_reac = False
		reversible = reaction.attrib["reversible"]
		listOfReactant = reaction.find(root+"listOfReactants")
		try :
			for specie in listOfReactant :
				if specie.attrib['species'] == metabo :
					listR.remove(reaction)
					remove_reac = True
					break
		except :
			pass
		if remove_reac==False and reversible == "true" :
			listOfProduct = reaction.find(root+"listOfProducts")
			try :
				for specie in listOfProduct :
					if specie.attrib['species'] == metabo :
						listR.remove(reaction)
						break
			except :
				pass

	new_file = "/".join(file_draft.split("/")[:-1])+"/"+outFile
	with open(new_file,"wb") as file :
		file.write(line0.encode('utf-8'))
		draft.write(file, pretty_print=True)

	return new_file

if __name__ == '__main__':
	file_draft = sys.argv[1]
	metabo = sys.argv[2]
	try :
			outFile = sys.argv[3]
	except IndexError :
			outFile = "new_draft.sbml"

	new_file = without_metabo(file_draft,metabo,outFile)
	print(new_file)


import os
from supabase import create_client, Client

url: str = os.environ.get("SUPABASE_URL")
key: str = os.environ.get("SUPABASE_KEY")
supabase: Client = create_client(url, key)

response = supabase.table('Users').select("*").execute()
print(response)
data, count = supabase.table('Users').insert({"id": 1, "email": "t@t.com"}).execute()
print(data)

#func = supabase.functions()
#@asyncio.coroutine
#async def test_func(loop):
#  resp = await func.invoke("hello-world",invoke_options={'body':{}})
#  return resp

#loop = asyncio.get_event_loop()
#resp = loop.run_until_complete(test_func(loop))
#loop.close()


class SeatManager:

    def __init__(self, n: int):
        self.l = [i for i in range(1, n+1)]
        print(self.l)

    def reserve(self) -> int:
        temp = self.l.pop(0)
        return temp

    def unreserve(self, seatNumber: int) -> None:
        n = len(self.l)
        flag = 0
        for i in range(n):
            if self.l[i] > seatNumber:
                self.l.insert(i, seatNumber)
                flag = 1
                break
        if flag == 0:
            self.l.append(seatNumber)

# Your SeatManager object will be instantiated and called as such:
# obj = SeatManager(n)
# param_1 = obj.reserve()
# obj.unreserve(seatNumber)


import argparse
import os
import pickle
import sys

import numpy as np
import seaborn as sns

from pysrc import plots
from pysrc.sampling import baseline
from pysrc.services.data_service import load_site_data
from pysrc.services.file_service import (
    logs_dir_path,
    output_dir_path,
    plots_dir_path,
)

sys.path.append(os.path.abspath("src"))
sns.set(font_scale=1.2)

# Read arguments from stdin
parser = argparse.ArgumentParser(description="parameter settings")

parser.add_argument("--model", type=str, default="full_model_v3")
parser.add_argument("--xi", type=float, default=2.0)
parser.add_argument("--pf", type=float, default=21.5)
parser.add_argument("--pa", type=float, default=42.03)
parser.add_argument("--weight", type=float, default=0.25)
parser.add_argument("--sitenum", type=int, default=78)
parser.add_argument("--timehzn", type=int, default=200)

# Parse arguments
args = parser.parse_args()

# Create output and plots directories
output_dir = output_dir_path(**vars(args))
plots_dir = plots_dir_path(**vars(args))
logs_dir = logs_dir_path(**vars(args))

with open(output_dir / "results.pcl", "rb") as f:
    # Load the data from the file
    results = pickle.load(f)

# Load site data
(
    zbar_2017,
    gamma,
    z_2017,
    forest_area_2017,
    theta,
    site_theta_2017_df,
    site_gamma_2017_df,
    municipal_theta_df,
    municipal_gamma_df,
) = load_site_data(args.sitenum)

# Load coef baseline samples
fit = baseline.sample(model_name=args.model, num_samples=10000, num_sites=args.sitenum)
base_samples = np.concatenate(
    (fit.stan_variable("theta"), fit.stan_variable("gamma")), axis=1
)

try:
    adj_samples = results["final_sample"]
except KeyError:
    print(
        """
        Algorithm did not finish converging.
        Plotting adjusted samples from last iteration...
        """
    )
    adj_samples = results["collected_ensembles"][results["cntr"] - 1]

# Plot overlapped densities
plots.density_overlap(base_samples, adj_samples, plots_dir, args.sitenum)

# Plot absolute and percentage error
plots.traceplot_abs_error(results, plots_dir)
plots.traceplot_pct_error(results, plots_dir)

# Plot sampling time
plots.traceplot_sampling_time(results, plots_dir)

# Plot theta and gamma convergence
plots.traceplot_params_pct_error(results, plots_dir)
plots.traceplot_gammas(results, plots_dir)
plots.traceplot_thetas(results, plots_dir)

# Plot agg %change in z
plots.agg_Z_trajectory(
    z_2017=z_2017,
    zbar_2017=zbar_2017,
    results=results,
    num_sites=args.sitenum,
    plots_dir=plots_dir,
)

# Plot Z (for each site)
plots.Z_trajectory(results, plots_dir)

# Plot X (aggregate among sites)
plots.X_trajectory(results, plots_dir)

plots.delta_Z_trajectory(results, plots_dir)

# Plot adjustments
plots.adj_costs_trajectory(results, plots_dir)

# Plot trajectory of controls
plots.V_trajectory(results, plots_dir)
plots.U_trajectory(results, plots_dir)


class Solution:
    def minEatingSpeed(self, piles: List[int], h: int) -> int:
        # Applying binary search
        left, right = 1, max(piles)
        res = right
        while left <= right:
            mid = (right + left) // 2
            if self.canEatAll(piles, mid, h):
                res = min(mid, res)  # If can eat them all update res
                right = mid - 1 # Explore left
            else:
                left = mid + 1 # k is too small explore right
        return res

    def canEatAll(self, piles, k, h):
        countHours = 0
        for pile in piles:
            countHours += (pile // k) + (pile % k > 0)
            if countHours > h:
                return False
        return True

January LeetCoding Challenge/Jan 20 875. Koko Eating Bananas (Medium)/Solution.py


#! /Library/Frameworks/Python.framework/Versions/3.7/bin/python3
# By Nicholas Coletta, in the year 2019.
# This is part of my tour on codewars.com. The code below is a solution to a problem.

# INSTRUCTIONS: Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
# EXAMPLE:
# scramble('rkqodlw', 'world') ==> True
# scramble('cedewaraaossoqqyt', 'codewars') ==> True
# scramble('katas', 'steak') ==> False
from collections import Counter
def scramble(s1, s2):
    sone = Counter(s1)
    stwo = Counter(s2)
    diff = stwo - sone
    if len(diff) == 0:
        return True
    else:
        return False
# Both sets of code work. The commented is slower by about 2000ms. Which this challenge relied on performance.
''' compList = []
    for letter in s1:
        if letter in s2:
            if s2.count(letter) > compList.count(letter):
                compList.append(letter)
    print(compList)
    if len(compList) == len(s2):
        return True
    else:
        return False'''

print(scramble('rkqodlw', 'world'))


import os, sys, re
from PIL import Image
from os import listdir
from os.path import isfile, join

fscreenshots=open('../../public_html/screenshots/screenshots_.html','w')
f800x660=open('../../public_html/screenshots/800x660.html','w')
f800x600=open('../../public_html/screenshots/800x600.html','w')
f640x512=open('../../public_html/screenshots/640x512.html','w')
felse=open('../../public_html/screenshots/else.html','w')
v800x660=[]
v800x600=[]
v640x512=[]
velse=[]

def replaceStringInFile(filePath):
	'''
	output = open(tempName,'w')
	output.write(outtext)
	output.close()
	'''
	i1=Image.open(filePath)
	if (i1.size[0]==800) and (i1.size[1]==660):
		v800x660.append(filePath)
		ln='%s: (%d, %d)\n' % (i, i1.size[0], i1.size[1])
		ln='''
%s
\n''' % (filePath, filePath)
		ln='''

\n''' % (filePath, filePath)
		ln='''

 %s
''' % (filePath, filePath, filePath)
		ln=ln.replace('../../public_html/','')
		ln=ln.replace('screenshots/','')
		ln=ln.replace('dx9_','../dx9_')
		f800x660.write(ln);
	elif (i1.size[0]==800) and (i1.size[1]==600):
		v800x600.append(filePath)
		ln='%s: (%d, %d)\n' % (i, i1.size[0], i1.size[1])
		ln='''
%s
\n''' % (filePath, filePath)
		ln='''

\n''' % (filePath, filePath)
		ln='''

 %s
''' % (filePath, filePath, filePath)
		ln=ln.replace('../../public_html/','')
		ln=ln.replace('screenshots/','')
		ln=ln.replace('dx9_','../dx9_')
		f800x600.write(ln);
	elif (i1.size[0]==640) and (i1.size[1]==512):
		v640x512.append(filePath)
		ln='%s: (%d, %d)\n' % (i, i1.size[0], i1.size[1])
		ln='''
%s
\n''' % (filePath, filePath)
		ln='''

\n''' % (filePath, filePath)
		ln='''

 %s
''' % (filePath, filePath, filePath)
		ln=ln.replace('../../public_html/','')
		ln=ln.replace('screenshots/','')
		ln=ln.replace('dx9_','../dx9_')
		f640x512.write(ln);
	else:
		#print filePath, i1.size[0], i1.size[1]
		velse.append(filePath)
		ln='%s: (%d, %d)\n' % (i, i1.size[0], i1.size[1])
		ln='''
%s
\n''' % (filePath, filePath)
		ln='''

\n''' % (filePath, filePath)
		ln='''

 %s
''' % (filePath, filePath, filePath)
		ln=ln.replace('../../public_html/','')
		ln=ln.replace('screenshots/','')
		ln=ln.replace('dx9_','../dx9_')
		felse.write(ln);

def myfun(dummy, dirr, filess):
	#print '#3'
	#print dummy, dirr, filess
	#onlyfiles = [f for f in listdir(dirr) if isfile(join(dirr, f))]
	#print onlyfiles
	filess = [f for f in listdir(dirr) if isfile(join(dirr, f))]
	#print filess
	for child in filess:
	    #print child
	    if '.jpg' == os.path.splitext(child)[1] and os.path.isfile(dirr+'/'+child):
		    replaceStringInFile(dirr+'/'+child)
		    #print child

ln='''<TITLE>Screenshots</TITLE>
Screenshots

\n'

Screenshots (800, 660)

Screenshots (800, 600)

Screenshots (640, 512)

Screenshots

'''

ln1='<TITLE>Screenshots</TITLE>
Screenshots

\n'
ln2='

\n'

fscreenshots.write(ln)
f800x660.write(ln1)
f800x600.write(ln1)
f640x512.write(ln1)
felse.write(ln1)
v=['../../public_html']
for i in v:
	os.path.walk(i, myfun, 13)

f800x660.write(ln2)
f800x600.write(ln2)
f640x512.write(ln2)
felse.write(ln2)
f800x660.close()
f800x600.close()
f640x512.close()
felse.close()
fscreenshots.close()


import unittest
from io import StringIO
import pandas
import numpy

from woldrnaseq.gff2table import (
    tokenize,
    parse_attributes,
    AttributesParser,
    format_gtf_record,
    GFFParser,
    parse_score,
    parse_strand,
    parse_phase,
)

class TestAttributeParser(unittest.TestCase):
    def test_quoting_missing(self):
        p = AttributesParser(' ')
        self.assertRaises(ValueError, list, p.tokenize('a "b'))

    def test_embedded_sep(self):
        p = AttributesParser(' ')
        t = list(p.tokenize('a "b;c"; d 1'))
        self.assertEqual(t, ['a', ' ', '"b;c"', ';', 'd', ' ', '1'])

    def test_empty(self):
        p = AttributesParser()
        attributes = p('')
        self.assertEqual(attributes, 0)

    def test_function_empty(self):
        attributes = list(parse_attributes('', sep=' '))
        self.assertEqual(len(attributes), 0)

    def test_gtf_extra_spaces(self):
        p = AttributesParser(' ')
        t = list(p.tokenize(' a 1;    b   "b"; '))
        self.assertEqual(t, ['a', ' ', '1', ';', 'b', ' ', '"b"', ';'])

    def test_tokenize_gtf_extra_spaces(self):
        t = list(tokenize(' a 1;    b   "b"; ', sep=' '))
        self.assertEqual(t, ['a', ' ', '1', ';', 'b', ' ', '"b"', ';'])

    def test_gff_extra_spaces(self):
        p = AttributesParser('=')
        t = list(p.tokenize(' a=1;    b=  "b"; '))
        self.assertEqual(t, ['a', '=', '1', ';', 'b', '=', '"b"', ';'])

    def test_tokenize_gff_extra_spaces(self):
        t = list(tokenize(' a=1;    b=  "b"; ', sep='='))
        self.assertEqual(t, ['a', '=', '1', ';', 'b', '=', '"b"', ';'])

    @unittest.skip('We should suppress extra semicolons')
    def test_gff_extra_semicolons(self):
        p = AttributesParser('=')
        t = list(p.tokenize(' a=1;; b="b"; '))
        self.assertEqual(t, ['a', '=', '1', ';', 'b', '=', '"b"', ';'])

    def test_simple_gtf(self):
        p = AttributesParser()
        attributes = p('gene_id "gene1"')
        self.assertEqual(attributes, 1)
        self.assertIn('gene_id', p.terms)
        self.assertEqual(p.terms['gene_id'], {0: 'gene1'})
        self.assertIsInstance(p.terms['gene_id'][0], str)

    def test_numeric_gtf(self):
        p = AttributesParser()
        attributes = p('exon_number 1')
        self.assertEqual(attributes, 1)
        self.assertIn('exon_number', p.terms)
        self.assertEqual(p.terms['exon_number'], {0: 1})
        self.assertIsInstance(p.terms['exon_number'][0], int)

    def test_multi_value_gtf(self):
        p = AttributesParser(' ')
        attributes = p(
            'gene_id "gene1"; transcript_id "transcript1"; exon_number 1')
        self.assertEqual(attributes, 3)
        line_no = 0
        for name, expected, attribute_type in [
                ('gene_id', 'gene1', str),
                ('transcript_id', 'transcript1', str),
                ('exon_number', 1, int)]:

            self.assertIn(name, p.terms)
            self.assertEqual(p.terms[name], {line_no: expected})
            self.assertIsInstance(p.terms[name][line_no], attribute_type)

    def test_multi_value_gff(self):
        p = AttributesParser('=')
        attributes = p('gene_id=gene1;transcript_id=transcript1;exon_number=1')
        self.assertEqual(attributes, 3)
        line_no = 0
        for name, expected, attribute_type in [
                ('gene_id', 'gene1', str),
                ('transcript_id', 'transcript1', str),
                ('exon_number', 1, int)]:

            self.assertIn(name, p.terms)
            self.assertEqual(p.terms[name], {line_no: expected})
            self.assertIsInstance(p.terms[name][line_no], attribute_type)

    def test_gff_value_with_spaces(self):
        p = AttributesParser('=')
        t = list(p.tokenize('mol_type=genomic DNA'))
        self.assertEqual(t, ['mol_type', '=', 'genomic DNA'])

    def test_grcm38(self):
        p = AttributesParser('=')
        attributes = p('ID=id0;Dbxref=taxon:10090;Name=1;chromosome=1;gbkey=Src;genome=chromosome;mol_type=genomic DNA;strain=C57BL/6J')
        self.assertEqual(attributes, 8)
        line_no = 0
        for name, expected, attribute_type in [
                ('ID', 'id0', str),
                ('Dbxref', 'taxon:10090', str),
                ('Name', 1, int),
                ('chromosome1', 1, int),
                ('gbkey', 'Src', str),
                ('genome', 'chromosome', str),
                ('mol_type', 'genomic DNA', str),
                ]:

            self.assertIn(name, p.terms)
            self.assertEqual(p.terms[name], {line_no: expected})
            self.assertIsInstance(p.terms[name][line_no], attribute_type)

    def test_ignore_space(self):
        p = AttributesParser(' ', ignore=['chromosome', 'junk'])
        record = 'chromosome 1;ID id0;junk drawer'

        t = list(p.tokenize(record))
        self.assertEqual(t, [
            'chromosome', ' ', '1', ';',
            'ID', ' ', 'id0', ';',
            'junk', ' ', 'drawer'
        ])
        attributes = p(record)
        self.assertEqual(attributes, 1)
        self.assertIn('ID', p.terms)
        self.assertEqual(p.terms['ID'][0], 'id0')
        self.assertNotIn('chromosome', p.terms)
        self.assertEqual(p.reserved['chromosome'], 0)

    def test_ignore_equal(self):
        p = AttributesParser('=', ignore=['chromosome', 'junk'])
        record = 'chromosome=1;ID=id0;junk=drawer'

        t = list(p.tokenize(record))
        self.assertEqual(t, [
            'chromosome', '=', '1', ';',
            'ID', '=', 'id0', ';',
            'junk', '=', 'drawer'
        ])
        attributes = p(record)
        self.assertEqual(attributes, 1)
        self.assertIn('ID', p.terms)
        self.assertEqual(p.terms['ID'][0], 'id0')
        self.assertNotIn('chromosome', p.terms)
        self.assertEqual(p.reserved['chromosome'], 0)

    def test_no_stop_iteration(self):
        g = parse_attributes('chromosome 1;ID id0;junk drawer', sep=' ')

        try:
            attributes = dict(g)
            self.assertEqual(len(attributes), 3)
        except StopIteration:
            raise RuntimeError('Should not raise stop iteration')

class TestParseHelpers(unittest.TestCase):
    def test_parse_score(self):
        self.assertIs(parse_score('.'), numpy.nan)
        self.assertEqual(parse_score('1000'), 1000)
        self.assertEqual(parse_score('0'), 0)
        self.assertEqual(parse_score('0.5'), 0.5)

    def test_parse_strand(self):
        self.assertEqual(parse_strand('+'), 1)
        self.assertIs(parse_strand('.'), numpy.nan)
        self.assertEqual(parse_strand('-'), -1)
        self.assertIs(parse_strand('junk'), numpy.nan)

    def test_parse_phase(self):
        # should we test for
        self.assertIs(parse_phase('.'), numpy.nan)
        for i in ['0', '1', '2']:
            self.assertEqual(parse_phase(i), int(i))
        self.assertRaises(ValueError, parse_phase, '5')

class TestGFFParser(unittest.TestCase):
    def test_parse_simple_gtf(self):
        text = StringIO('''chr1	source	exon	1	1000	.	+	.	junk "drawer"''')
        p = GFFParser(' ')
        p.read_gff(text)
        self.assertEqual(p.gtf.shape, (1, 9))
        self.assertIn('chromosome', p.gtf.columns)
        self.assertIn('junk', p.gtf.columns)

    def test_parse_collision_gtf(self):
        """Make sure that the mandatory first 8 columns keep the correct name
        """
        text = StringIO('''chr1	source	exon	1	1000	.	+	.	chromosome "drawer"''')
        p = GFFParser(' ')
        p.read_gff(text)
        self.assertEqual(p.gtf.shape, (1, 9))
        self.assertEqual('chromosome', p.gtf.columns[0])
        self.assertEqual('chromosome1', p.gtf.columns[8])

    def test_parse_gtf(self):
        """Check a minimal realistic gtf file
        """
        text = StringIO('''chr1	source	exon	1	1000	.	+	.	gene_id "gene1"; transcript_id "transcript1"
chr1	source	exon	2000	2100	.	+	.	gene_id "gene2"; transcript_id "transcript1"
chr1	source	exon	2000	2150	.	+	.	gene_id "gene2"; transcript_id "transcript2"
''')
        p = GFFParser(' ')
        p.read_gff(text)
        self.assertEqual(p.gtf.shape, (3, 10))
        self.assertEqual(list(p.gtf.columns), [
            'chromosome', 'source', 'type', 'start', 'stop',
            'score', 'strand', 'frame', 'gene_id', 'transcript_id'])

        expected = [
            {'start':    1, 'stop': 1000, 'gene_id': 'gene1', 'transcript_id': 'transcript1'},
            {'start': 2000, 'stop': 2100, 'gene_id': 'gene2', 'transcript_id': 'transcript1'},
            {'start': 2000, 'stop': 2150, 'gene_id': 'gene2', 'transcript_id': 'transcript2'},
        ]
        for i, row in p.gtf.iterrows():
            for key in expected[i]:
                self.assertEqual(row[key], expected[i][key])
            self.assertEqual(p.attribute_parser.terms['transcript_id'][i],
                             expected[i]['transcript_id'])

    def test_format_gtf_record(self):
        gtf_data = '''chr1	source	exon	1	1000	.	+	.	gene_id "gene1"; transcript_id "transcript1";
chr1	source	exon	2000	2100	.	+	.	gene_id "gene2"; transcript_id "transcript1";
chr1	source	exon	2000	2150	.	+	.	gene_id "gene2"; transcript_id "transcript2";
'''
        text = StringIO(gtf_data)
        p = GFFParser(' ')
        p.read_gff(text)

        formatted = []
        for i, row in p.gtf.iterrows():
            formatted.append(format_gtf_record(row, value_sep=' ', field_sep='; '))

        assert gtf_data == '\n'.join(formatted) + '\n'

        text2 = StringIO('\n'.join(formatted))
        p2 = GFFParser(' ')
        p2.read_gff(text2)

        assert p.gtf.shape == p2.gtf.shape
        for column in p.gtf.columns:
            for x, y in zip(p.gtf[column], p2.gtf[column]):
                if pandas.isnull(x) and pandas.isnull(y):
                    continue
                elif x == y:
                    continue
                else:
                    raise AssertionError('x={x} does not equal y={y} in column {column}'.format(x=x,y=y,column=column))


#!/usr/bin/env python2.6
#$ -S /usr/bin/python2.6
#$ -cwd

from optparse import OptionParser
import sys
import re
import collections
import os
import math
sys.path.append(os.path.join(os.environ.get("ISACMD"),"bin"))
from dp_align import read_sequences

def read_table(fn_table):
    f_table = open(fn_table)
    table = {}
    header = f_table.readline()
    for line in f_table:
        terms = re.compile("\s+").split(line.strip())
        ## lifetime, wait
        table[terms[1]] = (int(terms[2]), int(terms[3]))
    f_table.close()
    return table

def read_table_trans(fn_table_trans):
    f_trans = open(fn_table_trans)
    table = {}
    header = f_trans.readline()
    for line in f_trans:
        terms = re.compile("\s+").split(line.strip())
        table[(terms[0],terms[1])] = int(terms[2])
    f_trans.close()
    return table

def read_dict(fn_dict):
    f_dict = open(fn_dict)
    dict = {}
    for line in f_dict:
        terms = re.compile("\s+").split(line.strip())
        dict[terms[0]] = terms[2]
    f_dict.close()
    return dict

def group_table(table,dict):
    table_group = {}
    for state, val in table.items():
        grp = dict[state]
        if grp in table_group:
            table_group[grp] = (table_group[grp][0] + val[0],
                                table_group[grp][1] + val[1])
        else:
            table_group[grp] = (val[0], val[1])
    return table_group

def group_trans(table_group_pre, trans, dict):
    table_group = table_group_pre
    trans_group = {}
    for state_pair, val in trans.items():
        grp_s = dict[state_pair[0]]
        grp_t = dict[state_pair[1]]
        if grp_s==grp_t:
            table_group[grp_s] = (table_group[grp_s][0],
                                  table_group[grp_s][1] + val)
        elif (grp_s,grp_t) in trans_group:
            trans_group[(grp_s,grp_t)] = trans_group[(grp_s,grp_t)] + val
        else:
            trans_group[(grp_s,grp_t)] = val
    return table_group, trans_group

def output_gml(fn_graph_conv, table_group, trans_group):

    try: f_out = open(fn_graph_conv, 'w')
    except IOError:
        sys.stderr.write("File"+ fn_out +" could not be opend.\n")
        sys.exit()

    f_out.write('graph [\n')
    f_out.write('  directed 1\n')

    sum_cnt = 0.0
    for state,val in table_group.items():
        sum_cnt += val[0]
    i = 0
    state_id = {}
    for state,val in table_group.items():
        f_out.write('  node [\n')
        f_out.write('    id ' + str(i) + '\n')
        f_out.write('    state "' + state + '"\n')
        f_out.write('    count ' + str(val[0]) + '\n')
        f_out.write('    count_rel ' + str(float(val[0])/sum_cnt) + '\n')
        f_out.write('    logcount ' + str(math.log10(float(val[0])/sum_cnt)) + '\n')
        f_out.write('    wait ' + str(val[1]) + '\n')
        f_out.write('  ]\n')
        state_id[state] = i
        i+=1

    sum_cnt_trans = 0.0
    for s_t, val in trans_group.items():
        sum_cnt += val
    for s_t, val in trans_group.items():
        f_out.write('  edge [\n')
        f_out.write('    source ' + str(state_id[s_t[0]]) + '\n')
        f_out.write('    target ' + str(state_id[s_t[1]]) + '\n')
        f_out.write('    count ' + str(val) + '\n')
        f_out.write('    count_rel ' + str(float(val)/sum_cnt) + '\n')
        f_out.write('    logcount ' + str(math.log10(float(val)/sum_cnt)) + '\n')
        f_out.write('  ]\n')

    f_out.close()

def _main():
    p = OptionParser()
    p.add_option('--i-table', dest='fn_table',
                 help="input file for state table")
    p.add_option('--i-table-trans', dest='fn_table_trans',
                 help="input file for state transition table")
    p.add_option('--i-state-dict', dest='fn_state_dict_in',
                 help="input file name for .fsa sequence file.")
    p.add_option('--o-graph-conv', dest='fn_graph_conv',
                 help="output file for the graph in GML format")

    opts, args = p.parse_args()

    dict = read_dict(opts.fn_state_dict_in)
    table = read_table(opts.fn_table)
    table_trans = read_table_trans(opts.fn_table_trans)

    table_group_pre = group_table(table, dict)
    table_group, trans_group = group_trans(table_group_pre, table_trans, dict)
    output_gml(opts.fn_graph_conv, table_group, trans_group)

if __name__ == '__main__':
    _main()


from ..mutations import neighborhood
from ._lib import find_datasets

def test_neighborhood():
    dataset = [
        (("ACG", 1), "CCG TCG GCG AAG ATG AGG ACA ACC ACT ACG")
    ] + find_datasets("neighborhood", lambda x: x.splitlines())

    for input_sample, output_sample in dataset:
        pattern, d = input_sample
        d = int(d)
        output_sample = set(output_sample.split())
        output = neighborhood(pattern, d)
        assert output == output_sample, "{0} != {1}".format(output, output_sample)

def main():
    test_neighborhood()
    print("Success!")

if __name__ == '__main__':
    main()


#! /usr/bin/env python3

"""
Hartree code for N-electron 1D harmonic quantum dot

- Related to FYS-4096 Computational Physics
- Test case using simpson integrations should give:

    Total energy      11.502873299221452
    Kinetic energy    3.622113606711247
    Potential energy  7.880759692510205

    Density integral  3.9999999999999996

- Job description in short (more details in the pdf-file):
  -- Problem 1: add/fill needed functions and details
  -- Problem 2: Include input and output as text file
  -- Problem 3: Include input and output as HDF5 file
"""
from numpy import *
from matplotlib.pyplot import *
import scipy.sparse as sp
import scipy.sparse.linalg as sla
from scipy.integrate import simps
import h5py
import os

FILENAMESAVE = "testa"
FILENAMELOAD = "testa"
SAVING = False
LOADING = False

def hartree_potential(ns,x):
    """
    Hartree potential using Simpson integration
    """
    Vhartree=0.0*ns
    for ix in range(len(x)):
        r = x[ix]
        f = 0.0*x
        for ix2 in range(len(x)):
            rp = x[ix2]
            f[ix2]=ns[ix2]*ee_potential(r-rp)
        Vhartree[ix]= simps(f, x)
    return Vhartree

def ee_potential(x):
    global ee_coef

    """ 1D electron-electron interaction """
    return ee_coef[0] / sqrt(x**2 + ee_coef[1])

def ext_potential(x,m=1.0,omega=1.0):
    """ 1D harmonic quantum dot """
    return 0.5*m*omega**2*x**2

def density(psis):
    ns=zeros((len(psis[0]),))

    for i in range(len(ns)):

        for idx in range(len(psis[:])):

            ns[i] += psis[idx][i] * conj(psis[idx][i])

    return ns

def initialize_density(x,dx,normalization=1):
    rho=exp(-x**2)
    A=simps(rho,x)
    return normalization/A*rho

def check_convergence(Vold,Vnew,threshold):
    difference_ = amax(abs(Vold-Vnew))
    print('  Convergence check:', difference_)
    converged=False
    if difference_ <threshold:
        converged=True
    return converged

def diagonal_energy(T,orbitals,x):
    """
    Calculate diagonal energy
    (using Simpson)
    """
    Tt=sp.csr_matrix(T)
    E_diag=0.0

    for i in range(len(orbitals)):
        evec=orbitals[i]
        E_diag+=simps(evec.conj()*Tt.dot(evec),x)
    return E_diag

def offdiag_potential_energy(orbitals,x):
    """
    Calculate off-diagonal energy
    (using Simpson)
    """
    U = 0.0
    for i in range(len(orbitals)-1):
        for j in range(i+1,len(orbitals)):
            fi = 0.0*x
            for i1 in range(len(x)):
                fj = 0.0*x
                for j1 in range(len(x)):
                    fj[j1]=abs(orbitals[i][i1])**2*abs(orbitals[j][j1])**2*ee_potential(x[i1]-x[j1])
                fi[i1]=simps(fj,x)
            U+=simps(fi,x)
    return U

def plot_orbitals(orbitals, x, ax):

    idx = 1
    for orb in orbitals:

        prob = orb * orb.conj()
        ax.plot(x, prob, label = "Density of electron {}".format(idx))
        idx += 1

def save_ns_in_ascii(ns,filename):
    s=shape(ns)
    f=open(filename+'_density.txt','w')
    for ix in range(s[0]):
        f.write('{0:12.8f}\n'.format(ns[ix]))
    f.close()
    f=open(filename+'_shape.txt','w')
    f.write('{0:5}'.format(s[0]))
    f.close()

def save_orbitals_in_ascii(orbitals, filename):

    f = open(filename+'_orbitals.txt','w')

    for orb in orbitals:

        for idx in range(len(orb)):

            f.write("{0:12.8f}\n".format(orb[idx]))

    f.close

def save_grid_in_ascii(x, filename):

    f = open(filename+'_grid.txt','w')

    for idx in range(len(x)):
        f.write("{0:12.8f}\n".format(x[idx]))

    f.close

def load_orbitals_in_ascii(filename):

    f = open(filename+"_shape.txt", 'r')

    for line in f:
        s = array(line.split(), dtype = int)
    f.close()

    d = loadtxt(filename+"_orbitals.txt")

    En = int(len(d) / s[0])

    orbitals = zeros((En, s[0]))

    for e in range(En):

        for idx in range(s[0]):

            orbitals[e, idx] = d[(e+1) * idx]

    return orbitals

def load_grid_from_ascii(filename):

    f = open(filename+"_shape.txt", 'r')

    for line in f:
        s = array(line.split(), dtype = int)
    f.close()

    x = zeros((s[0],))
    d = loadtxt(filename+"_grid.txt")

    for idx in range(s[0]):
        x[idx] = d[idx]

    return x

def load_ns_from_ascii(filename):
    f=open(filename+'_shape.txt','r')
    for line in f:
        s=array(line.split(),dtype=int)
    f.close()
    ns=zeros((s[0],))
    d=loadtxt(filename+'_density.txt')
    k=0
    for ix in range(s[0]):
        ns[ix]=d[k]
        k+=1
    return ns

def save_data_to_hdf5_file(fname,orbitals,density,N_e,occ,grid,ee_coefs):
    return

def calculate_SIC(orbitals,x):
    V_SIC = []
    for i in range(len(orbitals)):
        V_SIC.append(-hartree_potential(abs(orbitals[i])**2,x))
    return V_SIC

def normalize_orbital(evec,x):
    """ Normalize orbitals to one """

    integrand = evec * evec.conj()
    integral = simps(integrand, x)

    return evec / sqrt(integral)

def kinetic_hamiltonian(x):
    grid_size = x.shape[0]
    dx = x[1] - x[0]
    dx2 = dx**2

    H0 = sp.diags(
        [
            -0.5 / dx2 * np.ones(grid_size - 1),
            1.0 / dx2 * np.ones(grid_size),
            -0.5 / dx2 * np.ones(grid_size - 1)
        ],
        [-1, 0, 1])
    return H0

def main():

     # --- Setting up the system etc. ---
    global ee_coef
    # e-e potential parameters [strenght, smoothness]
    ee_coef = [1.0, 1.0]
    # number of electrons
    N_e = 6
    # 1D occupations each orbital can have max 2, i.e., spin up and spin down
    # e.g., occ = [0,0,1,1] means lowest up and down, next lowest up and down
    #       occ = [0,1,2,3] means all spin up

    # S = 3
    # occ = [0,1,2,3,4,5]
    # S = 0
    occ = [0,0,1,1,2,2]

    # occ = [0,1,2,3]
    # occ = [0,0,1,1]

    # grid
    x=linspace(-4,4,120)
    # threshold
    threshold=1.0e-4
    # mixing value
    mix=0.2
    # maximum number of iterations
    maxiters = 100
    # --- End setting up the system etc. ---

    # Initialization and calculations start here
    dx = x[1]-x[0]
    T = kinetic_hamiltonian(x)
    Vext = ext_potential(x)

    """
    #FILL#
    In problems 2 and 3: READ in density / orbitals / etc.
    """

    filename = FILENAMELOAD

    if LOADING:
        if os.path.isfile(filename + "_shape.txt"):

            print("Loading from files {}_*".format(filename))
            print("*** *** ***")

            ns=load_ns_from_ascii(filename)
            x = load_grid_from_ascii(filename)
            orbitals = load_orbitals_in_ascii(filename)

    else:
        ns=initialize_density(x,dx,N_e)

    print('Density integral        ', simps(ns,x))
    print(' -- should be close to  ', N_e)

    print('\nCalculating initial state')
    Vhartree=hartree_potential(ns,x)
    VSIC=[]

    if LOADING:
        VSIC=calculate_SIC(orbitals,x)
    else:
        for i in range(N_e):
            VSIC.append(ns*0.0)

        """
          #FILL#
          In problems 2 and 3 this needs to be modified, since
          then you have orbitals already at this point !!!!!!!!!!!!
        """

    Veff=sp.diags(Vext+Vhartree,0)
    H=T+Veff
    for i in range(maxiters):
        print('\n\nIteration #{0}'.format(i))
        orbitals=[]
        for i in range(N_e):
            print('  Calculating orbitals for electron ', i+1)
            eigs, evecs = sla.eigs(H+sp.diags(VSIC[i],0), k=N_e, which='SR')
            eigs=real(eigs)
            evecs=real(evecs)
            print('    eigenvalues', eigs)
            evecs[:,occ[i]]=normalize_orbital(evecs[:,occ[i]],x)
            orbitals.append(evecs[:,occ[i]])
        Veff_old = 1.0*Veff
        ns=density(orbitals)
        Vhartree=hartree_potential(ns,x)
        VSIC=calculate_SIC(orbitals,x)
        Veff_new=sp.diags(Vext+Vhartree,0)
        if check_convergence(Veff_old,Veff_new,threshold):
            break
        else:
            """ Mixing the potential """
            Veff= mix * Veff_old +  (1 - mix) * Veff_new
            H = T+Veff

    print('\n\n')
    off = offdiag_potential_energy(orbitals,x)
    E_kin = diagonal_energy(T,orbitals,x)
    E_pot = diagonal_energy(sp.diags(Vext,0),orbitals,x) + off
    E_tot = E_kin + E_pot
    print('Total energy     ', E_tot)
    print('Kinetic energy   ', E_kin)
    print('Potential energy ', E_pot)
    print('\nDensity integral ', simps(ns,x))

    if SAVING:
        filename = FILENAMESAVE
        print("Saving to files: {}_*".format(filename))

        save_ns_in_ascii(ns,filename)
        save_orbitals_in_ascii(orbitals, filename)
        save_grid_in_ascii(x, filename)

    """
    #FILL#
    In problems 2 and 3:
    WRITE OUT to files: density / orbitals / energetics / etc.
    save_ns_in_ascii(ns,'density') etc.
    """

    fig = figure(figsize = (13,13))
    ax = fig.gca()
    ax.plot(x,abs(ns), label = "Total electron density")
    ax.set_xlabel(r'$x$ (a.u.)')
    ax.set_ylabel(r'$n(x)$ (1/a.u.)')

    ax.set_title("N-electron density for N={} and tolerance {}".format(N_e, threshold))

    energytext = "Total energy {:2.3f} Ha \n Kinetic energy {:2.3f} Ha \n Potential energy {:2.3f} Ha".format(E_tot, E_kin, E_pot)
    ax.text(0.2,0.9,energytext, horizontalalignment='center', verticalalignment='center', transform = ax.transAxes)

    plot_orbitals(orbitals, x, ax)
    legend()
    show()

if __name__=="__main__":
    main()


import inspect
import copy
from aorist import *
from aorist_recipes import programs
from common import endpoints

"""
Defining schema
"""
attributes = [
    Attribute(KeyStringIdentifier("id")),
    Attribute(StringIdentifier("author")),
    Attribute(StringIdentifier("subreddit")),
    Attribute(POSIXTimestamp("created_utc")),
    Attribute(FreeText("title")),
    Attribute(FreeText("selftext", nullable=True)),
]
"""
A row in our table is a struct.
"""
subreddit_datum = RowStruct(
    name="subreddit",
    attributes=attributes,
)
tmp_dir = "tmp/subreddits"
"""
Data will be replicated to Hive
"""
local = HiveTableStorage(
    location=HiveLocation(MinioLocation(name='reddit')),
    encoding=Encoding(NewlineDelimitedJSONEncoding()),
    layout=TabularLayout(StaticTabularLayout()),
)
"""
Declaring where our subreddits live, i.e. in PushShift
"""
subreddits = ['france']#, 'newzealand']
tabular_schema = default_tabular_schema(
    subreddit_datum, subreddit_datum.name, attributes
)
assets = {x: StaticDataTable(
    name=x,
    schema=DataSchema(tabular_schema),
    setup=StorageSetup(RemoteStorageSetup(
        remote=Storage(RemoteStorage(
            location=RemoteLocation(
                PushshiftAPILocation(
                    subreddit=x
                )
            ),
            layout=APIOrFileLayout(
                APILayout(
                    PushshiftSubredditPostsAPILayout()
                ),
            ),
            encoding=Encoding(
                NewlineDelimitedJSONEncoding()
            ),
        )),
    )),
    tag=x,
    ) for x in subreddits}

embedding = FasttextEmbedding(
    name="embedding",
    comment="Fasttext embedding of size 128",
    schema=DataSchema(FasttextEmbeddingSchema(
        dim=128,
        source_schema=tabular_schema,
        text_attribute_name="selftext",
    )),
    setup=StorageSetup(LocalStorageSetup(
        Storage(local),
        '/tmp/fasttext_embedding',
    )),
    source_assets=[Asset(v) for v in assets.values()],
)
assets = {
    k: Asset(v) for (k, v) in assets.items()
}
assets['embedding'] = Asset(embedding)
"""
Creating the dataset
"""
subreddits = DataSet(
    name="subreddits",
    description="""
    A selection of small region-based Subreddits to demonstrate
    collecting Reddit data via [Pushshift](https://pushshift.io/).
    """,
    source_path=__file__,
    datum_templates=[DatumTemplate(subreddit_datum)],
    assets=assets,
    access_policies=[],
)
"""
Dataset will be replicated.
"""
subreddits = subreddits.replicate_to_local(
    Storage(local), tmp_dir, Encoding(CSVEncoding())
)
universe = Universe(
    name="my_cluster",
    datasets=[subreddits],
    endpoints=endpoints,
)
universe.compute_uuids()

result = dag(
    universe,
    ["UploadFasttextToMinio"],
    "airflow",
    programs,
    dialect_preferences=[
        R(),
        Python([]),
        Bash(),
        Presto(),
    ],
)
print(result)


from flask import Flask, render_template
import pandas as pd
import matplotlib.pyplot as plt

from io import BytesIO
import base64

import matplotlib

matplotlib.use('Agg')  # Указываем использовать бэкенд Agg для отрисовки графиков

app = Flask(__name__)

@app.route('/')
def plot_graph():
    # Чтение данных из CSV файла в DataFrame
    # df = pd.read_csv('data/test.csv', delimiter=',')
    df = pd.read_csv('data/com12_60s.csv', delimiter=',')

    signals = []

    start_row_index = 0

    for index, row in df.iterrows():
        if row['V_value'] == 0:
            if index != start_row_index:
                signal = df.iloc[start_row_index:index].to_dict(orient='list')
                signals.append(signal)
            start_row_index = index

    # Добавляем последний сигнал
    signal = df.iloc[start_row_index:].to_dict(orient='list')
    signals.append(signal)

    images_for_signals = {
        "voltage_pulse": [],
        "current_pulse": [],
        "WE_pulse": [],
    }

    current_ch0 = []
    current_ch1 = []
    Qch = []

    fig, ax = plt.subplots()

    for signal in signals:

        # current_measurements
        if len(signal["I_value"]) >= 3:
            last_three_values = signal["I_value"][-3:]
            current_measurement = int(round(sum(last_three_values) / 3000))
        else:
            current_measurement = None

        # split current_measurement by channel number
        if signal["Channel#"][1] == 0:
            current_ch0.append(current_measurement)
        elif signal["Channel#"][1] == 1:
            current_ch1.append(current_measurement)

        # superimposed I_value img creation
        y_values = signal["I_value"]
        y_values = [int(round(value / 1000)) for value in y_values]
        x_values = signal["Time"]

        # normalization of x_values
        min_value = min(x_values)
        max_value = max(x_values)
        new_min = 0
        new_max = 120
        normalized_x_values = [(x - min_value) / (max_value - min_value) * (new_max - new_min) + new_min for x in
                               x_values]

        # current density calculation
        electrode_area = 3.14 * 20
        current_density = [int(round(value / electrode_area)) for value in y_values]

        ax.plot(normalized_x_values, current_density, marker='o', linestyle='-', markersize=3)

        # calculation of a parameter Qch that is proportional to the charge
        # normalization of y_values
        min_y_value = min(y_values)
        normalized_y_values = [y - min_y_value for y in y_values]
        area = 0
        n = len(normalized_x_values)
        for i in range(1, n):
            h = normalized_x_values[i] - normalized_x_values[i - 1]
            area += 0.5 * (normalized_y_values[i] + normalized_y_values[i - 1]) * h

        Qch.append(area)

    plt.xlabel('Time as normalized_x_values')
    plt.ylabel('current_density')
    plt.grid(True)
    fig.set_figwidth(5)
    img_buf = BytesIO()
    plt.savefig(img_buf, format='png', bbox_inches='tight', dpi=300)
    plt.clf()
    img_buf.seek(0)
    img_base64 = base64.b64encode(img_buf.read()).decode()  # base64 needed for HTML
    images_for_signals["current_pulse"].append(img_base64)

    plt.hist(Qch, bins=20, edgecolor='k')
    plt.xlabel('Qch')
    plt.ylabel('Events')
    img_buf = BytesIO()
    plt.savefig(img_buf, format='png', bbox_inches='tight', dpi=300)
    plt.clf()
    img_buf.seek(0)
    Qch_hist = base64.b64encode(img_buf.read()).decode()  # base64 needed for HTML

    # for signal in signals:
    #     # voltage_pulse image creation
    #     y_values = signal["V_value"]
    #     y_values = [int(round(value / 1000)) for value in y_values]
    #     x_values = signal["Time"]
    #     fig, ax = plt.subplots()
    #     ax.plot(x_values, y_values, marker='o', linestyle='-')
    #     plt.xlabel('Time')
    #     plt.ylabel('V_value')
    #     plt.grid(True)
    #     fig.set_figwidth(5)
    #     img_buf = BytesIO()  # Сохранение графика как изображения
    #     plt.savefig(img_buf, format='png', bbox_inches='tight', dpi=300)
    #     plt.clf()
    #     img_buf.seek(0)
    #     img_base64 = base64.b64encode(img_buf.read()).decode()  # base64 needed for HTML
    #     images_for_signals["voltage_pulse"].append(img_base64)
    #
    #     # current_pulse image creation
    #     y_values = signal["I_value"]
    #     y_values = [int(round(value / 1000)) for value in y_values]
    #     fig, ax = plt.subplots()
    #     ax.plot(x_values, y_values, marker='o', linestyle='-')
    #     plt.xlabel('Time')
    #     plt.ylabel('I_value')
    #     plt.grid(True)
    #     fig.set_figwidth(5)
    #     img_buf = BytesIO()  # Сохранение графика как изображения
    #     plt.savefig(img_buf, format='png', bbox_inches='tight', dpi=300)
    #     plt.clf()
    #     img_buf.seek(0)
    #     img_base64 = base64.b64encode(img_buf.read()).decode()  # base64 needed for HTML
    #     images_for_signals["current_pulse"].append(img_base64)
    #
    #     # WE_pulse image creation
    #     y_values = signal["WE_value"]
    #     y_values = [int(round(value / 1000)) for value in y_values]
    #     fig, ax = plt.subplots()
    #     ax.plot(x_values, y_values, marker='o', linestyle='-')
    #     plt.xlabel('Time')
    #     plt.ylabel('WE_value')
    #     plt.grid(True)
    #     fig.set_figwidth(5)
    #     img_buf = BytesIO()  # Сохранение графика как изображения
    #     plt.savefig(img_buf, format='png', bbox_inches='tight', dpi=300)
    #     plt.clf()
    #     img_buf.seek(0)
    #     img_base64 = base64.b64encode(img_buf.read()).decode()  # base64 needed for HTML
    #     images_for_signals["WE_pulse"].append(img_base64)

    # list of indices for HTML loop
    max_images_for_signals_count = max(len(img) for img in images_for_signals.values())
    indices = list(range(max_images_for_signals_count))

    # current_ch0 and current_ch1 image creation
    print("current_ch0", current_ch0)
    print("current_ch1", current_ch1)
    indices_current_ch0 = list(range(len(current_ch0)))

    fig, ax = plt.subplots()
    ax.plot(indices_current_ch0, current_ch0, label='current_ch0', marker='o', linestyle='-', markersize=3)
    ax.plot(indices_current_ch0, current_ch1, label='current_ch1', marker='o', linestyle='-', markersize=3)
    plt.xlabel('index')
    plt.ylabel('current_measurement')
    plt.grid(True)
    fig.set_figwidth(5)
    img_buf = BytesIO()  # Сохранение графика как изображения
    plt.savefig(img_buf, format='png', bbox_inches='tight', dpi=300)
    plt.clf()
    img_buf.seek(0)
    image_for_current_measurements = base64.b64encode(img_buf.read()).decode()  # base64 needed for HTML

    return render_template('index.html', images_for_signals=images_for_signals, indices=indices,
                           image_for_current_measurements=image_for_current_measurements, Qch_hist=Qch_hist)

if __name__ == '__main__':
    app.run()


"""

"""

#Here is a 8-liner implementation:
import bisect
class Solution(object):
    def kthSmallest(self, matrix, k):
        lo, hi = matrix[0][0], matrix[-1][-1]
        while lo<hi:
            mid = (lo+hi)//2
            if sum(bisect.bisect_right(row, mid) for row in matrix) < k:
                lo = mid+1
            else:
                hi = mid
        return lo
#2. Heap solution gives me 176 ms.
# The time complexity is O(k * log n),
# so the worst-case and average-case time complexity is O(n^2 * log n).
# Space complexity is O(n).

import heapq
class Solution(object):
    def kthSmallest(self, matrix, k):
        heap = [(row[0], i, 0) for i, row in enumerate(matrix)]
        heapq.heapify(heap)
        ret = 0
        for _ in range(k):
            ret, i, j = heapq.heappop(heap)
            if j+1 < len(matrix[0]):
                heapq.heappush(heap, (matrix[i][j+1], i, j+1))
        return ret
#3. Sorting gives me 80ms. Time complexity of sorting an array of size n^2 is O(n^2 * log n). Space complexity is O(n^2).

#The difference is that Timsort implemented in Python is capable of taking advantage of existing partial orderings. Moving sorted data in bulk is always faster than comparing and moving individual data elements, due to modern hardware architecture. Time complexity is the same because merging n sorted arrays of size n is still O(n^2 * log n) in the worst case.

class Solution(object):
    def kthSmallest(self, matrix, k):
        l = []
        for row in matrix:
            l += row
        return sorted(l)[k-1]


import time
import multiprocessing

def fatorial(n):
    fat = n
    for i in range(n - 1, 1, -1):
        fat = fat * i
    return fat

def fatorial_lista(lista, result_parcial, id):
    lista_retorno = []
    for item in lista:
        resultado = fatorial(item)
        lista_retorno.append(resultado)
    result_parcial[id] = lista_retorno

if __name__ == "__main__":
    quantidade_numeros = 5000
    hora_inicio = time.time()

    lista = []
    for i in range(quantidade_numeros):
        lista.append(i)

    num_processos = 4
    hora_inicio = time.time()

    with multiprocessing.Manager() as manager:
        # Cria lista na memória do SP
        lista = manager.list(lista)
        # Vetor para salvar a soma parcial de cada thread
        result_parcial = manager.list(num_processos * [0])

        lista_processos = []
        for i in range(num_processos):
            ini = i * int(quantidade_numeros / num_processos)
            fim = (i + 1) * int(quantidade_numeros / num_processos)
            p = multiprocessing.Process(target=fatorial_lista, args=(lista[ini:fim],result_parcial, i))
            p.start()
            lista_processos.append(p)

        for p in lista_processos:
            p.join()

        resultado = [x for l in result_parcial for x in l]

        hora_final = time.time()
        tempo_decorrido = hora_final - hora_inicio

        print("Primeiros resultados:", resultado[:5])
        print(f"Tempo multiprocess: {tempo_decorrido}")

        arq = open("08C.txt", "w")
        for item in resultado:
            arq.write(f"{item}\n")
        arq.close()


import json

from django.conf import settings
from django.http import HttpResponse

from tags.models import Tag

from django.apps import apps
get_model = apps.get_model

# Including these declarations here because it would be nice to not rely on the taggit autosuggest app
MAX_SUGGESTIONS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MAX_SUGGESTIONS', 20)
TAG_MODELS = getattr(settings, 'TAGGIT_AUTOSUGGEST_MODELS', {'default': ('taggit', 'Tag')})
if not type(TAG_MODELS) == dict:
    TAG_MODELS = {'default': TAG_MODELS}

def list_all_tags(request):
    """Returns all the tags in the database"""
    all_tags = Tag.objects.all().values_list('name', flat=True)
    return HttpResponse(json.dumps(list(all_tags)), content_type='application/json')

def list_tags(request, tagmodel=None):
    """
    Returns a list of JSON objects with a `name` and a `value` property that
    all start like your query string `q` (not case sensitive).
    """
    if not tagmodel or tagmodel not in TAG_MODELS:
        TAG_MODEL = get_model(*TAG_MODELS['default'])
    else:
        TAG_MODEL = get_model(*TAG_MODELS[tagmodel])

    query = request.GET.get('q', '')
    limit = request.GET.get('limit', MAX_SUGGESTIONS)
    try:
        request.GET.get('limit', MAX_SUGGESTIONS)
        limit = min(int(limit), MAX_SUGGESTIONS)  # max or less
    except ValueError:
        limit = MAX_SUGGESTIONS
    except TypeError:
        pass

    tag_name_qs = TAG_MODEL.objects.filter(name__icontains=query).order_by('name', 'id'). \
        values('pk', 'name')

    if callable(getattr(TAG_MODEL, 'request_filter', None)):
        tag_name_qs = tag_name_qs.filter(TAG_MODEL.request_filter(request)).distinct()

    if MAX_SUGGESTIONS:
        data = [{'id': n['pk'], 'name': n['name'], 'value': n['name']} for n in tag_name_qs[:limit]]
    else:
        data = [{'id': n['pk'], 'name': n['name'], 'value': n['name']} for n in tag_name_qs]

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


def getFileContent(path):
	with open(path, "r") as file:
		return file.read()

def getData(string):
	blocs = string.split('\n\n')
	drawnNumbers = [ int(s) for s in blocs[0].split(',') ]
	blocs = [ bloc.split('\n') for bloc in blocs[1:] ]
	blocs = [ [ s for s in bloc if s != '' ] for bloc in blocs ] # for trailing newlines at the end.
	blocs = [ [ [ s for s in row.split(' ') if s != '' ] for row in bloc ] for bloc in blocs ]
	boardsMatrixList = [ [ [ int(s) for s in row ] for row in bloc ] for bloc in blocs ]
	size = len(boardsMatrixList[0][0])
	return size, drawnNumbers, boardsMatrixList

def getBoardMaps(boardsMatrixList):
	boardMaps = []
	for i in range(len(boardsMatrixList)):
		boardMatrix = boardsMatrixList[i]
		boardMap = {}
		boardMaps.append(boardMap)
		for row in range(len(boardMatrix)):
			for col in range(len(boardMatrix[0])):
				val = boardMatrix[row][col]
				boardMap[val] = [row, col, 0]
	return boardMaps

def addValue(board, val):
	if val in board:
		board[val][2] = 1
		return True
	return False

def checkBoard(board, size):
	rowsSums, colsSums = [0] * size, [0] * size
	for val in board:
		if board[val][2] == 1:
			row, col = board[val][0], board[val][1]
			rowsSums[row] += 1
			colsSums[col] += 1
	return size in rowsSums or size in colsSums

def getScore(board, lastVal):
	s = 0
	for val in board:
		if board[val][2] == 0:
			s += val
	return lastVal * s

def playForWin(drawnNumbers, boardMaps, size):
	for val in drawnNumbers:
		for i in range(len(boardMaps)):
			if addValue(boardMaps[i], val) and checkBoard(boardMaps[i], size):
				print('Winning board %d!' % i)
				return getScore(boardMaps[i], val)
	print('No winner yet...')
	return -1

stringInput = getFileContent('resources/input_04.txt')
size, drawnNumbers, boardsMatrixList = getData(stringInput)
print('size:', size)
print('drawnNumbers:\n', drawnNumbers)
print('boards matrices:', *boardsMatrixList, sep='\n')

boardMaps = getBoardMaps(boardsMatrixList)
# print('boardMaps:', *boardMaps, sep='\n')

score = playForWin(drawnNumbers, boardMaps, size)
print('score:', score, '\n') # 44088

# ------------------------------------------
# Part 2:

def playForLoss(drawnNumbers, boardMaps, size):
	boardMapsIndexes = range(len(boardMaps))
	for val in drawnNumbers:
		nextBoardMapsIndexes = []
		for i in boardMapsIndexes:
			if addValue(boardMaps[i], val) and checkBoard(boardMaps[i], size):
				lastWinIndex = i
				# print('Winning board °%d, discarding it!' % i)
			else:
				nextBoardMapsIndexes.append(i)
		boardMapsIndexes = nextBoardMapsIndexes
		if nextBoardMapsIndexes == []:
			print('Last board °%d won!' % lastWinIndex)
			return getScore(boardMaps[lastWinIndex], val)
	print('No winner yet...')
	return -1

score = playForLoss(drawnNumbers, boardMaps, size)
print('score:', score) # 23670


import cv2 as cv

# img = cv.imread("prototype.png")

# cv.imshow("image", img)

# cv.waitKey(0)

capture = cv.VideoCapture(r"C:\Users\ACER\Downloads\ariandel.mp4")

while True:
    isTrue, frame = capture.read()
    cv.imshow('Video', frame)

    if cv.waitKey(20) & 0xFF==ord('d'):
        break
capture.release()
cv.destroyAllWindows()


import commands
import logging
import ce_deploy_scripts

def get_host_conn_state(hosts):

    for key in hosts:
        logging.info('\ncheck connection with %s\n' % key)
        shell_file_path = ce_deploy_scripts.BASE_DIR + "/shell_script/netping.sh"
        shell_cmd = "sh " + shell_file_path + " " + hosts[key]
        output = commands.getstatusoutput(shell_cmd)
        logging.info('\n%s\n' % output[1])
        if output[0] == 0:
            logging.error('\nhost %s is unavailable\n' % key)
            return False

    return True


#Functions that return values
#This function takes in 2 arguments, adds them and returns the sum
def add(a, b):
    print(f"ADDING  {a} + {b}")
    #Sum is returned
    return a + b

#This function takes in 2 arguments and returns the difference
def subtract(a, b):
    print(f"SUBTRACTING {a} - {b}")
    #The difference is returned
    return a - b
#This function takes in 2 numbers and returns the product
def multiply(a, b):
    print(f"MULTIPLYING {a} * {b}")
    #The product is returned
    return a*b
#This function takes in 2 numbers and returns the quotient
def divide(a, b):
    print(f"Divide {a}/{b}")
    #The quotient is returned
    return a/b

print("Let's do some math with just functions!")

#The above mentioned functions are called with appropriate argument values
#And assigned to a variable
#30+5
age = add(30, 5)
#78-4
height = subtract(78,4)
#90*2
weight= multiply(90, 2)
#100/2
iq = divide(100,2)

#Print this formatted string with the above variable values integrated
print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}")

#A puzzle for extra credit, type it in anyway
#Print the statement below
print("Here is the puzzle.")
#Functions assigned to variable.The below statement is called/ executed inside
#out, i.e. divide, multiply,subtract, add in that order
what = add(age, subtract(height, multiply(weight, divide(iq,2))))
#Prints the string below, but I would have put it as a formatted string with {}
print("That becomes: ", what, "Can you do it by hand?")#-4391
#The normal formula is:
print(age+height-((iq/2)*weight))

#My own functions
def circumference(a):
    return round(a*2*3.14159,3)

circum= circumference(10)

print(f"The circumference of a circle with radius 10 units is {circum}")

def temp_convert(a):
    return round((1.8*a)+32,3)
#This messy but I had to typecast for this to run, above fn temp_convert(a)
#Wont run unless the a or temp in this case is typecast to float beacuse 1.8 is
#a float
temp= float(input("Enter a temperature in degrees Celcius: "))
print(f"The fahrenheit equivalent of {temp} is {temp_convert(temp)}")

def BMI_calc(a,b):
    a_kg = float(a)/2.24
    b_cm = (float(b)*2.54)/100
    return round(a_kg/b_cm**2,3)

wgt= input("What is your weight (in lbs) ?: ")
hgt= input("What is your height (in inches) ?")

print(f"Your BMI value is {BMI_calc(wgt,hgt)}")
#Doing the inverse, reverse-engineering the functions
#My simple formula
print(5+3*10-6)
#The same using the functions is
print(subtract(add(5,multiply(3,10)),6))


# -*- coding: utf-8 -*-
#BEGIN_HEADER
import logging
import os
import re
import subprocess
import sys
import traceback
import uuid
from datetime import datetime
from pprint import pformat

# SDK Utils
from installed_clients.KBaseDataObjectToFileUtilsClient import KBaseDataObjectToFileUtils
from installed_clients.DataFileUtilClient import DataFileUtil as DFUClient
from installed_clients.KBaseReportClient import KBaseReport
from installed_clients.WorkspaceClient import Workspace as workspaceService

# EggnogMapperUtil
from kb_eggnog_mapper.Utils.EggnogMapperUtil import EggnogMapperUtil

#END_HEADER

class kb_eggnog_mapper:
    '''
    Module Name:
    kb_eggnog_mapper

    Module Description:
    A KBase module: kb_eggnog_mapper
    '''

    ######## WARNING FOR GEVENT USERS ####### noqa
    # Since asynchronous IO can lead to methods - even the same method -
    # interrupting each other, you must be *very* careful when using global
    # state. A method could easily clobber the state set by another while
    # the latter method is running.
    ######################################### noqa
    VERSION = "0.0.1"
    GIT_URL = "https://github.com/kbaseapps/kb_eggnog_mapper"
    GIT_COMMIT_HASH = "e80aadc84a9663e2421ce90545bc7e0939b4252f"

    #BEGIN_CLASS_HEADER
    #END_CLASS_HEADER

    # config contains contents of config file in a hash or None if it couldn't
    # be found
    def __init__(self, config):
        #BEGIN_CONSTRUCTOR
        self.config = config
        self.workspaceURL = config['workspace-url']
        self.shockURL = config['shock-url']
        self.handleURL = config['handle-service-url']
        self.serviceWizardURL = config['srv-wiz-url']
        self.callbackURL = os.environ.get('SDK_CALLBACK_URL')
        if self.callbackURL == None:
            raise ValueError ("SDK_CALLBACK_URL not set in environment")

        self.EMAPPER_VER = config['emapper_ver']

        self.scratch = os.path.abspath(config['scratch'])
        if self.scratch == None:
            self.scratch = os.path.join('/kb','module','local_scratch')
        if not os.path.exists(self.scratch):
            os.makedirs(self.scratch)

        logging.basicConfig(format='%(created)s %(levelname)s: %(message)s',
                            level=logging.INFO)
        #END_CONSTRUCTOR
        pass

    def run_eggnog_mapper(self, ctx, params):
        """
        :param params: instance of type "EggnogMapper_Input"
           (run_eggnog_mapper() ** ** run eggnog-mapper on a collection of
           genomes and/or AMAs) -> structure: parameter "workspace_name" of
           type "workspace_name" (** Common types), parameter "workspace_id"
           of type "workspace_id", parameter "target_refs" of type
           "data_obj_ref", parameter "novel_fams" of type "bool", parameter
           "genome_disp_name_config" of String
        :returns: instance of type "ReportResults" (** Report Results) ->
           structure: parameter "report_name" of String, parameter
           "report_ref" of String
        """
        # ctx is the context object
        # return variables are: output
        #BEGIN run_eggnog_mapper
        search_tool_name = 'eggnog_mapper_v'+self.EMAPPER_VER
        emu = EggnogMapperUtil(self.config, ctx)
        output = emu.run_EMAPPER_App (search_tool_name, params)
        #END run_eggnog_mapper

        # At some point might do deeper type checking...
        if not isinstance(output, dict):
            raise ValueError('Method run_eggnog_mapper return value ' +
                             'output is not type dict as required.')
        # return the results
        return [output]
    def status(self, ctx):
        #BEGIN_STATUS
        returnVal = {'state': "OK",
                     'message': "",
                     'version': self.VERSION,
                     'git_url': self.GIT_URL,
                     'git_commit_hash': self.GIT_COMMIT_HASH}
        #END_STATUS
        return [returnVal]


import time

import pytest
from koyo.timer import format_time, time_average, time_loop

@pytest.mark.parametrize(
    "value, expected",
    [
        (0.01, "us"),
        (0.1, "ms"),
        (0.5, "s"),
        (1, "s"),
        (60, "s"),
        (75, "min"),
        (3654, "hr"),
    ],
)
def test_format_time(value, expected):
    """Test 'format_time'"""
    result = format_time(value)
    assert expected in result

def test_time_average():
    """Test 'time_average'"""
    t_start = time.time()
    time.sleep(0.01)
    result = time_average(t_start, 1)
    assert "Avg:" in result
    assert "Tot:" in result
    assert result.startswith("[")
    assert result.endswith("]")

def test_time_loop():
    """Test 'time_loop'"""
    t_start = time.time()
    time.sleep(0.01)
    result = time_loop(t_start, 0, 0)
    assert "Avg:" in result
    assert "Rem:" in result
    assert "Tot:" in result
    assert "%" in result

    result = time_loop(t_start, 0, 0, as_percentage=False)
    assert "%" not in result
    assert result.startswith("[")
    assert result.endswith("]")


import pygame
import math
import sys
import re

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)

grid_size = 101
block_size = 8
multiplier = 1.13
fps = 60

def run_sim(start_state, end_state, path, maze):
	start_x, start_y = start_state
	end_x, end_y = end_state

	pygame.init()

	length = int(math.ceil(multiplier * grid_size * block_size))

	size = (length, length)
	window = pygame.display.set_mode(size)
	pygame.display.set_caption("A* Path")

	done = False
	clock = pygame.time.Clock()

	path_index = 0
	revealed_path = {}
	while not done:
		for event in pygame.event.get():
			if event.type == pygame.QUIT:
				done = True

		window.fill(BLACK)
		for y in range(grid_size):
			for x in range(grid_size):
				rect = pygame.Rect(x * (block_size + 1), y * (block_size + 1), block_size, block_size)

				if path_index < len(path):
					curr_path_node_x, curr_path_node_y = path[path_index]
					revealed_path[(curr_path_node_x, curr_path_node_y)] = True

				if start_x == x and start_y == y:
					pygame.draw.rect(window, BLUE, rect)
				elif end_x == x and end_y == y:
					pygame.draw.rect(window, GREEN, rect)
				elif revealed_path.get((x, y)):
					pygame.draw.rect(window, RED, rect)
				else:
					if maze[y][x]:
						pygame.draw.rect(window, WHITE, rect)
					else:
						pygame.draw.rect(window, BLACK, rect)

		path_index += 1
		pygame.display.flip()
		clock.tick(fps)

	pygame.quit()

def main():
	start_state = None
	end_state = None
	path = None
	maze = {}

	with open(sys.argv[1], 'r') as f:
		line_row = 0
		for line in f:
			if not line:
				continue
			if not start_state:
				start_state = [int(n) for n in line.split(',')]
				continue
			if not end_state:
				end_state = [int(n) for n in line.split(',')]
				continue
			line_col = 0
			maze[line_row] = {}
			for pos in line:
				maze[line_row][line_col] = True if pos == '0' else False
				line_col += 1
			line_row += 1

	# print start_state
	# print end_state

	with open(sys.argv[2], 'r') as f:
		path_string = f.read()
		path_string_list = re.findall(r'{([0-9]+, [0-9]+)}', path_string)
		path = []
		for pair in path_string_list:
			path.append([int(n) for n in pair.split(',')])

	# print path

	run_sim(start_state, end_state, path, maze)

if __name__ == '__main__':
	main()