from flask import Flask, jsonify, request, render_template
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import config

app = Flask (__name__)

db = SQLAlchemy(app)
ma = Marshmallow(app)
app.config['SQLALCHEMY_DATABASE_URI']= config.connectionString

class CustomerModel(db.Model):
    __tablename__ = 'customersTable' #nome da tabela dele no banco
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)
    birthDay = db.Column(db.String)
    generalRegistry = db.Column(db.String)
    address = db.Column(db.String)
    phoneNumber = db.Column(db.String)
    historic = db.Column(db.Boolean)

    def __repr__(self):
        return ("<Customer(name=" + self.name
		+ ", birthDay=" + self.birthDay
		+ ", generalRegistry=" + self.generalRegistry
		+ ", address=" + self.address
		+ ", phoneNumber=" + self.phoneNumber
		+ ", historic=" + self.historic + ">")
class CustomerSchema(ma.ModelSchema):
	class Meta:
		model = CustomerModel

@app.route('/index.html')
def index():
	#não consegui relacionar a tempo o web-form com a API e o BD
	#seguirei tentando
    return render_template('index.html')

@app.route('/allCustomers', methods=['GET'])
def getAllCustomers():
	#aqui poderiamos limitar registros por data ou uma quantidade específica para não dar over no BD
	try:
		allCustomers = CustomerModel.query.all()
		customerSchema = CustomerSchema(many=True)
		outPut = customerSchema.dump(allCustomers)
		print ('Registros retornados com sucesso')
		return jsonify({'customers':outPut}), 200
	except:
		print ('Não foi possível retornar todos os registros')

@app.route('/allCustomers/<string:namePassed>', methods=['GET'])
def getCustomerPerName(namePassed):
	#busca por um nome específico proveniente da chamada da API
	try:
		specificCustomer = CustomerModel.query.filter(CustomerModel.name.like("%" + str(namePassed) + "%"), CustomerModel.historic == False)
		customerSchema = CustomerSchema(many=True)
		outPut = customerSchema.dump(specificCustomer)
		print ('Obj. retornado com sucesso')
		return jsonify({'customer':outPut}), 200
	except:
		print ('localizar o registro, Obj. pode não  ser existente no banco')

@app.route('/sendRegistry', methods=['POST'])
def postCustomer():
	#adiciona um registro conforme o JSON vindo da requisição
	try:
		engine = create_engine(config.connectionString)
		Session = sessionmaker(bind=engine)
		session = Session()
		data = request.get_json()
		customerToAdd = CustomerModel(name = data['name'], birthDay = data['birthDay'], generalRegistry = data['generalRegistry'], address = data['address'], phoneNumber = data['phoneNumber'], historic = False) # Acabou de criar não é historico
		session.add(customerToAdd)
		session.commit()
		print ('Obj. adicionado ao banco com sucesso')
		return jsonify(data), 201
	except:
		#para isso poderia realizar verificação do registro no banco, a fim de evitar duplicatas
		print ('Não foi possivel adicionar Obj.')

@app.route('/<string:nameToDelete>', methods=['GET'])
def removeCustomer(nameToDelete):
	# realiza a deleção lógica, a fim de resguardar os dados no banco
	try:
		engine = create_engine(config.connectionString)
		Session = sessionmaker(bind=engine)
		session = Session()
		toBeDeleted = session.query(CustomerModel).filter(CustomerModel.name.like('%' + str(nameToDelete) + '%'), CustomerModel.historic == False).first()
		ch = toBeDeleted
		session.delete(toBeDeleted)
		session.commit()
		addCs = CustomerModel(id = ch.id, name = ch.name, birthDay = ch.birthDay, generalRegistry = ch.generalRegistry, address = ch.address, phoneNumber = ch.phoneNumber, historic = True)
		session.add(addCs)
		session.commit()
		customerSchema = CustomerSchema()
		outPut = customerSchema.dump(ch)
		print ('Deleção realizada com sucesso')
	except:
		print ('Não foi possivel realizar deleção, Obj. não existente no banco')
	return jsonify({'toBeDeleted': outPut }), 200

if __name__ == '__main__':
	app.run(debug = True, host = '127.0.0.1')


from collections import deque
n=int(input())
w=list(map(int,input().split()))
d={}
for i in range(n):
    d[w[i]]=i
w.sort()
stack=deque()
s=input()
ans=[]
j=0
for i in range(2*n):
    if s[i]=='0':
        y=d[w[j]]
        stack.append(y)
        ans.append(y+1)
        j+=1
    else:
        x=stack.pop()
        ans.append(x+1)
print(*ans)


import sys

class Vehicle(object):
    vehicle_id = 0
    vehicles_sold = []
    def __init__(self,year,mileage,purchase_price,serial_number):
        self.__year = year
        self.__mileage = mileage
        self.__purchase_price = purchase_price
        if type(year) != int or type(mileage) != int or type(purchase_price) != int:
            raise ValueError("Illegal argument for either year, mileage or price: Must be int.")
        self.__serial_number = serial_number
        self.__vehicle_id = Vehicle.generate_vehicle_id()
        Vehicle.vehicle_id += 1
    def __str__(self):
        return str(self.__vehicle_id)
    def get_id(self):
        return self.__vehicle_id
    @staticmethod
    def generate_vehicle_id():
        return 100000 + Vehicle.vehicle_id

class Car(Vehicle):
    def __init__(self,year,mileage,purchase_price,serial_number,doors):
        Vehicle.__init__(self, year, mileage, purchase_price, serial_number)
        self.__doors = doors
        self.__wheels = 4

class Lorry(Vehicle):
    def __init__(self,year,mileage,purchase_price,serial_number,wheels,doors=2):
        Vehicle.__init__(self, year, mileage, purchase_price, serial_number)
        self.__doors = doors
        self.__wheels = wheels

class Motorcycle(Vehicle):
    classic_count = 0
    def __init__(self,year,mileage,purchase_price,serial_number,classic=False):
        Vehicle.__init__(self, year, mileage, purchase_price, serial_number)
        self.__classic = classic
        if classic:
            Motorcycle.classic_count += 1

### test cases ###

# initialising vehicle instances

Veh1 = Vehicle(2008,65000,7500,"34567851g4")
Veh2 = Car(2007,125000,5500,"e44653ftu1",4)
Veh3 = Car(2012,45000,8900,"gf5622iguz",doors=2)
Veh4 = Lorry(2005,180000,16000,"hbh997123f",6)
Veh5 = Lorry(2013,30000,35000,"hjbf17jbkh",8,4)
Veh6 = Motorcycle(1975,75500,40000,"bh545664rh",True)

print(Veh1,Veh2,Veh3,Veh4,Veh5,Veh6)
#prints 	100000 	100001 	100002 	100003 	100004 	100005

# Veh7 = Motorcycle("year",10000,25000,"bjhgss4rdh",False)
# instance Veh7 generates an exception (ValueError) (uncomment to test)


from email_sender.render import render
from email_sender.sender import send_mail

params = {
    "h1": "this is h1 label",
    "content": " hi , it's test send email",
    "url": "https://www.baidu.com/"
}
if __name__ == "__main__":
    content = render(params)
    send_mail("zk246422@163.com", content)


# -*- coding: utf-8 -*-
import frappe
from frappe.utils import flt

def execute():
	cust_list = frappe.db.sql("""SELECT cu.name FROM `tabCustomer` cu
		WHERE cu.name NOT IN (SELECT parent FROM `tabSales Team` WHERE parenttype = 'Customer'
		AND parent = cu.name)""", as_list=1)
	if cust_list:
		for d in range(len(cust_list)):
			new_st = frappe.get_doc({
					"doctype": "Sales Team",
					"parent": cust_list[d][0],
					"parenttype": 'Customer',
					"allocated_percentage": 100,
					"sales_person": "Rohit Duggal",
					"idx": 1,
					"parentfield": 'sales_team'
					})
			new_st.insert(ignore_permissions=True)
			print ("For Customer:" + cust_list[d][0] + " inserted New Sales Person Rohit Duggal")


N = input()
mn = int(1e9)
mx=-1
def div(s,cnt):
    global mn, mx
    #print('s, cnt: ',s,cnt)
    for el in s:
        if int(el)%2:
            cnt+=1
    if len(s)>=3:
        for i in range(1,len(s)-1):
            for j in range(i+1,len(s)):
                #print('\t',len(s), i, j)
                #print(s[:i], s[i:j], s[j:])
                a = str(sum([int(s[:i]), int(s[i:j]), int(s[j:])]))
                if len(a)>=3:
                    div(a,cnt)
                else:
                    div(a,cnt)
    elif len(s)==2:
        a = str(int(s[0])+int(s[1]))
        div(a,cnt)
    else: # len 1
        if cnt<mn:
            mn=cnt
        if cnt>mx:
            mx=cnt
        #print('답 추가', cnt)

div(N,0)

print(mn,mx)


import sqlite3
import pandas as pd

def getInfo(db_name, id):
    conn = sqlite3.connect(db_name)
    cur = conn.cursor()
    cur.execute(f"""SELECT * FROM items WHERE items.item_id == {id}""")
    df = pd.DataFrame(cur.fetchall(),
                      columns=['item_id', 'item_name', 'item_type', 'item_description', 'item_quantity', 'item_price'])
    conn.commit()
    item_name = df['item_name'][0]
    item_type = df['item_type'][0]
    item_description = df['item_description'][0]
    item_quantity = df['item_quantity'][0]
    item_price = df['item_price'][0]
    return item_name, item_type, item_description, item_quantity, item_price

def getDB(db_name):
    conn = sqlite3.connect(db_name)
    cur = conn.cursor()
    cur.execute(f"""SELECT * FROM items LIMIT 10""")
    df = pd.DataFrame(cur.fetchall(),
                      columns=['item_id', 'item_name', 'item_type', 'item_description', 'item_quantity', 'item_price'])
    conn.commit()
    return df

def add_item(db_name, id, name, tp, descr, quantity, price):
    conn = sqlite3.connect(db_name)
    cur = conn.cursor()
    my_data = (id, name, tp, descr, quantity, price)
    q = f"INSERT INTO items VALUES (?,?,?,?,?,?)"
    cur.execute(q, my_data)
    conn.commit()
    return 0


def find(name):
    for i in range(len(name), 0, -1):
        res = []
        for j in range(0, len(name) - i + 1):
            res.append(name[j:j + i])
        for j in range(len(res)):
            if res.count(res[j]) > 1:
                return res[j]
    return "0"

str = input()
cnt = 1
res = str
while len(res) > 1:
    res = find(res)
    if res == "0":
        break
    else:
        cnt += 1
print(cnt)


'''
Created on Dec 14, 2013

@author: ivan
'''
import unittest

class TestFormat(unittest.TestCase):

    def testIndex(self):
        import myplaces.format as fmt
        index=fmt.index()
        self.assertEqual(len(index),3)
        self.assertEqual(index[0][0], 'CSV')
        self.assertEqual(index[2][0], 'GEOJSON')

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testIndex']
    unittest.main()


import csv

dataset1 = []
dataset2 = []

with open('final.csv', 'r') as o:
    dataset1.append(o)

with open('dataset1.csv', 'r') as o:
    dataset2.append(o)

header1 = dataset1[0]
header2 = dataset2[0]

planetdata1 = dataset1[1:]
planetdata2 = dataset2[1:]

planetdata = []
for index, datarow in enumerate(planetdata1):
    planetdata.append(planetdata1[index] + planetdata2[index])

headers = (header1) + (header2)

with open('dataset5.csv', 'a+') as o:
    csvwriter = csv.writer(o)
    csvwriter.writerow(headers)
    csvwriter.writerows(planetdata)


# -*- coding:utf-8 -*-
def test(data):
    print("test is show")

# 调用函数
test(123)

# 引用函数
ret = test

print(ret)
print(test)

# 通过引用调用函数
ret(123)

# 把函数引用当成参数传递
def application(func):
    func(123)

application(ret)


import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np

class LossAverage(object):
    """Computes and stores the average and current value for calculate average loss"""
    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = round(self.sum / self.count, 4)
        # print(self.val)

class DiceAverage(object):
    """Computes and stores the average and current value for calculate average loss"""
    def __init__(self,class_num):
        self.class_num = class_num
        self.reset()

    def reset(self):
        self.value = np.asarray([0]*self.class_num, dtype='float64')
        self.avg = np.asarray([0]*self.class_num, dtype='float64')
        self.sum = np.asarray([0]*self.class_num, dtype='float64')
        self.count = 0

    def update(self, logits, targets):
        self.value = DiceAverage.get_dices(logits, targets)
        self.sum += self.value
        self.count += 1
        self.avg = np.around(self.sum / self.count, 4)
        # print(self.value)

    @staticmethod
    def get_dices(logits, targets):
        dices = []
        for class_index in range(targets.size()[1]):
            inter = torch.sum(logits[:, class_index, :, :, :] * targets[:, class_index, :, :, :])
            union = torch.sum(logits[:, class_index, :, :, :]) + torch.sum(targets[:, class_index, :, :, :])
            dice = (2. * inter + 1) / (union + 1)
            dices.append(dice.item())
        return np.asarray(dices)

class SoftDiceLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(SoftDiceLoss, self).__init__()

    def forward(self, logits, targets):
        num = targets.size(0)
        smooth = 1

        probs = F.sigmoid(logits)
        m1 = probs.view(num, -1)
        m2 = targets.view(num, -1)
        intersection = (m1*m2)

        score = 2.*(intersection.sum(1)+smooth/(m1.sum(1)+m2.sum(1)+smooth))
        score = 1 - score.sum() / num
        return score


#!/usr/bin/python

from collections import OrderedDict

from ..xml import _File
from .schema import _Schema
from ..error import (_NoSuchDocIdError, _NoSuchColumnError,)

# this module contains the saros db class.
# ##############################################################################

class _SarosDB:
    # this private class models Saros database -- the document repository.  it
    # offers methods for typical database operations -- queries & updates.
    #
    # NOTE:
    # there is no API, however, to link doc revisions; instead, clients must:
    # 1. request XML dump of a specific doc revision (i.e., doc name & revision)
    # 2. update XML with valid revision link info, & send it to SarosDB to load
    # 3. SarosDB then parses XML, & loads data
    # 4. After load, by default, SarosDB updates "last" of all revisions of the
    #    doc whose revision < revision of the just updated link.
    #
    # SCHEMA:
    # 1. each row represents a doc with a unique combination of "name" & "rev"
    # 2. doc_id -- unique combination of "name" & "rev" -- indexes each row
    # 3. a doc with same "name" may have >1 revision; each form a seperate row
    # 4. "name"     -> doc's name
    #    "rev"      -> doc's revision number (starts from 1, increase by 1)
    #    "prev"     -> "rev" of immediate predecessor; for "rev"=1, "prev"=0
    #    "Last"     -> last "rev" in the chain "rev" belongs ~ total revisions
    #    "content"  -> doc's content
    # 5. each row should have valid "prev" & "last" values; if not, we'll have
    #    broken revision chains.  Saros database, however, does not enforce this
    #    rule, so any broken revision links must be fixed thru a data update.
    #
    # DESIGN:
    # 1. the database -- __docs (see below) -- is modeled as a class variable,
    #    so that all _SarosDB instances share the same data, & database updates
    #    from any _SarosDB instance are available to all _SarosDB instances.
    # 2. to make (1) work, all methods are class methods, but you can still use
    #    _SarosDB().method().  ref: https://pythonbasics.org/classmethod/
    # 3. saros db maintains good data, with the exception that revisions may be
    #    unlinked.  good data means that data have right types; revisions
    #    consecutive; `id`, `name`, `last`, `prev`, & `content` values proper.
    # 4. saros has no api to add a document. the only way to update data in
    #    saros is through a file upload. so based on (3), the `schema` module
    #    offers basic schema validation for file data.  and saros app fixes any
    #    broken links.  with those 2 things, saros db should be just fine.

    # __docs = { doc_id: [ ("name", val), ("rev", val), ("prev", val), ("last", val), ("content", val) ] }
    # NOTE: the database contains broken revision links.
    __docs = { # represents the database
        "JE00-1": [("name", "JE00"), ("rev", 1), ("prev", 0), ("last", 3), ("content", "i am JE00-1")],
        "JE00-2": [("name", "JE00"), ("rev", 2), ("prev", 1), ("last", 3), ("content", "i am JE00-2")],
        "JE00-3": [("name", "JE00"), ("rev", 3), ("prev", 2), ("last", 3), ("content", "i am JE00-3")],
        "JE00-4": [("name", "JE00"), ("rev", 4), ("prev", 0), ("last", 6), ("content", "i am JE00-4")],
        "JE00-5": [("name", "JE00"), ("rev", 5), ("prev", 4), ("last", 6), ("content", "i am JE00-5")],
        "JE00-6": [("name", "JE00"), ("rev", 6), ("prev", 5), ("last", 6), ("content", "i am JE00-6")],
        "JE00-7": [("name", "JE00"), ("rev", 7), ("prev", 0), ("last", 8), ("content", "i am JE00-7")],
        "JE00-8": [("name", "JE00"), ("rev", 8), ("prev", 7), ("last", 8), ("content", "i am JE00-8")],
        "JE01-1": [("name", "JE01"), ("rev", 1), ("prev", 0), ("last", 2), ("content", "i am JE01-1")],
        "JE01-2": [("name", "JE01"), ("rev", 2), ("prev", 1), ("last", 2), ("content", "i am JE01-2")],
        "JE02-1": [("name", "JE02"), ("rev", 1), ("prev", 0), ("last", 4), ("content", "i am JE02-1")],
        "JE02-2": [("name", "JE02"), ("rev", 2), ("prev", 1), ("last", 4), ("content", "i am JE02-2")],
        "JE02-3": [("name", "JE02"), ("rev", 3), ("prev", 2), ("last", 4), ("content", "i am JE02-3")],
        "JE02-4": [("name", "JE02"), ("rev", 4), ("prev", 3), ("last", 4), ("content", "i am JE02-4")],
        "JE02-5": [("name", "JE02"), ("rev", 5), ("prev", 0), ("last", 7), ("content", "i am JE02-5")],
        "JE02-6": [("name", "JE02"), ("rev", 6), ("prev", 5), ("last", 7), ("content", "i am JE02-6")],
        "JE02-7": [("name", "JE02"), ("rev", 7), ("prev", 6), ("last", 7), ("content", "i am JE02-7")],
        "JE03-1": [("name", "JE03"), ("rev", 1), ("prev", 0), ("last", 1), ("content", "i am JE03-1")],
        "JE04-1": [("name", "JE04"), ("rev", 1), ("prev", 0), ("last", 1), ("content", "i am JE04-1")],
        "JE04-2": [("name", "JE04"), ("rev", 2), ("prev", 0), ("last", 2), ("content", "i am JE04-2")]
    }

    @classmethod
    def _dump(cls):
        # dump of all docs & their `id`s, sorted by `id`
        # returns [(doc_id, doc_data)], where doc_data=[(col_name, value)]
        dump=[]
        for _id in sorted(cls.__docs):
            data=cls.__doc_data(_id)    # fix for a nasty bug
            dump.append((_id, data))
        return dump

    @classmethod
    def _doc_names(cls):
        # list of all unique doc names, sorted by name
        names=[]
        for doc_id in cls.__docs:
            name=cls.__fetch(doc_id, _Schema.name)
            if name not in names:
                names.append(name)
        return sorted(names)

    @classmethod
    def _last_revs(cls, name):
        # gathers "last" for all revisions of doc named `name`
        # returns an unordered [ ("rev", "last") ]
        last_revs=[]
        for doc_id in cls.__docs:
            if name in doc_id:
                rev=cls.__fetch(doc_id, _Schema.rev)
                last=cls.__fetch(doc_id, _Schema.last)
                last_revs.append((rev, last))
        return last_revs

    @classmethod
    def _doc_dump(cls, name, rev, fname):
        # dumps doc named `name`, revision `rev` into file named `fname`
        # NOTE: `fname` does NOT include path & extn.
        doc_id=_Schema._doc_id(name, rev)
        data=cls.__doc_data(doc_id)    # fixed to avoid nasty bugs
        doc=[(_Schema.id.name, doc_id)] + data
        _File(fname)._write(doc)

    @classmethod
    def _load(cls, fname, link=True):
        # loads doc data contained in file named `fname` into the database.
        # by default (i.e., `link`=True), updates `last` of upstream revs.
        # NOTE: `fname` does NOT include path & extn.
        #
        # `doc`: doc data as an ordered dict with `_Schema` members as keys.
        doc=_File(fname)._schema_map()
        doc_id=doc.pop(_Schema.id)
        cls.__put(doc_id, doc.items())      # load doc into db
        if link:
            cls.__update_links(doc_id)

    @classmethod
    def __doc_data(cls, doc_id):
        # returns doc data, as a new list, for `doc_id`.
        # new list reqd; otherwise, any local changes, made either by clients or
        # by saros, will be reflected everywhere, creating nasty bugs.
        if not cls.__docs.has_key(doc_id):
            raise _NoSuchDocIdError(doc_id)
        return [item for item in cls.__docs[doc_id]]

    @classmethod
    def __update_links(cls, doc_id):
        # doc_id -> id of doc whose revision link has just been updated.
        # name -> name associated with `doc_id`
        # rev -> revision associated with `doc_id`
        # last -> last associated with `doc_id`
        #
        # for all revs `_rev` of doc named `name`, update links -- i.e., `last`
        # values -- if `_rev` < `rev`.
        last=cls.__fetch(doc_id, _Schema.last)
        name=cls.__fetch(doc_id, _Schema.name)
        rev=cls.__fetch(doc_id, _Schema.rev)
        for (_rev, _) in cls._last_revs(name):
            if _rev < rev:    # fix for a nasty bug
                _id=_Schema._doc_id(name, _rev)
                data=[(_Schema.last, last)]
                cls.__put(_id, data)

    @classmethod
    def __fetch(cls, doc_id, col):
        # given a doc_id & col (i.e., attribute), returns the value
        doc=cls.__doc_data_dict(doc_id)
        if doc.has_key(col.name):
            return doc[col.name]
        raise _NoSuchColumnError(doc_id, col)

    @classmethod
    def __put(cls, doc_id, data):
        # updates data -- [(col, val)] -- of doc referred by `doc_id`
        doc=cls.__doc_data_dict(doc_id)
        for (col, val) in data:
            if not doc.has_key(col.name):
                raise _NoSuchColumnError(doc_id, col)
            doc[col.name]=val
        cls.__docs[doc_id]=doc.items()

    @classmethod
    def __doc_data_dict(cls, doc_id):
        # returns an ord dict of doc data, allowing easy lookup.
        return OrderedDict(cls.__doc_data(doc_id))


import os
from pyBlang import variable, utils

class Result:

    def __init__(self, path, post_proc_option):
        self.path = path
        self.pp_option = post_proc_option
        self.__get_folders()
        self.print_folders()
        self.variables = self.__set_variables()

    def __get_folders(self):
        # res_options = {'NoPostProcessor': ['samples', 'monitoring'],
        #                'DefaultPostProcessor': ['samples', 'posteriorPlots', 'summaries', 'ess', 'tracePlots',
        #                                         'tracePlotsFull', 'monitoring', 'monitoringPlots']}

        if self.pp_option is 'DefaultPostProcessor':
            self.__get_samples()
            self.__get_posterior_plots()
            self.__get_summaries()
            self.__get_ess()
            self.__get_trace_plots()
            self.__get_trace_plots_full()
            self.__get_monitoring()
            self.__get_monitoring_plots()
        else:
            self.__get_samples()
            self.__get_monitoring()

    def __get_samples(self, dataframe=False):
        self.samples = [f for f in os.listdir(self.path+"/samples/") if not f.startswith('.')]
        for i in self.samples:
            if i.endswith('tsv'):
                self.samples.remove(i)
        self.samples = utils.build_idx_dict(self.samples, self.path + "/samples/")

    def __get_posterior_plots(self):
        self.post_plots = os.listdir(self.path + "/posteriorPlots")
        self.post_plots = utils.build_idx_dict(self.post_plots, self.path + "/posteriorPlots/")

    def __get_summaries(self):
        self.summaries = os.listdir(self.path + "/summaries")
        self.summaries = utils.build_idx_dict(self.summaries, self.path + "/summaries/")

    def __get_ess(self):
        self.ess_list = os.listdir(self.path + "/ess")
        self.ess_list = utils.build_idx_dict(self.ess_list, self.path + "/ess/")

    def __get_trace_plots(self):
        self.traces = os.listdir(self.path + "/tracePlots")
        self.traces = utils.build_idx_dict(self.traces, self.path + "/tracePlots/")

    def __get_trace_plots_full(self):
        self.traces_full = os.listdir(self.path + "/tracePlotsFull")
        self.traces_full = utils.build_idx_dict(self.traces_full, self.path + "/tracePlotsFull/")

    def __get_monitoring(self):
        self.monitoring = [f for f in os.listdir(self.path+"/monitoring/") if not f.startswith('.')]
        for i in self.monitoring:
            if i.endswith('tsv'):
                self.monitoring.remove(i)
        self.monitoring = utils.build_idx_dict(self.monitoring, self.path + "/monitoring/")

    def __get_monitoring_plots(self):
        self.monitoring_plots = os.listdir(self.path + "/monitoringPlots")
        self.monitoring_plots = utils.build_idx_dict(self.monitoring_plots, self.path + "/monitoringPlots/")

    def print_folders(self):
        print(str(vars(self).keys()).replace("dict_keys(", "Result folders are: ").replace(")", ""))

    def __set_variables(self):
        paths = self.samples.values()
        rvars = []
        for i in paths:
            rvars.append(variable.Variable(path=i))

        result = {}
        for i in rvars:
            result.update({i.name : i})
        return result


import boto3
import os
import posixpath
import io
import pandas as pd
from math import radians

from scipy.spatial import cKDTree

def lambda_handler(event, context):
    hdb_resale_prices = read_dataframe(
        join_path(
            os.environ["LOCATION_TRANSFORMED_ANALYTICS"],
            os.environ["STORAGE_FILE_HDB_RESALE_PRICES"],
        )
    )
    mrt_stations = read_dataframe(
        join_path(
            os.environ["LOCATION_TRANSFORMED_ANALYTICS"],
            os.environ["STORAGE_FILE_MRT_GEODATA"],
        )
    )
    mall_geodata = read_dataframe(
        join_path(
            os.environ["LOCATION_TRANSFORMED_ANALYTICS"],
            os.environ["STORAGE_FILE_MALL_GEODATA"],
        )
    )
    hdb_address_geodata = read_dataframe(
        join_path(
            os.environ["LOCATION_TRANSFORMED_ANALYTICS"],
            os.environ["STORAGE_FILE_HDB_ADDRESS_GEODATA"],
        )
    )

    feature_set = pd.merge(
        hdb_resale_prices,
        hdb_address_geodata,
        how="left",
        on=["block", "street_name"],
    )

    missing_latitude_count = feature_set["latitude"].isnull().sum()
    print(
        f"Number of rows with missing address location: {missing_latitude_count} out of {feature_set.shape[0]}"
    )
    feature_set = feature_set.dropna(subset=["latitude"])

    feature_set = _add_closest_mrt(feature_set, mrt_stations)
    feature_set = _add_closest_mall(feature_set, mall_geodata)
    feature_set = _add_distance_to_cbd(feature_set)

    dst_file = join_path(
        os.environ["LOCATION_TRANSFORMED_ANALYTICS"],
        os.environ["ANALYTICS_FILE_FEATURE_SET"],
    )

    write_dataframe(feature_set, dst_file)

    return event

def _add_closest_mrt(feature_set, mrt_stations):
    feature_set = _find_closest_location(feature_set, mrt_stations, "closest_mrt")
    return feature_set

def _add_closest_mall(feature_set, mall_geodata):
    feature_set = _find_closest_location(feature_set, mall_geodata, "closest_mall")

    return feature_set

def _add_distance_to_cbd(feature_set):
    cbd_location = pd.DataFrame.from_dict(
        {
            "latitude": [1.280602347559877],
            "longitude": [103.85040609311484],
            "name": "CBD",
        }
    )

    feature_set = _find_closest_location(feature_set, cbd_location, "cbd")

    return feature_set

def _find_closest_location(
    feature_set: pd.DataFrame, locations: pd.DataFrame, location_type: str
) -> pd.DataFrame:
    EARTH_RADIUS = 6371

    # Convert latitude and longitude to radians
    feature_set["latitude_rad"] = feature_set["latitude"].apply(radians)
    feature_set["longitude_rad"] = feature_set["longitude"].apply(radians)
    locations["latitude_rad"] = locations["latitude"].apply(radians)
    locations["longitude_rad"] = locations["longitude"].apply(radians)

    # Create a KDTree for the location dataframe
    location_tree = cKDTree(locations[["latitude_rad", "longitude_rad"]])

    # Query the KDTree for each point in the points dataframe
    distances, indices = location_tree.query(
        feature_set[["latitude_rad", "longitude_rad"]], k=1
    )

    # Get the closest entry from the location dataframe
    feature_set[f"{location_type}"] = locations.loc[indices, "name"].values  # type: ignore
    feature_set[f"distance_to_{location_type}"] = distances * EARTH_RADIUS * 1000

    # Drop the intermediate columns
    feature_set.drop(["latitude_rad", "longitude_rad"], axis=1, inplace=True)

    return feature_set

def join_path(*paths) -> str:
    return posixpath.join(*[str(path) for path in paths])

def read_dataframe(src_path: str) -> pd.DataFrame:
    print(f"Read dataframe from {src_path}")

    s3 = boto3.resource("s3")
    obj = s3.Object(os.environ["S3_BUCKET"], src_path)
    df = pd.read_csv(io.BytesIO(obj.get()["Body"].read()))

    return df

def write_dataframe(df: pd.DataFrame, dst_path: str) -> None:
    print(f"Write dataframe to {dst_path}")

    csv_buffer = io.StringIO()
    df.to_csv(csv_buffer, index=False)

    s3 = boto3.resource("s3")
    s3.Object(os.environ["S3_BUCKET"], dst_path).put(Body=csv_buffer.getvalue())


def is_prime(n):
    i=1
    nodiv=0
    while i<=n:
        if n%i==0:
            nodiv+=1
        i+=1
    if nodiv==2:
        return True
    else:
        return False

list1=[]
for i in range (10000,100000):
    if is_prime(i):
        istr=str(i)
        if istr[0]==istr[4] and istr[1]==istr[3]:
            list1.append(i)
print (list1)


import sys
import csv
import re

header = ['Peak_no','x','y']
data =[]
with open(sys.argv[1], encoding = 'utf-8') as f:
    in1 = f.readlines()

for i in in1:
    #print(i)
    if re.search(r"^\s+[0-9]+", i):
        #print(i)
        data.append([i.split()[0],i.split()[5],i.split()[6]])

with open('out.csv', 'w', encoding='UTF8', newline='') as f:
    writer = csv.writer(f)

    # write the header
    writer.writerow(header)

    # write multiple rows
    writer.writerows(data)


from .models import Course, Tag
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q

def searchCourses(request):
    search = ''
    if request.GET.get('search'):
        search = request.GET.get('search')

    tags = Tag.objects.filter(name__icontains=search)
    courses = Course.objects.distinct().filter(
        Q(title__icontains=search) | Q(owner__name__icontains=search) | Q(tags__in=tags))
    return courses, search

def paginationCourses(request, courses, results):
    page = request.GET.get('page')

    paginator = Paginator(courses, results)

    try:
        courses = paginator.page(page)
    except PageNotAnInteger:
        page = 1
        courses = paginator.page(page)
    except EmptyPage:
        page = paginator.num_pages
        courses = paginator.page(page)

    left_index = (int(page)-4)

    if left_index < 1:
        left_index = 1

    right_index = (int(page)+5)
    if right_index > paginator.num_pages:
        right_index = paginator.num_pages + 1

    custom_range = range(left_index, right_index)

    return custom_range, courses


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 16 02:39:13 2022

@author: arventh
"""

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import os
import math
import numpy as np
import pandas as pd
from scipy.signal import find_peaks
from matplotlib import rcParams
rcParams['font.family'] = 'sans-serif'
rcParams['font.sans-serif'] = ['Segoe UI']

folder = '/home/arventh/Documents/oxDNAdata/AV/TO-TD7/3-6_TD_force_design03' #raw_input directory
txt = '3-6_out_trajectory.dat'
os.chdir(folder)
data = open(txt, 'r')

dt = 0.005 #simulation time units (Output has time in MD units where MD units = steps * dt)
F_units = 48.63 #units in pN
l_units = 0.8518 #units in nm
t_units = 3.03e-12 #seconds
set1 = np.array([241, 220, 71])
set2 = np.array([71, 113, 92])
set3 = np.array([28, 7, 49])
set4 = np.array([199, 178, 157])
tri1, tri2, tri3, tri4 = [],[],[],[]
x, y1, y2, y3, y4 = [],[],[],[],[]

#functions
def length(i,j):
    dist = math.sqrt((i[0]-j[0])**2 + (i[1]-j[1])**2 + (i[2]-j[2])**2)
    return dist

def incircle(pts):
    a = length(pts[0:3],pts[3:6])
    b = length(pts[6:9],pts[3:6])
    c = length(pts[6:9],pts[0:3])
    Perimeter = a+b+c
    p = Perimeter/2
    Area = math.sqrt(p*(p-a)*(p-b)*(p-c))
    r = l_units*(2*Area)/Perimeter #https://brilliant.org/wiki/inscribed-triangles/
    return(r)

n = -3
for line in data:
    if n == -3:
        t = line.strip('t= \n')
        time = float(t)*dt*t_units*1e6 #time elapsed in microseconds
        x.append(time)
    n += 1
    if n in set1:
        Tri = np.array(line.split(), dtype=float)
        tri1.extend(Tri[0:3])
    if n in set2:
        Tri = np.array(line.split(), dtype=float)
        tri2.extend(Tri[0:3])
    if n in set3:
        Tri = np.array(line.split(), dtype=float)
        tri3.extend(Tri[0:3])
    if n in set4:
        Tri = np.array(line.split(), dtype=float)
        tri4.extend(Tri[0:3])
    if n == 252:
        y1.append(incircle(tri1))
        y2.append(incircle(tri2))
        y3.append(incircle(tri3))
        y4.append(incircle(tri4))
        #print (x, y1, y2, y3, y4)
        tri1, tri2, tri3, tri4 = [],[],[],[]
        n = -3

fig = plt.figure(5)       # size in inches
ax1 = fig.add_subplot(111)
ax1.set(title='Distances vs Time',ylabel='Distance (nm)',xlabel='Time (us)')
ax1.set(xlim=[0,12],ylim=[1,4])
plt.axhline(y=2.6, color="#aaaaaa", linestyle="--")

lw = 0.4
plt.plot(x, y1, linewidth=lw, alpha = 0.4, color='#00BFFF', label='Pore 1')
plt.plot(x, y2, linewidth=lw, alpha = 0.4, color='#00BFFF', label='Pore 2')
plt.plot(x, y3, linewidth=lw, alpha = 0.4, color='#00BFFF', label='Pore 3')
plt.plot(x, y4, linewidth=lw, alpha = 0.4, color='#00BFFF', label='Pore 4')

plt.savefig('Pore sizes vs Time for' + txt + '.svg', transparent=True)
plt.show()

for oolala in range(len(x)):
    csv = open("Pore_dilations_graph_plot.csv", "a")
    csv.write(str(x[oolala]) + ',' + str(y1[oolala]) + ',' + str(y2[oolala]) + ',' + str(y3[oolala]) + ',' + str(y4[oolala]) + '\n')

csv.close()
data.close()


import sys
import secrets
import copy
from util import *

sbox = [[0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76],
        [0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0],
        [0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15],
        [0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75],
        [0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84],
        [0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf],
        [0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8],
        [0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2],
        [0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73],
        [0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb],
        [0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79],
        [0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08],
        [0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a],
        [0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e],
        [0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf],
        [0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16]]

sbox_inv = [[0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB],
            [0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB],
            [0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E],
            [0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25],
            [0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92],
            [0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84],
            [0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06],
            [0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B],
            [0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73],
            [0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E],
            [0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B],
            [0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4],
            [0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F],
            [0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF],
            [0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61],
            [0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D]]

def print_state(state):
    for i in range(0, len(state)):
        print(hex(state[i][0]),hex(state[i][1]),hex(state[i][2]),hex(state[i][3]))

#------ AES HELPER FUNCTIONS ------

#assumes 0 <= n <= 255
def sub(n):
    return sbox[(n & 0xf0) >> 4][n & 0x0f]      #sbox[high bits][low bits]

#substitute every byte in the state using the s-box
def subBytes(state):
    for i in range(0, len(state)):
        for j in range(0, len(state[i])):
            state[i][j] = sub(state[i][j])

#assumes 0 <= n <= 255
def invSub(n):
    return sbox_inv[(n & 0xf0) >> 4][n & 0x0f]

def invSubBytes(state):
    for i in range(0, len(state)):
        for j in range(0, len(state[i])):
            state[i][j] = invSub(state[i][j])

#does a left circular shift on the elements of row
#ex. shift([0, 1, 2, 3]) -> [1, 2, 3, 0]
def shift(row):
    temp = row[0]
    for i in range(0, len(row) - 1):
        row[i] = row[i+1]

    row[len(row)-1] = temp

#applies the left circular shift n times, where n is the index of the row
def shiftRows(state):
    for i in range(0, len(state)):
        for j in range(0, i):
            shift(state[i])

#does a right circular shift on the elements of row
#ex. shift([0, 1, 2, 3]) -> [3, 0, 1, 2]
def invShift(row):
    temp = row[len(row)-1]
    for i in range(len(row)-1, 0, -1):
        row[i] = row[i-1]

    row[0] = temp

#applies the right circular shift n times, where n is the index of the row
def invShiftRows(state):
    for i in range(0, len(state)):
        for j in range(0, i):
            invShift(state[i])

#mixColumns multiplies each column of the state [b3, b2, b1, b0], represented as
#b3*x^3 + b2*x^2 + b1*x + b0, by the constant polynomial 3x^3 + x^2 + x + 2 modulo x^4 + 1.
#all these polynomials have coefficients in GF(2^8)
xtime = lambda a: (((a << 1) ^ 0x1B) & 0xFF) if (a & 0x80) else (a << 1)

def mix(col):

    t = col[0] ^ col[1] ^ col[2] ^ col[3]
    u = col[0]
    col[0] ^= t ^ xtime(col[0] ^ col[1])
    col[1] ^= t ^ xtime(col[1] ^ col[2])
    col[2] ^= t ^ xtime(col[2] ^ col[3])
    col[3] ^= t ^ xtime(col[3] ^ u)

def mixColumns(state):

    for i in range(0, 4):
        col = [state[0][i], state[1][i], state[2][i], state[3][i]]
        mix(col)
        state[0][i] = col[0]
        state[1][i] = col[1]
        state[2][i] = col[2]
        state[3][i] = col[3]

#sets up the inverse polynomial in the state, so that when mixColumns is called again, the
#original polynomial is obtained
def invMixColumns(state):
    for i in range(4):
        u = xtime(xtime(state[0][i] ^ state[2][i]))
        v = xtime(xtime(state[1][i] ^ state[3][i]))
        state[0][i] ^= u
        state[1][i] ^= v
        state[2][i] ^= u
        state[3][i] ^= v

    mixColumns(state)

#XORs each byte of the state with each corresponding byte of the subkey
def addRoundKey(state, subkey):
    for i in range(0, len(state)):
        for j in range(0, len(state[i])):
            state[i][j] = state[i][j] ^ subkey[j][i]

#------ KEY SCHEDULER ------

#puts each byte in the given word through the s-box
def subWord(word):
    for i in range(0, 4):
        word[i] = sub(word[i])

#does a left circular shift on the bytes in the word
def rotWord(word):
    shift(word)

#based directly on the pseudocode from FIPS-197 section 5.2
def keyExpansion(main_key, nk): #-- TODO: verify correctness for nk != 4
    temp = []
    i = 0
    rcon = [0x0, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
    keys = []

    while i < nk:
        keys.append([main_key[4*i], main_key[4*i + 1], main_key[4*i + 2], main_key[4*i + 3]])
        i += 1

    i = nk

    while i < (4 * ((nk+6) + 1)):
        temp = keys[i-1].copy()

        if (i % nk) == 0:
            rotWord(temp)
            subWord(temp)
            temp[0] = temp[0] ^ rcon[i//nk]
        elif (nk > 6 and i % nk == 4):
            temp = subWord(temp)
        else:
            pass

        for j in range(0, len(temp)):
            temp[j] = keys[i-4][j] ^ temp[j]

        keys.append(temp.copy())

        i += 1

    return keys

#---------------    CIPHERS    ---------------

#based on FIPS-197 section 5.1
#this encrypts a single 16-byte block of data
#state is assumed to be a 4x4 array of bytes, keys is 44x4 array of bytes
def aes(state, keys):
    nb = 4
    nr = 10

    addRoundKey(state, keys[0:nb])

    for i in range(1, nr):
        subBytes(state)
        shiftRows(state)
        mixColumns(state)
        addRoundKey(state, keys[i*nb: (i+1)*nb])

    subBytes(state)
    shiftRows(state)
    addRoundKey(state, keys[nr*nb:(nr+1)*nb])
    return 0

#based on FIPS-197 section 5.3
#this decrypts a single 16-byte block of data
#parameters are the same as in aes()
def invAes(state, keys):
    nb = 4
    nr = 10

    addRoundKey(state, keys[nr*nb:(nr+1)*nb])

    for i in range(nr-1, 0, -1):
        invShiftRows(state)
        invSubBytes(state)
        addRoundKey(state, keys[i*nb: (i+1)*nb])
        invMixColumns(state)

    invShiftRows(state)
    invSubBytes(state)
    addRoundKey(state, keys[0:nb])

#------------ FILE I/O ------------

#takes an array of bytes of unknown size b, and formats it into the state array
def make_state(b):

    if len(b) == 16:
        state = [[b[0], b[4], b[8], b[12]],
                 [b[1], b[5], b[9], b[13]],
                 [b[2], b[6], b[10], b[14]],
                 [b[3], b[7], b[11], b[15]]]

    else:
        state = [[0, 0, 0, 0],
                 [0, 0, 0, 0],
                 [0, 0, 0, 0],
                 [0, 0, 0, 0]]

        #handles the case where b does not contain 16 bytes
        for i in range(0, 15):
            try:
                state[i//4][i%4] = b[(i*4)%15]
            except:
                pass

    return state

#reads plaintext bytes from file
def get_bytes(filename):
    plaintext = []

    f = open(filename, "rb")

    try:
        bytes_read = f.read(16)
        while bytes_read:
            plaintext.append(make_state(bytes_read))
            bytes_read = f.read(16)
    finally:
        f.close()

    return plaintext

#reads bytes from keyfile
def get_key(filename):
    f = open(filename, "rb")

    try:
        bytes_read = f.read(16)
        if len(bytes_read) < 16:
            print("file not large enough!")
            exit()
    finally:
        f.close()

    #print(bytes_read)
    return bytes_read

#writes the text, formatted as an array of 4x4 states, to the output file
def write_to_output(filename, text):
    f = open(filename, "wb")

    for i in range(0, len(text)):
        for j in range(0, len(text[i])):
            for k in range(0, len(text[i][j])):
                if i == len(text)-1 and text[i][k][j] == 0:
                    pass
                else:
                    f.write(bytes([text[i][k][j]]))

    f.close()

def get_iv(iv):
    for i in range(0, 4):
        temp = [0] * 4

        for i in range(0, len(temp)):
            temp[i] = bytes("5", "utf8")[0] #secrets.randbits(8)

        iv.append(temp)

#---------- DON'T USE THIS!!! ---------------------------
def aes_ecb(plaintext_filename, key_filename, output_filename, n):
    input_text = get_bytes(plaintext_filename)
    key_bytes = get_key(key_filename)
    keys = keyExpansion(key_bytes, 4)

    if n == 0:
        for i in range(0, len(input_text)):
            aes(input_text[i], keys)

    if n == 1:
        for i in range(0, len(input_text)):
            invAes(input_text[i], keys)

    write_to_output(output_filename, input_text)

def aes_cbc(plaintext_filename, key_filename, output_filename, n):
    iv = []
    get_iv(iv)

    input_text = get_bytes(plaintext_filename)
    key_bytes = get_key(key_filename)
    keys = keyExpansion(key_bytes, 4)

    if n == 0:
        addRoundKey(input_text[0], iv)
        aes(input_text[0], keys)

        for i in range(1, len(input_text)):
            addRoundKey(input_text[i], input_text[i-1])
            aes(input_text[i], keys)

        input_text = [iv] + input_text

        write_to_output(output_filename, input_text)

    if n == 1:

        last_block = copy.deepcopy(input_text[0])

        for i in range(1, len(input_text)):
            current_block = copy.deepcopy(input_text[i])

            invAes(input_text[i], keys)
            addRoundKey(input_text[i], last_block)

            last_block = copy.deepcopy(current_block)

        write_to_output(output_filename, input_text[1:])

def flatten(states):
    result = []
    for i in range(0, len(states)):
        for j in range(0, len(states[i])):
            for k in range(0, len(states[i][j])):
                #if i == len(states)-1 and states[i][k][j] == 0:
                #    pass
                #else:
                result.append(states[i][k][j])

    return result

def ark(state, subkey):
    for i in range(0, len(state)):
        for j in range(0, len(state[i])):
            state[i][j] = state[i][j] ^ subkey[i][j]

def format_iv(iv):
    f = [[iv[0], iv[4], iv[8], iv[12]],
         [iv[1], iv[5], iv[9], iv[13]],
         [iv[2], iv[6], iv[10], iv[14]],
         [iv[3], iv[7], iv[11], iv[15]]]

    return f

def aes_cbc_encrypt(key, data, iv_):
    iv = format_iv(iv_)
    temp = copy.deepcopy(data)
    states = []
    keys = keyExpansion(key, 4)

    while len(temp) > 0:
        states.append(make_state(temp[:16]))
        temp = temp[16:]

    ark(states[0], iv)
    aes(states[0], keys)

    for i in range(1, len(states)):
        ark(states[i], states[i-1])
        aes(states[i], keys)

    s = bytes(flatten(states))

    return s

def aes_cbc_decrypt(key, data, iv):
    temp = copy.deepcopy(data)
    states = []
    keys = keyExpansion(key, 4)

    while len(temp) > 0:
        states.append(make_state(temp[:16]))
        temp = temp[16:]

    last_block = format_iv(iv) #copy.deepcopy(states[0])

    for i in range(0, len(states)):
        current_block = copy.deepcopy(states[i])
        invAes(states[i], keys)
        ark(states[i], last_block)
        last_block = copy.deepcopy(current_block)

    s = bytes(flatten(states))
    #s = s + bytes([0])

    return s


############### FK Arm##############3
import pymel.core as pm
import maya.cmds as cmds

def shapeBuilderUI():

    if cmds.window('Win' ,exists=True):
       cmds.deleteUI('Win')

    if cmds.windowPref('Win', exists=True ):
       cmds.windowPref( 'Win', r=True )

    cmds.window('Win',title='FK Setup',s=0,h=600,w=300)
    cmds.showWindow('Win')

    form = cmds.formLayout('form01',bgc =[(.179),(.179),(.189)],w=300,h=600)

    cmds.text('Text_Joints',l='Number Of Joints')
    cmds.intField('intField_Jnts',w=240,h=25)
    cmds.separator('S01')
    cmds.button('Button_CreateJnts',l='Create Joints',w=150,h=25,bgc=[(.2),(.5),(.4)],c='createJoints()')
    ######################################################################################
    cmds.text('txtOrient',l='ORIENT JOINTS')
    cmds.checkBox('bxyz',label='XYZ')
    cmds.checkBox('bzxy',label='ZXY')
    cmds.checkBox('byzx',label='YZX')
    cmds.button('Button_OrientJnts',l='Orient Joints',w=150,h=25,bgc=[(.2),(.5),(.4)],c='orientJoints()')
    ########################################################################
    cmds.text('textCtrl',l='CONTROLLER')
    cmds.optionMenu('OptMenu', h=20,ann=('It will create the controller'),bgc=[(.2),(.5),(.4)])
    cmds.menuItem('CubeMenu',l='Cube')
    cmds.menuItem('CircleMenu',l='Sphere')
    cmds.menuItem('SquareMenu',l='Square')

    #######################################################################
    cmds.text('txtSize',l='CONTROLLER SIZE')
    cmds.intSliderGrp('sizeSlider',l='Size',min=1,f=True,w=365)
    ###############################################################
    cmds.text('txtColor',l='CONTROLLER COLOR')
    cmds.colorIndexSliderGrp('colorSlider', label='Color', min=0, max=20, value=10 )
    ##################################################
    cmds.text('Text_Suffix',l='SUFFIX')
    cmds.textField('txtF',w=240,h=25)

    ######################################3
    cmds.button('Button_FkChain',l=' Build FK_Chain',c='fkSetup()',bgc=[(.057),(.074),(.1)],h=38,w=75)
    cmds.button('Button_IkChain',l=' Build IK_Chain',c='IkSetup()',bgc=[(.057),(.074),(.1)],h=38,w=75)
    cmds.button('Button_Fk_IK_Chain',l=' Build FK_IkChain',c='fk_IkSetup()',bgc=[(.057),(.074),(.1)],h=38,w=75)

    cmds.formLayout('form01',edit=True,attachForm=[('Text_Joints','top', 13),
    ('Text_Joints','left',98),
    ('intField_Jnts','left',30),
    ('Button_CreateJnts','left',34),
    ('Button_CreateJnts','right',30),
    ('txtOrient','left',30),
    ('txtOrient','right',30),
    ('bxyz','left',32),
    ('Button_OrientJnts','left',30),
    ('Button_OrientJnts','right',30),

    ('textCtrl','right',30),
    ('textCtrl','left',30),
    ('OptMenu','right',30),
    ('OptMenu','left',30),

    ('txtSize','right',30),
    ('txtSize','left',30),
    ('sizeSlider','left',-87),
    ('colorSlider','left',-87),
    ('txtColor','left',30),
    ('txtColor','right',30),
    ('Text_Suffix','right',30),
    ('Text_Suffix','left',30),
    ('Button_FkChain','left',30),
    ('txtF','left',30),

    ],

    attachControl=[('intField_Jnts','top',8,'Text_Joints'),
    ('Button_CreateJnts','top',5,'intField_Jnts'),
    ('txtOrient','top',12,'Button_CreateJnts'),
    ('bxyz','top',11,'txtOrient'),
    ('bzxy','top',11,'txtOrient'),
    ('byzx','top',11,'txtOrient'),
    ('Button_OrientJnts','top',10,'bzxy'),
    ('textCtrl','top',5,'Button_OrientJnts'),
    ('OptMenu','top',10,'textCtrl'),
    ('txtSize','top',10,'OptMenu'),
    ('sizeSlider','top',10,'txtSize'),
    ('txtColor','top',10,'sizeSlider'),
    ('colorSlider','top',10,'txtColor'),
    ('Text_Suffix','top',10,'colorSlider'),
    ('txtF','top',10,'Text_Suffix'),
    ('Button_FkChain','top',14,'txtF'),
    ('Button_IkChain','top',14,'txtF'),
    ('Button_Fk_IK_Chain','top',14,'txtF'),

    ('bzxy','left',56,'bxyz'),
    ('byzx','left',56,'bzxy'),
    ('Button_IkChain','left',5,'Button_FkChain'),
    ('Button_Fk_IK_Chain','left',5,'Button_IkChain')

    ])

###############################################################################
##                        Creating Functions                                ###
###############################################################################

#Function for creating joints

def createJoints():
	jntList=[]
	Jnts=cmds.intField('intField_Jnts',query=True,value=True)
	for i in range(Jnts):
		number = i+1
		a=pm.joint(n = 'Tmp_0'+str(number)+'_Jnt')
		pm.xform(t=(1,0,0))
		jntlist.append(a)

def orientJoints():
    cmds.checkBox('bxyz',label='XYZ',q=True,value=True,sl=True)

    for i in range(a):
        cmds.joint(e=True,zso=True, oj='xyz',secondaryAxisOrient='yup',ch=True)

shapeBuilderUI()


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

def matrix_multiplication_with_blocking(matrix_size, block_size):
    m1 = np.random.rand(matrix_size, matrix_size)
    m2 = np.random.rand(matrix_size, matrix_size)
    # intialize zero matrix same size of m1 & m2
    res = np.zeros((matrix_size, matrix_size))

    for i in range(0, matrix_size, block_size):
        for j in range(0, matrix_size, block_size):
            for k in range(0, matrix_size, block_size):
                m1_block = m1[i:i+block_size, k:k+block_size]
                m2_block = m2[k:k+block_size, j:j+block_size]
                res[i:i+block_size, j:j+block_size] += np.dot(m1_block, m2_block)
    return res

def matrix_multiplication_without_blocking(matrix_size):
    A = np.random.rand(matrix_size, matrix_size)
    B = np.random.rand(matrix_size, matrix_size)
    m, n = A.shape
    n, p = B.shape
    C = np.zeros((m, p))
    for i in range(m):
        for j in range(p):
            for k in range(n):
                C[i,j] += A[i,k] * B[k,j]
    return C

matrix_sizes = [64,128,256,512]
block_sizes = [1,4,8,16,32]

results = []
for matrix_size in matrix_sizes:
    for block_size in block_sizes:
        start_time = time.time()
        matrix_multiplication_with_blocking(matrix_size, block_size)
        end_time = time.time()
        time_taken = end_time - start_time
        results.append((matrix_size, block_size, time_taken))

df = pd.DataFrame(results, columns=['Matrix Size', 'Block Size', 'Time Taken'])
# Create a plot
fig, ax = plt.subplots(figsize=(10,10))

for matrix_size in matrix_sizes:
    ax.set_xlabel('Block Size')
    ax.set_ylabel('Execution Time (s)')
    ax.set_title('Figure 1')
    ax.plot(df[df['Matrix Size']==matrix_size]['Block Size'], df[df['Matrix Size']==matrix_size]['Time Taken'], label='Matrix Size = ' + str(matrix_size))

ax.legend()
plt.show()

# crate a table
table = pd.pivot_table(df, values='Time Taken', index=['Matrix Size'], columns=['Block Size'])
table_formatted = table.applymap(lambda x: '{:.4f}'.format(x))
fig2 = plt.figure(figsize=(12,8))
plt.axis('off')
plt.title('Figure 2\nMatrix Multiplication with Blocking Results', fontsize=12)
plt.table(cellText=table_formatted.values, colLabels=table_formatted.columns, rowLabels=table_formatted.index, loc='center', fontsize=20)
plt.show()

#main for matrix multiplication without blocking

results = []
for matrix_size in matrix_sizes:
    start_time = time.time()
    matrix_multiplication_without_blocking(matrix_size)
    end_time = time.time()
    time_taken = end_time - start_time
    results.append((matrix_size, time_taken))

df = pd.DataFrame(results, columns=['Matrix Size', 'Time Taken'])

# Create a plot
plt.plot(df['Matrix Size'], df['Time Taken'])
plt.xlabel('Matrix Size')
plt.ylabel('Execution Time (s)')
plt.title('Figure 1')
plt.show()

# Create a table
fig, ax = plt.subplots(figsize=(8, 6))
table_values = df.applymap(lambda x: '{:.4f}'.format(x)).values
table = ax.table(cellText=table_values, colLabels=df.columns, loc='center')
ax.set_title('Figure 2')
ax.set_xlabel('Matrix Size')
ax.set_ylabel('Execution Time (s)')
ax.axis('off')
plt.show()


from rest_framework import status, viewsets
from rest_framework.response import Response
from django.contrib.auth.decorators import login_required

from aircraft.models import Aircraft
from aircraft.serializers import AircraftSerializer

class AircrafViewSet(viewsets.GenericViewSet):
    """
    A simple GenericViewSet for aircrafts CRUD operations
    """
    serializer_class = AircraftSerializer
    queryset = Aircraft.objects.all()

    def list(self, request):
        """
        Return a list of all existing aircrafts
        """
        serializer = self.get_serializer(self.get_queryset(), many=True)
        return Response(serializer.data)

    def retrieve(self, request, pk):
        """
        Return the given aircraft
        """
        item = self.get_object()
        serializer = self.get_serializer(item)
        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        """
        Create a new aircraft instance
        """
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def update(self, request, *args, **kwargs):
        """
        Update the given aircraft
        """
        item = self.get_object()
        serializer = self.get_serializer(item, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_202_ACCEPTED)

    def destroy(self, request, pk=None):
        """
        Delete the given aircraft
        """
        item = self.get_object()
        item.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)


#!/usr/bin/env python3
# -*-coding:utf-8-*-

class Solution(object):
    def trap(self, height):
        """
        :type height: List[int]
        :rtype: int
        """

        # solution1:
        # return self.solution1_exhaustion(height)

        # solution2:
        return self.solution2_two_pointers(height)

    def solution1_exhaustion(self, height):
        water = 0
        left_max = {}
        right_max = {}
        for index in range(len(height)):
            left_max[index] = 0 if index == 0 else max(left_max[index - 1], height[index - 1])

        for index in range(len(height)):
            index = len(height) - 1 - index
            right_max[index] = (0 if index == len(height) - 1
                                else max(right_max[index + 1], height[index + 1])
                                )

        for index, value in enumerate(height):
            if min(left_max[index], right_max[index]) > value:
                water += min(left_max[index], right_max[index]) - value

        return water

    def solution2_two_pointers(self, height):
        water = 0
        left = 0
        right = len(height) - 1
        left_max = 0
        right_max = 0

        while left < right:
            if height[left] > height[right]:
                if right_max > height[right]:
                    water += right_max - height[right]
                else:
                    right_max = height[right]
                right -= 1
            else:
                if left_max >= height[left]:
                    water += left_max - height[left]
                else:
                    left_max = height[left]
                left += 1
        return water


import requests
import schedule
import time

def send_sms():
    resp = requests.post('https://textbelt.com/text', {
        'phone' : '+8801778124049',
        'message' : 'hello mithun',
        'key' : 'texbelt',
    })
    print(resp.json)

schedule.every().day.at('06:00').do(send_sms)

while True:
    schedule.run_pending()
    time.sleep(1)


import os.path
import natsort
import random
import itertools
import numpy as np
import cv2
import shutil
import glob,os.path

from matplotlib import pyplot as plt

DIR_IMAGES = "Images"
VIEWS_IMAGES = ["Inferior","Superior"]

BORDER = 25
SIZE = 250

THRESHOLD_LOWER = np.array([0,0,0])
THRESHOLD_UPPER = np.array([250,250,250])

N_NEW_IMAGES = 10
GENERATE_IMAGES = 1

def run():

    # Checa se os diretórios foram corretamente divididos pelo usuário
    filesDepth3 = glob.glob('Images/*/*/*')
    dirsDepth3 = list(filter(lambda f: os.path.isdir(f), filesDepth3))

    if len(dirsDepth3) > 0:
        print("ERRO: Os subfolders da pasta images devem ter uma profundidade maxima de 2.")
        print("As seguintes pasta não estão seguindo este critério: ")
        for depth in dirsDepth3:
            print(depth)
        #end for
        print("Corrigir antes de prosseguir!!!")
        return
    #end if

    filesDepth2 = glob.glob('Images/*/*')
    dirsDepth2 = list(filter(lambda f: os.path.isdir(f), filesDepth2))

    for views in dirsDepth2:
        if views.split("\\")[-1] not in VIEWS_IMAGES:
            print("ERRO: A vista %s do grupo %s não é suportada por este programa!!"%(views.split("\\")[-1],views.split("\\")[-2]))
            print("Corrigir de prosseguir!!!")
            return
        #end if
    #end for

    if os.path.isdir("training_images"):
        shutil.rmtree('training_images', ignore_errors=True)
    #end if

    #Cria os diretórios para cada grupo e os seus subdiretórios com as vistas
    for dirToCreate in filesDepth2:
        os.makedirs("training_images\\%s"%dirToCreate[7:])

    for path, subdirs, files in os.walk(DIR_IMAGES):
        imgNumber = 0
        for name in files:
            if name.lower().endswith(".jpg"):
                try:
                    filePath = path + "\\" + name
                    imageView = path.split("\\")[-1]
                    imageGroup = path.split("\\")[-2]

                    imageResized = cropAndResizeImg(filePath)

                    if GENERATE_IMAGES:
                        newImages = generateImages(imageResized)
                        for img in newImages:
                            cv2.imwrite(("training_images\\%s\\%s\\%s.jpg"%(imageGroup,imageView,imgNumber)),img)
                            imgNumber +=1
                    else:
                        cv2.imwrite(("training_images\\%s\\%s\\%s.jpg"%(imageGroup,imageView,imgNumber)),newImages)
                        imgNumber += 1
                except Exception as e:
                    print(("ERROR: IMAGEM %s: "%name),str(e))
            #end if
        #end for
    #end for
#end def

def generateImages(image):
    img_Crop = image[BORDER-1:BORDER+SIZE-1, BORDER-1:BORDER+SIZE-1]

    # Generate all possible non-repeating pairs
    numbers = [i for i in range(0,51)]
    pairs = np.array(list(itertools.combinations(numbers, 2)))
    random.shuffle(pairs)

    newImages = []

    for i in range(0,N_NEW_IMAGES):
        [x,y] = random.choice(pairs)
        np.delete(pairs,[x,y])

        left = x if x <= 24 else 50 - x
        right = 50 - x if x <= 24 else x
        top = y if y <= 24 else 50 - y
        bottom = 50 - y if y <= 24 else y

        newImages.append(cv2.copyMakeBorder(img_Crop, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[255,255,255]))

    return newImages
    #end for
#end def

def cropAndResizeImg(image):
    img_BGR = np.array(cv2.imread(image))

    mask = cv2.inRange(img_BGR, THRESHOLD_LOWER, THRESHOLD_UPPER)
    img_threshold = cv2.bitwise_and(img_BGR,img_BGR, mask= mask)

    img_Crop = cropImageObject(img_threshold,img_BGR)

    img_resized = cv2.resize(img_Crop, (SIZE,SIZE))

    img_Border10 = cv2.copyMakeBorder(img_resized, BORDER, BORDER, BORDER, BORDER, cv2.BORDER_CONSTANT, value=[255,255,255])

    return img_Border10

def cropImageObject(img_threshold, img):
    img_Gray = cv2.cvtColor(img_threshold, cv2.COLOR_BGR2GRAY)
    x,y,w,h = cv2.boundingRect(img_Gray)

    if h > w:
        if h % 2 == 0:
            return img[y:y+h, x-(h-w)//2:x+w+(h-w)//2]
        else:
            return img[y:y+h, x-(h-w)//2:x+w+(h-w)//2+1]
        #end if
    elif h < w:
        if h % 2 == 0:
            return img[y-(w-h)//2:y+h+(w-h)//2, x:x+w]
        else:
            return img[y-(w-h)//2:y+h+(w-h)//2+1, x:x+w]
        #end if
    elif h == 2:
        return img[y:y+h, x:x+w]
    #end if
#end def


# Need this to import from parent directory when running outside pycharm
import os
import glob
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), os.pardir))

from ac_utils.general import load_from_json, save_to_json, promt_user_to_abort_if_file_exists, print_progress, \
    seconds_to_day_hour_minute_second
from ac_utils.worker import WorkParallelizer
import tempo_estimation.analysis_algorithms as rhythm_algorithms
import key_estimation.analysis_algorithms as tonal_algorithms
import pitch_estimation.analysis_algorithms as pitch_algorithms
from ac_utils import analysis_algorithms as general_algorithms
celery_available = True
try:
    from tasks import run_analysis_algorithm
except ImportError:
    # This can happen if celery is not available and run_analysis_algorithm is not defined
    # We set the celery available flag here so the script knows
    celery_available = False
import click
import time

@click.command()
@click.argument('dataset_path')
@click.option('--algorithms', default='',
              help='Algorithm names separated by commas')
@click.option('--max_sounds', default=None, help='Max number of sounds to analyze (default None).')
@click.option('--save_every', default=100, help='Save analysis results every X processed sounds (default 100).')
@click.option('--incremental', default=False, is_flag=True,
              help='If an analysis file is found for the given algorithm and this option is set to true, the algorithm '
                   'will only analyse the sounds that have not been analysed yet (default False).')
@click.option('--use_celery', default=False, is_flag=True,
              help='Whether to use celery for running the analysis tasks (default False).')
@click.option('--force', default=False, is_flag=True,
              help='Overwrite existing analysis files without asking (default False).')
@click.option('--workers', default=4, help='Number of workers to use for parallelized analysis of audio files (default 4).')
def analyze_dataset(dataset_path, algorithms, max_sounds, save_every, incremental, use_celery, force, workers):
    """
    Analyze the audio files in a dataset with the specified algorithms.
    """

    if use_celery and not celery_available:
        print('Celery not found, will analyze ignoring --use_celery option')
        use_celery = False

    available_algorithms = list()
    for algorithms_set in [rhythm_algorithms, general_algorithms, tonal_algorithms, pitch_algorithms]:
        for item in dir(algorithms_set):
            if item.startswith('algorithm_'):
                available_algorithms.append([
                    item.replace('algorithm_', ''),
                    algorithms_set.__getattribute__(item)
                ])

    analysis_algorithms_to_run = list()
    algorithm_names = algorithms.split(',')
    for algorithm_name, algorithm_function in available_algorithms:
        if algorithm_name in algorithm_names:
            out_file_path = os.path.join(dataset_path, "analysis_%s.json" % algorithm_name)
            if not incremental and not force:
                if promt_user_to_abort_if_file_exists(out_file_path, throw_exception=False):
                    analysis_algorithms_to_run.append([algorithm_name, algorithm_function])
            else:
                analysis_algorithms_to_run.append([algorithm_name, algorithm_function])
    if not analysis_algorithms_to_run:
        click.echo('No analysis algorithms to run. Available algorithms are:')
        for name, _ in available_algorithms:
            click.echo('\t%s' % name)
        return

    if use_celery:
        click.echo('We detected you\'re using celery to run the tasks, here are some useful commands:')
        click.echo('\tsudo rabbitmq-server -detached             (start rabbitmq broker)')
        click.echo('\tsudo rabbitmqctl stop                      (stop rabbitmq broker)')
        click.echo('\tcelery -A tasks worker --concurrency=4     (start Celery workers)')
        click.echo('\tcelery -A tasks purge                      (clear Celery queue)')

    metadata = load_from_json(os.path.join(dataset_path, "metadata.json"))
    algorithms_run = 0
    for analysis_algorithm_name, analysis_algorithm in analysis_algorithms_to_run:
        start_timestamp = time.time()
        algorithms_run += 1
        click.echo("Analyzing '%s' dataset [%i/%i] - %s" %
                   (dataset_path, algorithms_run, len(analysis_algorithms_to_run), analysis_algorithm_name))
        if max_sounds is None:
            max_sounds = len(metadata)
        else:
            max_sounds = int(max_sounds)

        out_file_path = os.path.join(dataset_path, "analysis_%s.json" % analysis_algorithm_name)
        analysis_results = dict()
        if incremental and os.path.exists(out_file_path):
            # Load existing analysis file (if it exists)
            analysis_results = load_from_json(out_file_path)
            click.echo("Continuing existing analysis (%i sounds already analysed)" % len(analysis_results))

        label = "Sending sounds to analyze..."
        asynchronous_job_objects = None
        wp = None
        if use_celery:
            asynchronous_job_objects = list()
        else:
            wp = WorkParallelizer(show_widgets=False)
        with click.progressbar(list(metadata.values())[:max_sounds], label=label) as sounds_metadata:
            for count, sound in enumerate(sounds_metadata):
                if incremental:
                    if str(sound['id']) in analysis_results:
                        # If analysis for that sound already exists, continue iteration with the next sound
                        continue

                # If there is no existing analysis, run it
                try:
                    sound['file_path'] = glob.glob(dataset_path + '/audio/wav/' + str(sound['id']) + '_*.wav')[0]
                    if not use_celery:
                        # Add jobs to work paralellizer
                        wp.add_task(analysis_algorithm, sound, task_id=sound['id'])
                    else:
                        task_object = run_analysis_algorithm.delay(analysis_algorithm, sound)
                        asynchronous_job_objects.append((sound['id'], task_object))
                except Exception:
                    print("Could not find " + str(sound['id']))

        if use_celery and len(asynchronous_job_objects):
            # Enter a loop to check status of jobs and add jobs to metadata as they get done
            finished_asynchronous_job_objects = dict()
            n_total_jobs = len(asynchronous_job_objects)
            n_jobs_done_in_last_save = 0
            while len(asynchronous_job_objects) != 0:
                time.sleep(1)
                i = 0
                jobs_to_delete_from_list = list()  # store position of job_objects in asynchronous_job_objects
                # that will be deleted after each while iteration
                for sound_id, job_object in asynchronous_job_objects:
                    max_objects_to_check = 100
                    if job_object.ready():
                        # Job is finished
                        finished_asynchronous_job_objects[sound_id] = job_object
                        jobs_to_delete_from_list.append(i)
                        try:
                            analysis = job_object.get()
                            if analysis:
                                analysis_results[sound_id] = analysis
                            else:
                                continue
                        except RuntimeError:
                            pass
                    i += 1
                    if i >= max_objects_to_check:
                        # We only check the first 'max_objects_to_check' in each iteration.
                        # Assuming that jobs are being processed approximately in the order they were sent,
                        # we should be fine.
                        break
                for index in sorted(jobs_to_delete_from_list, reverse=True):
                    del asynchronous_job_objects[index]
                print_progress('Analyzing sounds...', len(finished_asynchronous_job_objects), n_total_jobs,
                               start_time=start_timestamp, show_progress_bar=True)
                # Estimate time remaining
                if len(finished_asynchronous_job_objects) - n_jobs_done_in_last_save >= save_every:
                    # Save progress every 100 analysed sounds
                    n_jobs_done_in_last_save += len(finished_asynchronous_job_objects)
                    save_to_json(out_file_path, analysis_results)
            print('')
        else:
            wp.start(num_workers=workers)
            while True:
                time.sleep(1)
                finished = wp.show_progress()

                tasks_succeeded = wp.tasks_succeeded()
                for task in tasks_succeeded:
                    sound_id = task.id
                    if sound_id not in analysis_results:
                        analysis_results[sound_id] = task.result(timeout=0.0)

                if len(tasks_succeeded) % save_every == 0:
                    save_to_json(out_file_path, analysis_results)

                if finished:
                    break

            wp.show_errors()

        # Report number of correctly analyzed sounds
        end_timestamp = time.time()
        click.echo('Analyzed dataset with %i sounds (%i sounds correctly analysed), done in %s'
                   % (len(metadata), len(analysis_results),
                      seconds_to_day_hour_minute_second(end_timestamp - start_timestamp)))
        save_to_json(out_file_path, analysis_results, verbose=True)

if __name__ == '__main__':
    analyze_dataset()


from collections import deque
import sys
input = sys.stdin.readline

T = int(input())

for _ in range(T):
    N, M = map(int, input().split())
    queue = deque(list(map(int, sys.stdin.readline().split())))
    count = 0
    while queue:
        best = max(queue)
        front = queue.popleft()
        M -= 1

        if best == front:
            count += 1
            if M < 0:
                print(count)
                break

        else:
            queue.append(front)
            if M < 0 :
                M = len(queue) - 1


# General network architecture for a 1D polynomial Poincare map

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.models import Model

# Conjugacy Network
class Conjugacy(Model):
    def __init__(self,
                        width = 100,
                        size_x = 1,
                        activation = 'selu',
                        degree = 2,
                        steps = 1,
                        numblks_in = 1,
                        numblks_out = 1,
                        coeff1 = 3.5,
                        coeff2 = -3.5,
                        coeff3 = 0,
                        coeff4 = 0.0,
                        coeff5 = 0.0,
                        stretchloss = 0,
                        l1reg = 1e-15,
                        l2reg = 1e-15,
                        **kwargs):
        """
         Create network architecture for 1D polynomial Poincare mappings

         Inputs:
             width -- the number of units in each hidden layer
             size_x -- number of dimensions of the input data x_n
             activation -- activation function used for each hidden layer
             degree -- degree of the latent polynomial g(y)
             steps -- number of iterations in the future the network will use to compute the loss
             numblks_in --  number of hidden layers used to construct the conjugacy h(x)
             numblks_out -- number of hidden layers used to construct the inverse of the conjugacy h^-1(y)
            stretchloss -- add optional loss term that streches latent mapping domain to [0,1]. Set to 1 to include this loss. Default is off
             l1reg = L^1 regularization value
             l2reg = L^2 regularization value
            **kwargs -- additional keyword arguments.
        '"""
        super(Conjugacy, self).__init__()
        self.width = width
        self.size_x = size_x
        self.activation = activation
        self.degree = degree
        self.steps = steps
        self.numblks_in = numblks_in
        self.numblks_out = numblks_out
        self.coeff1 = coeff1
        self.coeff2 = coeff2
        self.coeff3 = coeff3
        self.coeff4 = coeff4
        self.coeff5 = coeff5
        self.stretchloss = stretchloss
        self.l1reg = l1reg
        self.l2reg = l2reg
        self.initializer = tf.keras.initializers.RandomNormal(mean=0.0, stddev=0.1, seed=None)

        # Latent mapping variables
        #        g(y) = c1*y + c2*y^2 + c3*y^3 + c4*y^4 + c5*y^5

        # Minimum degree is 2
        self.c1 = tf.Variable(self.coeff1, trainable = True)
        self.c2 = tf.Variable(self.coeff2, trainable = True)

        # Cubic terms
        if self.degree >= 3:
            self.c3 = tf.Variable(self.coeff3, trainable = True)
        else:
            self.c3 = tf.Variable(0.0, trainable = False)

        # Quartic terms
        if self.degree >= 4:
            self.c4 = tf.Variable(self.coeff4, trainable = True)
        else:
            self.c4 = tf.Variable(0.0, trainable = False)

        # Quintic terms
        if self.degree >= 5:
            self.c5 = tf.Variable(self.coeff5, trainable = True)
        else:
            self.c5 = tf.Variable(0.0, trainable = False)

        # Encoder function (homeomorphism)
        self.encoder = tf.keras.Sequential()

        for n in range(self.numblks_in): #adding more layers
            self.encoder.add(layers.Dense(self.width, activation=self.activation,
                                      kernel_initializer=self.initializer,
                                      kernel_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg),
                                      bias_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg)))

        self.encoder.add(layers.Dense(1, activation=self.activation,
                                  kernel_initializer=self.initializer,
                                  kernel_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg),
                                  bias_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg)))

        # Decoder function (inverse homeomorphism)
        self.decoder = tf.keras.Sequential()

        for n in range(self.numblks_out): #adding more layers
            self.decoder.add(layers.Dense(self.width, activation=self.activation,
                                      kernel_initializer=self.initializer,
                                      kernel_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg),
                                      bias_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg)))

        self.decoder.add(tf.keras.layers.Dense(self.size_x, activation= self.activation,
                                           kernel_initializer=self.initializer,
                                           kernel_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg),
                                           bias_regularizer=tf.keras.regularizers.L1L2(self.l1reg, self.l2reg)))

    def call(self, x):
        encoded = self.encoder(x[0])
        encoded_p1 = self.c1*encoded + self.c2*tf.square(encoded) + self.c3*tf.math.multiply(tf.square(encoded),encoded) + self.c4*tf.math.multiply(tf.square(encoded),tf.square(encoded)) + self.c5*tf.math.multiply(tf.math.multiply(tf.square(encoded),tf.square(encoded)),encoded)
        decoded = self.decoder(encoded_p1)

        # Conjugacy loss
        x_recon = self.decoder(encoded)
        self.add_loss(tf.reduce_mean(tf.math.square(x[0] - x_recon)))

        # Build stepping loss components
        yn = encoded
        for s in range(self.steps):
            ynp1 = self.encoder(x[s+1])

            # Iteration loss in y
            y_step = self.c1*yn + self.c2*tf.square(yn) + self.c3*tf.math.multiply(tf.square(yn),yn) + self.c4*tf.math.multiply(tf.square(yn),tf.square(yn)) + self.c5*tf.math.multiply(tf.math.multiply(tf.square(yn),tf.square(yn)),yn)
            self.add_loss((tf.reduce_mean(tf.math.square(ynp1 - y_step)))/self.steps)

            # Iteration loss in x
            xnp1 = self.decoder(y_step)
            self.add_loss((tf.reduce_mean(tf.math.square(x[s+1] - xnp1)))/self.steps)

            yn = y_step

        # Scale encoded data to [0,1] interval
        if self.stretchloss == 1:
            self.add_loss(0.25*(1 - tf.reduce_max(encoded))**2)
            self.add_loss(0.25*(tf.reduce_min(encoded))**2)
            self.add_loss(0.25*(1 - tf.reduce_max(encoded_p1))**2)
            self.add_loss(0.25*(tf.reduce_min(encoded_p1))**2)

        return decoded


from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import requests
from bs4 import BeautifulSoup
import time

# Wpisz tutaj link
URL = 'https://www.fly4free.pl/tanie-loty/loty/'

headers = {
    "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36'
}

current_id = ""

def check_price():
    global current_id  # Declare current_id as a global variable
    page = requests.get(URL, headers=headers)
    soup = BeautifulSoup(page.content, 'html.parser')
    found_id = soup.find_all("a", {"class": "item__details"})[0]['href']
    print(found_id)
    if current_id != found_id:
        print("New id!")
        current_id = found_id
        message = f"Nowe ogłoszenie {found_id}"
        #Wpisz tutaj telegram token
        TOKEN = ""
        #Wpisz tutaj telegram chat id token
        chat_id = ""
        chat_url = f"https://api.telegram.org/bot{TOKEN}/sendMessage?chat_id={chat_id}&text={message}"
        print(requests.get(chat_url).json())

    print(current_id)

while True:
    check_price()
    time.sleep(60)

#Przydatne linki
#https://www.siteguarding.com/en/how-to-get-telegram-bot-api-token


# -*- coding: utf-8 -*-
"""
Created on Fri Feb  3 09:43:07 2023

@author: n.patsalidis
"""
import sys
sys.path.insert(0, '/Users/n.patsalidis/Desktop/PHD/REPOSITORIES/MDanalysis')
import numpy as np
import md_analysis as mda
obj = mda.Analysis('../gro/alu.gro','../itp/alu_to.itp')
obj.read_file()
maxdist = 0.2
type1='Alt'
type2='O'
coordination_sub = obj.calc_atomic_coordination(maxdist,type1,type2)
coordination_sub.update(obj.calc_atomic_coordination(0.26,['Alo','Alt'], 'O'))
t = coordination_sub['Alt-O']
o = coordination_sub['Alo_Alt-O']
xt = np.count_nonzero(t==3)*100/t.shape[0]
xo =  np.count_nonzero(o==6)*100/o.shape[0]
print('COORDINATION ACCURACY: Alt--> {:4.3f} %, Alo --> {:4.3f} %'.format(xt,xo))


# Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0.

# Assume the environment does not allow you to store 64-bit integers (signed or unsigned).

#

# Example 1:

# Input: x = 123
# Output: 321
# Example 2:

# Input: x = -123
# Output: -321
# Example 3:

# Input: x = 120
# Output: 21

class Solution:
    def reverse(self, x: int) -> int:
        s = str(x)
        res = ''
        for i in range(len(s)-1, -1, -1):
            res += s[i]
        if x < 0:
            res = '-'+ res[:len(res)-1]
            return int(res) if int(res) >= -pow(2, 31) else 0
        else:
            return int(res) if int(res) <= pow(2, 31)-1 else 0

print(Solution().reverse(-1234567))


from tools.calculator import Calculator
from tools.error_handling import TransactionFailedError, CustomerNotFoundError
from tools.error_handling import DeleteTransactionFailedError,GetTransactionsError
from tools.error_handling import TransactionNotFoundError
from tools.error_handling import UpdateTransactionFailed

class ManageTransactions:
    def __init__(self, sql_contoller:object) -> None:
        """
        Args:
        -----
            sql_controller(SqlDB): The sql object that controll the db
        """
        self.sql_controller = sql_contoller

    def create_transaction(self,
                                client_id_sender:str,
                                client_id_getter:str,
                                total_transaction:float):
        """
        This method will create a new transaction and it will do all
        the calculation for converting the currency and add/sub from
        the totals.

        Args:
        -----
            client_id_sender(str): The customer id of the sender
            client_id_getter(str): The customer id of the getter
            total_transaction(float): The total transaction
        """
        try:
            customer_sender , customer_getter = self.get_customers(client_id_sender, client_id_getter)
            customer_sender_total, customer_getter_total = self.get_customer_total(
                                                            customer_sender,
                                                            customer_getter)
            current_currency, converte_currency = self.get_customers_currency(customer_sender,customer_getter)
            cal = Calculator(
                                customer_sender_total,
                                customer_getter_total,
                                total_transaction,
                                current_currency,
                                converte_currency)

            self.sql_controller.create_transaction(
                                                    client_id_sender,
                                                    client_id_getter,
                                                    cal.sub_total_sender(),
                                                    cal.add_total_getter(),
                                                    total_transaction,
                                                    current_currency,
                                                    cal.convert_money(),
                                                    converte_currency)
        except TransactionFailedError:
            raise TransactionFailedError("Failed to create transaction")
        except CustomerNotFoundError:
             raise CustomerNotFoundError("The customers are not found")

    def update_transaction(self, transaction_id:int, total_transaction:float):
        """
        This method will change the total transaction and it will reset
        to last totals and calculate again the new totals.

        Args:
        -----
            transaction_id(int): The id of the transaction
            total_transaction(float): The new total transaction
        """
        try:
            trans = self.sql_controller.get_transaction(transaction_id)
            customer_sender_total, customer_getter_total = self.reset_transaction(
                                                            trans["user_id_transac"],
                                                            trans["user_id_get"],
                                                            trans["total_before_convert"],
                                                            trans["currency_user_transac"],
                                                            trans["currency_user_get"])
            cal = Calculator(
                            customer_sender_total,
                            customer_getter_total,
                            total_transaction,
                            trans["currency_user_transac"],
                            trans["currency_user_get"])

            self.sql_controller.update_transaction(
                                                trans["user_id_transac"],
                                                trans["user_id_get"],
                                                cal.sub_total_sender(),
                                                cal.add_total_getter(),
                                                transaction_id,
                                                total_transaction,
                                                trans["currency_user_transac"],
                                                cal.convert_money(),
                                                trans["currency_user_get"])
        except UpdateTransactionFailed:
            raise UpdateTransactionFailed(f"failed to update the transaction \
                                            {transaction_id}")
        except TransactionNotFoundError:
            raise TransactionNotFoundError(f"can't find the transaction \
                                            {transaction_id}")
        except CustomerNotFoundError:
            raise UpdateTransactionFailed(f"failed to update the transaction \
                                            {transaction_id}")

    def delete_transaction(self, transaction_id:int):
        """
        This method will delete the transaction and reset the totals.

        Args:
        -----
            transaction_id(int): The transaction id
        """
        try:
            trans = self.sql_controller.get_transaction(transaction_id)
            customer_sender_total, customer_getter_total = self.reset_transaction(
                                                            trans["user_id_transac"],
                                                            trans["user_id_get"],
                                                            trans["total_before_convert"],
                                                            trans["currency_user_transac"],
                                                            trans["currency_user_get"])

            self.sql_controller.delete_transaction( transaction_id,
                                                    trans["user_id_transac"],
                                                    trans["user_id_get"],
                                                    customer_sender_total,
                                                    customer_getter_total)
        except DeleteTransactionFailedError:
            raise DeleteTransactionFailedError("Unable to delete transaction")
        except TransactionNotFoundError:
            raise TransactionNotFoundError(f"Transaction not found {transaction_id}")
        except CustomerNotFoundError:
            raise DeleteTransactionFailedError("Unable to delete transaction")

    def get_all_transaction(self) -> list:
        """
        This method will return a list of dicts of transactions

        Return:
        -------
            Return list of dicts of transactions
        """
        try:
            transactions  = []
            for transaction in self.sql_controller.get_transactions():
                transactions.append({   "id":transaction.id,
                                        "user_id_transac":transaction.user_id_transac,
                                        "user_id_get":transaction.user_id_get,
                                        "total_before_convert":transaction.total_before_convert,
                                        "currency_user_transac":transaction.currency_user_transac,
                                        "total_after_convert":transaction.total_after_convert,
                                        "currency_user_get":transaction.currency_user_get,
                                        "date":transaction.date})
            return transactions
        except GetTransactionsError:
            raise GetTransactionsError("Can't get the transaction")

    def reset_transaction(self,client_id_sender:str,
                                            client_id_getter:str,
                                            total_transaction:float,
                                            current_currency:str,
                                            converte_currency:str) -> tuple:
        """
        This method will reset the total of the two customers and it
        will return there last totals.

        Return:
        -------
            Return a tuple of the last totals
        """
        try:
            customer_sender , customer_getter = self.get_customers(client_id_sender, client_id_getter)
            client_sender_total, client_getter_total = self.get_customer_total(
                                                            customer_sender,
                                                            customer_getter)
            cal = Calculator(
                                client_sender_total,
                                client_getter_total,
                                total_transaction,
                                current_currency,
                                converte_currency)

            return (cal.add_total_sender(), cal.sub_total_getter())
        except CustomerNotFoundError:
            raise CustomerNotFoundError(f"Can't find the customers")

    def get_customer_total(self, customer_sender, customer_getter)->tuple:
        """
        This method will retrun the totals of the two customers

        Return:
        -------
            Return the total of the two customers
        """
        try:

            customer_sender_total = customer_sender["total_price"]
            customer_getter_total = customer_getter["total_price"]
            return (customer_sender_total, customer_getter_total)
        except CustomerNotFoundError:
            raise CustomerNotFoundError(f"Can't find the customers ids")

    def get_customers_currency(self, customer_sender, customer_getter):
        """
        This method will return thr customers currency

        Return:
        -------
            Return a tuple of the two currency of the customers
        """
        try:

            customer_sender_currency = customer_sender["currency"]
            customer_getter_currency = customer_getter["currency"]
            return (customer_sender_currency, customer_getter_currency)
        except CustomerNotFoundError:
            raise CustomerNotFoundError(f"Can't find the customers ids")

    def get_customers(self,client_id_sender, client_id_getter):
        """
        This method will return the two customers data

        Return:
        -------
            Return a tuple of the two customers
        """
        try:
            customer_sender = self.sql_controller.get_customer(client_id_sender)
            customer_getter = self.sql_controller.get_customer(client_id_getter)
            return (customer_sender, customer_getter)
        except CustomerNotFoundError:
            raise CustomerNotFoundError(f"Can't find the customers ids")


import cv2
import numpy as np
import math

def custom_gaussian_blur(image, kernel_size=(15, 15), sigma=0):
    # Créer un noyau gaussien
    kernel_x = cv2.getGaussianKernel(kernel_size[0], sigma)
    kernel_y = cv2.getGaussianKernel(kernel_size[1], sigma)

    # Calculer le produit tensoriel des noyaux pour obtenir un noyau 2D
    kernel = np.outer(kernel_x, kernel_y)

    # Appliquer la convolution avec le noyau gaussien
    blurred_image = cv2.filter2D(image, -1, kernel)

    return blurred_image

def custom_blur(image, kernel_size=(5, 5)):
    # Créer un noyau de moyenne
    kernel = np.ones(kernel_size, np.float32) / (kernel_size[0] * kernel_size[1])

    # Appliquer la convolution avec le noyau de moyenne
    blurred_image = cv2.filter2D(image, -1, kernel)

    return blurred_image

def custom_median_blur(image, ksize=5):
    # Copier l'image pour ne pas modifier l'originale
    result_image = np.copy(image)

    # Obtenez les dimensions de l'image
    rows, cols, channels = image.shape

    # Demi-taille du noyau
    ksize_half = ksize // 2

    # Parcourir chaque pixel de l'image
    for i in range(ksize_half, rows - ksize_half):
        for j in range(ksize_half, cols - ksize_half):
            # Récupérer la fenêtre du noyau
            window = image[i - ksize_half:i + ksize_half + 1, j - ksize_half:j + ksize_half + 1]

            # Appliquer le filtre médian sur chaque canal
            for c in range(channels):
                result_image[i, j, c] = np.median(window[:, :, c])

    return result_image

def gaussian(x, sigma):
    return np.exp(-x**2 / (2 * sigma**2))

def color_similarity(window, center, sigma_color):
    return np.exp(-np.sum((window - center) ** 2, axis=2) / (2 * sigma_color ** 2))

def spatial_similarity(i, j, center, d, sigma_space,rows,cols):
    row_indices = np.arange(max(0, i - d), min(rows, i + d + 1))
    col_indices = np.arange(max(0, j - d), min(cols, j + d + 1))

    spatial_kernel = np.exp(-((row_indices - i) ** 2 + (col_indices - j) ** 2) / (2 * sigma_space ** 2))
    return spatial_kernel

def custom_aloys_bilateral(image, d=9, color=20, space=20):
    h, w, _ = image.shape
    out = np.zeros_like(image, dtype=np.uint8)

    for row in range(h):
        for col in range(w):
            norm = 0.0
            filtered = np.zeros(3, dtype=np.float32)

            for dy in range(-d//2, d//2):
                for dx in range(-d//2, d//2):
                    x, y = col + dx, row + dy
                    if x < 0 or x >= w or y < 0 or y >= h:
                        continue

                    px1 = image[row, col]
                    px2 = image[y, x]

                    # Utiliser les canaux individuels pour calculer la différence d'intensité
                    intensityDistance = np.sum(np.abs(px1 - px2))

                    intensityWeight = gaussian(intensityDistance, color)
                    spatialWeight = gaussian(math.sqrt(dy**2 + dx**2), space)

                    weight = spatialWeight * intensityWeight
                    norm += weight
                    filtered += weight * image[y, x]

            out[row, col] = (filtered / norm).astype(np.uint8)

    return out