import distutils

from distutils.core import setup, Extension

extension = Extension("libschicmodule",
                      ["libschicmodule.c"],
                      extra_compile_args = ["-O0", "-g3"])
extension.undef_macros.append("NDEBUG")

setup(name="libschicmodule", version="0.1",
      ext_modules = [ extension ])

#---------------------------------------------------------------------------


from runDatasets import *
import argparse
import yaml

if __name__ == '__main__':

    np.seterr(invalid='ignore')  # suppress all numpy warnings

    parser = argparse.ArgumentParser(description='Collaborative Bandits')
    parser.add_argument('--alg', dest='alg', help='Select a specific algorithm, could be colin or factor')
    parser.add_argument('--data', dest='data', help='Select a specific dataset, could only be movielens for now')
    args = parser.parse_args()

    algName = str(args.alg)  # should be colin or factor
    if not (algName == 'colin' or algName == 'factor'):
        print('Choose colin or factor as the alg. Exiting...')
        exit()

    datasetName = str(args.data)  # should be movielens
    if not datasetName == 'movielens':  # or datasetName == 'yahoo'
        print('Choose movielens as the dataset. Exiting...')
        exit()

    ymlFilename = 'ML_config.yaml'
    if datasetName == 'yahoo':
        ymlFilename = 'yahoo_config.yaml'

    with open(ymlFilename, 'r') as ymlfile:
        dataInfo = yaml.load(ymlfile, Loader=yaml.FullLoader)

    if datasetName == 'movielens':
        # for movielens
        # top_users: select top users with the most ratings
        # top_movies: select top most rated movies among top_users with the most ratings
        # embeddingSize: size of the embedding for the CF

        path_input = dataInfo['path_input']
        path_output = path_input + "/results"
        dim_contexts = dataInfo['itemFeatureDim']

        clusterNum = dataInfo['clusterNum'] if 'clusterNum' in dataInfo else 100
        top_users = dataInfo['top_users'] if 'top_users' in dataInfo else 1000000
        top_movies = dataInfo['top_movies'] if 'top_movies' in dataInfo else 50
        embeddingSize = dataInfo['embeddingSize'] if 'embeddingSize' in dataInfo else 50
        sparsity = min(dataInfo['sparsity'], clusterNum) if 'sparsity' in dataInfo else clusterNum

        stopAfter = dataInfo['stopAfter'] if 'stopAfter' in dataInfo else 10000
        recordEvery = dataInfo['recordEvery'] if 'recordEvery' in dataInfo else 100
        skip = dataInfo['skip'] if 'skip' in dataInfo else 0
        batchUpdates = dataInfo['batchUpdates'] if 'batchUpdates' in dataInfo else 1
        initBanditParams = dataInfo['initBanditParams'] if 'initBanditParams' in dataInfo else 'zeros'
        runCF = dataInfo['run_CF'] if 'run_CF' in dataInfo else True
        runKmeans = dataInfo['run_Kmeans'] if 'run_Kmeans' in dataInfo else True

        warmStartPaths = dataInfo['warmStart_input'] if 'warmStart_input' in dataInfo else ""
        iFD = dataInfo['itemFeatureDim'] if 'itemFeatureDim' in dataInfo else -1
        lFD = dataInfo['latent_dim'] if 'latent_dim' in dataInfo else -1

        lambd = dataInfo['lambda_'] if 'lambda_' in dataInfo else -1

        alpha = dataInfo['alpha'] if 'alpha' in dataInfo else 0.5 * (algName == 'colin') + 0.375 * (algName == 'factor')
        alpha2 = dataInfo['alpha2'] if 'alpha2' in dataInfo else -1

        runMovieLens(algName, path_input, path_output, warmStartPaths, iFD, lFD, lambd, initBanditParams, alpha, alpha2,
                     runCF, runKmeans, top_users=top_users, numClust=clusterNum, sparsity=sparsity,
                     top_movies=top_movies, embeddingSize=embeddingSize, stopAfter=stopAfter,
                     recordEvery=recordEvery, skip=skip, batchUpdates=batchUpdates)


import requests
import pandas as pd
import numpy as np
from bs4 import BeautifulSoup

def getAugmentTables(url):
    html = requests.get(url).content
    df_list = pd.read_html(html)

    merged = {}
    for df in df_list:
        if 'Name' in df and 'Effects' in df:
            subset_df = df.set_index('Name')
            #subset_df['Weapon Sources'] = subset_df['Weapon Sources'].apply(lambda x: str(x).replace('\n',','))
            #subset_df['Weapon Sources'] = subset_df['Weapon Sources'].apply(lambda x: str(x).replace('\br',','))
            dict = subset_df.to_dict(orient='index')

            merged = {**merged, **dict}
            #print(subset_df)
    keys = merged.keys()

    print(merged['Might V']['Weapon Sources'])

def main():
    getAugmentTables('https://pso2na.arks-visiphone.com/wiki/Augment_Factors')
    """
    for i in SAFLinks:
        print(i)
    """
main()


"""
---------------------------------------------------------------------------------------------------
	Author
	    Francisco Rosal 18676
---------------------------------------------------------------------------------------------------
Basado en:
    https://medium.com/@alcantararosas/k-means-programando-el-algoritmo-desde-cero-en-python-f633b3a1c125
"""

import pandas
import seaborn
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import RandomForestClassifier

## Data Analysis
data = pandas.read_csv('advertising.csv')
data.head()
data.info()

## Exploratory Data Analysis
print("Exploratory Data Analysis")
# Histograma Edad.
plt.hist(data.Age)
plt.show()

# Crear un jointplot que muestre la relación de la edad vs los ingresos del área.
seaborn.jointplot(data = data, x = 'Age', y = 'Area Income')
plt.show()

# Crear un jointplot que muestre la distribución k de la relación de la edad vs el tiempo que diario empleado.
seaborn.jointplot(data = data, x = 'Age', y = 'Daily Time Spent on Site', color = 'red', kind = 'kde')
plt.show()

# Crear un jointplot del Daily Time Spent on Site vs. Daily Internet Usage.
seaborn.jointplot(data = data, x = 'Daily Time Spent on Site', y = 'Daily Internet Usage')
plt.show()

# Finalmente, crear un pairplot que separe las poblaciones de 'Clicked on Ad'.
seaborn.pairplot(data = data, hue = 'Clicked on Ad', palette = 'bwr')
plt.show()

## Logistic Regression
print("Logistic Regression")
X = data[['Daily Time Spent on Site', 'Age', 'Area Income','Daily Internet Usage', 'Male']]
y = data['Clicked on Ad']

# Usar train_test_split para generar X_train, X_test, y_train y y_test con un 33% en el split para split.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.33)

# Entrene y ajuste un modelo de regresión logística en el conjunto de entrenamiento.
clf = LogisticRegression(random_state = 0).fit(X_train, y_train)

## Predictions and Evaluations
print("Predictions and Evaluations")
clf.predict(X_test)

# Crear un reporte de classificación (classification_report) para el modelo.
print(classification_report(y_test, clf.predict(X_test)))

# Imprima el confussion matrix de la clasificación.
confusion_matrix(y_test, clf.predict(X_test))

# Aplique la clasificación utilizando Random Forest y compare los resultados.
rfc = RandomForestClassifier(max_depth = 2, random_state = 0).fit(X_train, y_train)
rfc.predict(X_test)
print(classification_report(y_test, rfc.predict(X_test)))
confusion_matrix(y_test, rfc.predict(X_test))


"""
З множини чисел [1..n] виділити підмножину досконалих чисел (число
називається досконалим якщо воно дорівнює сумі своїх власних дільників,
наприклад 6=3+2+1)
"""

def FindTrueOrFalse(N):
    lists = []
    for i in range(1,N // 2 + 1):
        if N % i == 0:
            lists.append(i)
    S = 0
    for i in lists:
        S += i
    return S == N

N = int(input("Введите N: "))
A = {i for i in range(N)}
A1 = set()
for i in A:
    if FindTrueOrFalse(i):
        A1.add(i)
print(A1)


import sys

import io_main

sys.path.append('../display')
import colors as dclr

sys.path.append('../handler')
import writer as hwriter

def write():
    question = "Do you want to add an entry? [y/n]"
    entries = list()

    while True:
           choice = io_main.query_yes_no(question)

           if choice == "y":
               entry = input()
               entries.append(list(entry))
           else:
               return

    hwriter.write('list.csv', entries)


import os
path1 = os.chdir("/path/images/folder/")
#First we should give path of images
i = 0

for file1 in os.listdir(path1):

    new_file_name1 = "new{}.jpg".format(i)
#new{}.jpg means it gives names new1.jpg,new2.jpg,...
    os.rename(file1, new_file_name1)
#rename the previous name to newname
    i = i+1


# Agenda:
    # Create icon
    # Set a title and
    # fill with background color

import pygame

# Intialize the pygame
pygame.init()

# create the screen
screen = pygame.display.set_mode((800, 600))

# Title (aka Caption) and Icon #   <<<<<<<<<< ====================
pygame.display.set_caption("Space Invader")
icon = pygame.image.load('ufo.png') # https://www.flaticon.com/search?word=ufo
pygame.display.set_icon(icon)

# Game Loop
running = True
while running:

    # completely fill the surface object with white colour
    # screen.fill(white)

    # RGB = Red, Green, Blue #   <<<<<<<<<< ====================
    # screen.fill((0, 0, 0))
    # screen.fill((255, 0, 0))
    # screen.fill((0, 255, 0))
    # screen.fill((0, 0, 255))
    screen.fill((255,255,255))

    # update the screen #   <<<<<<<<<< ====================
    pygame.display.update()

    # Capture and check events one by one
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


import pygame

class Settings:

	def __init__(self):

		self.SCREEN_WIDTH, self.SCREEN_HEIGHT = 1400, 1000

		self.BLACK = (0, 0, 0)
		self.WHITE = (255, 255, 255)
		self.BLUE = (61, 183, 228)
		self.YELLOW = (253, 184, 19)
		self.ORANGE = (255, 136, 73)
		self.GREEN = (105, 190, 40)

		self.BG_COLOUR = self.BLACK

		self.ICON = pygame.image.load('images/icon.png')
		self.FONT_SIZE = 30

		self.FPS = 1000

		self.INITIAL_X_VEL = 5
		self.INITIAL_Y_VEL = 0
		self.RUNGE_KUTTA_DT = 0.2

		self.STATIONARY_MASS = 1e4
		self.STATIONARY_RAD = 20
		self.MOVING_MASS = 1
		self.GRAV_CONST = 1

		self.TRAIL_SPACING = 15
		self.TRAIL_LENGTH = 100
		self.TRAIL_COLOUR = self.WHITE

		# Mass selector
		self.LARGE_R = 25
		self.MED_R = 20
		self.SMALL_R = 15
		self.SPACING = 20
		self.SELECTOR_CIRC_W = 4
		self.MASS_SCALING = 0.4
		self.IMAGE_SCALING = 0.65


import numpy as np
import scipy as sc
import matplotlib.pyplot as plt

funcion = lambda th :   np.sin( 1/2 * th[0]**2  + 1/4 * th[1]**2 + 3) * np.cos(2*th[0] + 1 - np.e**th[1])    # declaracion de funcion anonima  th = vector de parametros, es la variable de entrada
                      # np.sin( 1/2 * x**2  + 1/4 * y**2 + 3) * np.cos(2*x + 1 - np.e**y) es funcion a optimizar
# print funcion([5,3])

resolucion = 100
x = np.linspace(-2,2 ,resolucion) ; y = np.linspace(-2,2 ,resolucion)     # se tiene un amatriz de 100 * de resolucion

z = np.zeros((resolucion,resolucion))

# asignar valores... evlauar funcion
for iX, X in enumerate(x) :
    for iY, Y in enumerate(y):
        z[iY , iX] = funcion([X,Y])        # filas = y, columnas
# enumerate recorre el elemento y retorna indice, valor el indice se guarda en ix y el valor se guarda en X

plt.contourf(x,y,z,100)                    # x y y son los linspaces
plt.colorbar()

# tecnica de optimizacion del gradiente decendente

punto = np.random.rand(2) * 4 - 2      # este es pto inicial  np.random.rand(2)   valores entre 0 y 1;  np.random.rand(2) * 4 - 2 vlaores entre -2 y 2 conocido como theta
plt.plot( punto[0], punto[1],"ro", C ="red" , label='inicio')

T = np.copy(punto)             # copia evlauada con el punto inicial

# derivadas parciales obtiene la derivada en cadae eje del vector de parametros

learningRate = 0.1               # pequeno = muchos pasos poca distancia
delta = 0.0001                    # delta = H
grad = np.zeros(2)

for _ in range(100):              # iteracion

    for iT, th in enumerate(punto):  # calculo por medio d eminimas diferencias

        T = np.copy(punto)     # se actualiza con el nuevo valor del punt
        T[iT] = T[iT] + delta  # el primer componente del punto  se le hace un pequeno incremento

        derivada = (funcion(T) - funcion(
            punto)) / delta  # derivada(es un ratio) es la funcion evlauada en el incremento respecto al punto inicial e analisis

        grad[iT] = derivada

    punto = punto - grad * learningRate  # el valor del punto es actualizado
    #print funcion(punto)

    # visualizar el recorrido del punto cada detemirnada iteraciones
    if _% 4 == 0 :
        plt.plot(punto[0], punto[1], ".", c ="green" )  # marca el camino recorrido

plt.plot(punto[0], punto[1], "o", c ="white", label='final')
plt.legend()
plt.show()


#!/usr/bin/python3
# Creator: Thiemo Schuff, thiemo@schuff.eu
# Source: https://github.com/Starwhooper/RPi-ESP8266-temphumi-collector
# get awesomefonts from here: https://fontawesome.com/v5.15/icons/cloud-sun?style=solid
# Weather: https://openweathermap.org/api

try: from getmac import get_mac_address
except:
 print('python3 modul getmac is missed')
 print('please do follow command to get it:')
 print('sudo apt-get install python3-pip && sudo pip3 install getmac')
 exit()

try: import json
except:
 print('python3 modul json is missed')
 print('please do follow command to get it:')
 print('sudo apt-get install python3-pip && sudo pip3 install json')
 exit()

import datetime
import os
import re
import requests
import socket
import sys
import time
import urllib.request

ip = str((([ip for ip in socket.gethostbyname_ex(socket.gethostname())[2] if not ip.startswith("127.")] or [[(s.connect(("8.8.8.8", 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1]]) + ["no IP found"])[0])
ipareaparts = ip.split('.')

parent_dir = os.path.split(os.path.abspath(__file__))[0]

##########import config.json
try:
 with open(parent_dir + '/config.json','r') as file: cf = json.loads(file.read())
except: sys.exit('exit: The configuration file ' + parent_dir + '/config.json does not exist or has incorrect content. Please rename the file config.json.example to config.json and change the content as required')

##########check environment
try: htmlfile = open(cf["htmloutput"]["file"],'w')
except: print('file ' + cf["htmloutput"]["file"] + ' not aviable or permission missed')

try: cf["openweather"]["apikey"]
except: sys.exit('exit: no api key in configuration file ' + parent_dir + '/config.json found')

try: os.path.isdir(parent_dir + '/cache')
except:
 try:
  path = os.path.join(parent_dir, 'cache')
  os.mkdir(path)
 except: print('exit, folder ' + parent_dir + '/cache cloud not created')

##########Functions
def calc_abs_humi(relhumi,temp): return(round(10 ** 5 * 18.016 / 8314.3 * relhumi / 100 * 6.1078 * 10**( ( 7.5 * temp ) / ( 237.3 + temp ) ) / ( temp + 273.15 )))
def return_date(): return(datetime.date.today().strftime('%d. %b. \'%y'))
def return_time(): return(time.strftime('%H:%M', time.localtime()))

def return_todo(relhumi,abshumi,absoutdoorhumi,sensoroptions,device):
 sendmsg = False
 todo = ''
 shorttodo = ''
 if 'nw;' in sensoroptions:
  todo += cf["htmloutput"]["string_nowindow"]
 else:
  if relhumi < cf["limits"]["relhumi"]["min"]:
   todo += cf["htmloutput"]["string_tolesshumi"]
   if absoutdoorhumi < abshumi:
    todo += cf["htmloutput"]["string_tolesshumi_close"]
    shorttodo = cf["htmloutput"]["string_close"]
   if absoutdoorhumi > abshumi:
    todo += cf["htmloutput"]["string_tolesshumi_open"]
    shorttodo = cf["htmloutput"]["string_open"]
    sendmsg = True
  if relhumi >= cf["limits"]["relhumi"]["min"] and relhumi <= cf["limits"]["relhumi"]["max"]: todo += cf["htmloutput"]["string_righthumi"]
  if relhumi > cf["limits"]["relhumi"]["max"]:
   todo += cf["htmloutput"]["string_tomuchhumi"]
   if absoutdoorhumi < abshumi:
    todo += cf["htmloutput"]["string_tomuchhumi_open"]
    shorttodo = cf["htmloutput"]["string_open"]
    sendmsg = True
   if absoutdoorhumi > abshumi:
    todo += cf["htmloutput"]["string_tomuchhumi_close"]
    shorttodo = cf["htmloutput"]["string_close"]
  if sendmsg == True:
   pushovermessage("" + device + " " + shorttodo[0:1].lower() + shorttodo[1:] + ": r=" + str(relhumi) + "% " + remove_tags(todo))
#   print(todo)
 return(shorttodo,todo)

def is_number(s):
 try:
  float(s)
  return True
 except ValueError:
   return False

def tempdetails(shortmac,temp):
 global cf
 output = ''
 if shortmac in cf['device']:
  if 'sensor' in cf['device'][shortmac]:
   output += '

'
   if cf['device'][shortmac]['sensor'] == 'dht11': output += str(round(temp - 2,2)) + ' - ' + str(round(temp + 2,2))
   elif cf['device'][shortmac]['sensor'] == 'dht22': output += str(round(temp - 0.5,2)) + ' - ' + str(round(temp + 0.5,2))
   elif cf['device'][shortmac]['sensor'] == 'sht30': output += str(round(temp - 0.2,2)) + ' - ' + str(round(temp + 0.2,2))
   if cf['device'][shortmac]['sensor'] == 'dht11' and (temp <= 0 or temp >= 60): output += cf["htmloutput"]["string_outside_measuring_range"]
   elif cf['device'][shortmac]['sensor'] == 'dht22' and (temp <= -40 or temp >= 80): output += cf["htmloutput"]["string_outside_measuring_range"]
   output += '
'
 return(output)

def relhumidetails(shortmac,relhumi):
 global cf
 output = ''
 if shortmac in cf['device']:
  if 'sensor' in cf['device'][shortmac]:
   output += '

'
   if cf['device'][shortmac]['sensor'] == 'dht11': output += str(round(relhumi - 5,2)) + ' - ' + str(round(relhumi + 5,2))
   elif cf['device'][shortmac]['sensor'] == 'dht22': output += str(round(relhumi - 2,2)) + ' - ' + str(round(relhumi + 2,2))
   elif cf['device'][shortmac]['sensor'] == 'sht30': output += str(round(relhumi - 2,2)) + ' - ' + str(round(relhumi + 2,2))
   if cf['device'][shortmac]['sensor'] == 'dht11' and (relhumi <= 20 or relhumi >= 90): output += cf["htmloutput"]["string_outside_measuring_range"]
   elif cf['device'][shortmac]['sensor'] == 'dht22' and (relhumi <= 0 or relhumi >= 100): output += cf["htmloutput"]["string_outside_measuring_range"]
   output += '
'
 return(output)

if cf["pushover"]["notification"] == "on":
 import http.client, urllib

 def pushovermessage(message):
#  import requests
  r = requests.post("https://api.pushover.net/1/messages.json", data = {
   "token": cf["pushover"]["apikey"],
   "user": cf["pushover"]["userkey"],
   "html": 1,
   "priority": -2,
   "message": message
   })

 def remove_tags(text):
#  import re
  TAG_RE = re.compile(r'<[^>]+>')
  return TAG_RE.sub('', text)

##########import weather json
ow_remotefile = "http://api.openweathermap.org/data/2.5/weather?" + cf["openweather"]["location"] + "&appid=" + cf["openweather"]["apikey"] + "&lang=de&units=metric"
ow_localfile = parent_dir + '/cache/openweathermap.json'

try: owage = os.path.getmtime(ow_localfile)
except: owage = 0

if owage + int(cf["openweather"]["maxageinminutes"]) < time.time():
 from urllib.request import urlopen
 urllib.request.urlretrieve(ow_remotefile, ow_localfile)

openweatherjson = open(ow_localfile,)
data_weather = json.loads(openweatherjson.read())
openweatherjson.close()

outdoortemp = float(data_weather["main"]["temp"])
outdoorhumi = float(data_weather["main"]["humidity"])
outdoorpres = float(data_weather["main"]["pressure"])
outdoorhuml = calc_abs_humi(outdoorhumi,outdoortemp)
ow_date = datetime.datetime.fromtimestamp(data_weather["dt"])

misseddevices = []
for device in cf['device']:
 misseddevices.append(device)

##########generate html output
htmlstring = '<!DOCTYPE HTML>\n'
htmlstring += '\n'
htmlstring += '<meta charset="utf-8"/>\n'
htmlstring += '<meta name="viewport" content="width=device-width, initial-scale=1">\n'
htmlstring += '<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.2/css/all.css" integrity="sha384-fnmOCqbTlWIlj8LyTjo7mOUStjsKC4pOpQbqyi7RrhN7udi9RwhKkMHpvLbHG9Sr" crossorigin="anonymous">\n'
try:
 htmlstring += '\n'
except: htmlstring += '\n'
htmlstring += '\n'
htmlstring += '\n'
htmlstring += '
 Weather

' + return_date() + ' ' + return_time() + '
\n'
htmlstring += '
'
htmlstring += '
Sensor	Gerät		rel. Feuchte	abs. Feuchte	Aufgabe
'
htmlstring += '
 OpenWeather	Internet	' + str(round(outdoortemp)) + '°C	' + str(round(outdoorhumi)) + '%	' + str(round(outdoorhuml)) + 'g/㎥
That\'s the Internet at ' + ow_date.strftime("%d. %b. %H:%M") + '

'

for ipchangepart in range(0,255):
 ip = ipareaparts[0] + '.' + ipareaparts[1] + '.' + ipareaparts[2] + '.' + str(ipchangepart)
 mac = get_mac_address(ip=ip)
 if mac != "00:00:00:00:00:00":
  if len(str(mac)) == 17:
   mv_remotefile = "http://macvendors.co/api/" + mac
   mv_localfile = parent_dir + '/cache/' + mac + '.json'
   try:
    try: os.path.getmtime(mv_localfile)
    except: urllib.request.urlretrieve(mv_remotefile, mv_localfile)
    macjson = open(mv_localfile,)
    data_mac = json.loads(macjson.read())
    macjson.close()
    company = data_mac['result']['company'];
   except:
    print('unknown vendor: ' + mac)
    try: os.remove(mv_localfile)
    except: print('no cached file to delete: ' + mv_localfile)

   if company == 'Espressif Inc.':
    shortmac = str(mac)[9:]
    try: sensoroptions = cf['device'][shortmac]['options']
    except: sensoroptions = ''
    if 'i;' in sensoroptions:
     if shortmac in misseddevices:
      misseddevices.remove(shortmac)
     continue

    htmlstringonedevice = ''

    try:
     temp = urllib.request.urlopen('http://' + ip + '/temperature').read().decode("UTF-8")
     relhumi = urllib.request.urlopen('http://' + ip + '/humidity').read().decode("UTF-8")
    except:
     temp = 'error'
     relhumi = 'error'
     print("Device " + ip + " known on DHCP, but provide no information about temperatur or humidity")

    if is_number(relhumi) and is_number(temp):
     try: sensorlabel = cf['device'][shortmac]['label']
     except: sensorlabel = 'unknown'
     temp = float(temp)
     relhumi = float(relhumi)
     abshumi = calc_abs_humi(relhumi,temp)
#     try: sensoroptions = cf['device'][shortmac]['options']
#     except: sensoroptions = ''

     htmlstringonedevice += '
 Espressif
' + mac + ' ' + ip + '
	'
     htmlstringonedevice += sensorlabel
     htmlstringonedevice += '	'
     htmlstringonedevice += str(round(temp,2)) + '°C'
     htmlstringonedevice += tempdetails(shortmac,temp)
     htmlstringonedevice += '	'
     htmlstringonedevice += str(round(relhumi)) + '%'
     htmlstringonedevice += relhumidetails(shortmac,relhumi)
     htmlstringonedevice += '	'
     htmlstringonedevice += str(round(abshumi)) + 'g/㎥'
     htmlstringonedevice += '	'
     htmlstringonedevice += ''
     shorttodo, todo = return_todo(relhumi,abshumi,outdoorhuml,sensoroptions,sensorlabel)
     #htmlstringonedevice += str(return_todo(relhumi,abshumi,outdoorhuml,sensoroptions,sensorlabel))
     if len(shorttodo) >= 1: htmlstringonedevice += '' + shorttodo + ': '
     htmlstringonedevice += todo
#     htmlstringonedevice += '
'
     htmlstringonedevice += '
'
     if shortmac in misseddevices:
      misseddevices.remove(shortmac)
    htmlstring +=  htmlstringonedevice

for misseddevice in misseddevices:
 htmlstring += '
 ' + misseddevice + '	'
 try: sensorlabel = cf['device'][misseddevice]['label']
 except: sensorlabel = 'unknown'
 htmlstring += sensorlabel
 htmlstring += '	' + cf['htmloutput']['string_configured_but_not_found'] + '
'

htmlstring += "
\n"

htmlstring += "\n\n"
htmlfile.write(htmlstring)
htmlfile.close


import os

from flask import Flask
from flask_restful import Api

from adapters.handlers.error_handling import handler
from controllers.user_controller import user_bp

app = Flask(__name__)
app.register_blueprint(user_bp)
app.register_blueprint(handler)
app.config['SQLALCHEMY_DATABASE_URI'] = '{db}://{u}:{p}@{ur}:{pr}/{n}'.format(
    db='postgresql',
    u='postgres',
    p=os.environ.get('DB_PASS'),
    ur='localhost',
    pr='5432',
    n='python_test'
)
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

app.config["JSON_SORT_KEYS"] = False

# flask_restful
api = Api(app)

@app.before_first_request
def initiate_database():
    # db.drop_all()
    db.create_all()

@app.route('/health-check', methods=['GET'])
def teste():
    return {'app': 'running'}

if __name__ == '__main__':
    from adapters.sql_alchemy import db
    db.init_app(app)
    app.run(debug=False)


# Python program to print pattern G
def Pattern(line):
	pat=""
	for i in range(0,line):
		for j in range(0,line):
			if ((j == 1 and i != 0 and i != line-1) or ((i == 0 or
				i == line-1) and j > 1 and j < line-2) or (i == ((line-1)/2)
				and j > line-5 and j < line-1) or (j == line-2 and
				i != 0 and i != line-1 and i >=((line-1)/2))):
				pat=pat+"*"
			else:
				pat=pat+" "
		pat=pat+"\n"
	return pat

# Driver Code
line = 7
print(Pattern(line))


from typing import List

from django.db import models

from sms.enums import KAVENEGAR_LIMITS, KAVENEGAR_MESSAGE_LENGTH_LIMIT, KAVENEGAR_RECEPTORS_LIMIT
from sms.models import GymtimeSMSInterface
from sms.negar import GymtimeNegar

class GymtimeSimpleSMS(GymtimeSMSInterface):
    message = models.TextField(
        verbose_name='متن پیام',
    )
    receptors: List[str] = []

    def get_receptors(self) -> List[str]:
        return self.receptors

    def validate(self):
        validation = super().validate()
        receptors = self.get_receptors()

        if not receptors:
            validation.add_validation_error('شماره تلفنی برای ارسال پیام داده نشده است.')

        has_wrong_phone_number = False
        for receptor in receptors:
            if not self.validate_phone_number(receptor):
                has_wrong_phone_number = True
                validation.add_validation_error('شماره تلفن {} اشتباه است!'.format(receptor))

        if has_wrong_phone_number:
            validation.add_validation_error(self.WRONG_PHONE_NUMBER_ERRORS)

        if len(self.message) > KAVENEGAR_LIMITS[KAVENEGAR_MESSAGE_LENGTH_LIMIT]:
            validation.add_validation_error('حداکثر تعداد کارکتر پیام {} حرف است'.format(
                KAVENEGAR_LIMITS[KAVENEGAR_MESSAGE_LENGTH_LIMIT]
            ))

        if len(receptors) > KAVENEGAR_LIMITS[KAVENEGAR_RECEPTORS_LIMIT]:
            validation.add_validation_error('حداکثر تعداد مخاطبین {} است'.format(
                KAVENEGAR_LIMITS[KAVENEGAR_RECEPTORS_LIMIT]
            ))

        return validation

    def send(self):
        return GymtimeNegar.send(self.get_receptors(), self.message)

    @property
    def try_gymtime_sms(self):
        from sms.models import GymtimeSMS
        if isinstance(self, GymtimeSMS):
            return self
        try:
            return self.gymtimesms
        except:
            return None

    @property
    def try_club_sms(self):
        from gym.models import ClubSMS
        if isinstance(self, ClubSMS):
            return self
        try:
            return self.clubsms
        except:
            return None

    @property
    def try_club_sms_for_discount(self):
        from gym.models import ClubSMSForDiscount
        if isinstance(self, ClubSMSForDiscount):
            return self
        try:
            return self.clubsmsfordiscount
        except:
            return None

    @property
    def concrete_instance(self):
        return self.try_club_sms_for_discount or self.try_club_sms or self.try_gymtime_sms

    class Meta:
        verbose_name = 'پیامک معمولی'
        verbose_name_plural = 'پیامک‌های معمولی'


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Event',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('latitude', models.DecimalField(default=0.0, max_digits=17, decimal_places=14)),
                ('longitude', models.DecimalField(default=0.0, max_digits=17, decimal_places=14)),
                ('picture', models.ImageField(null=True, upload_to=b'photos', blank=True)),
                ('caption', models.CharField(max_length=300, blank=True)),
                ('submitted_date_time', models.DateTimeField(default=django.utils.timezone.now, verbose_name=b'date submitted')),
            ],
        ),
        migrations.CreateModel(
            name='Tag',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('name', models.CharField(max_length=30)),
            ],
        ),
        migrations.AddField(
            model_name='event',
            name='tags',
            field=models.ManyToManyField(to='crowdwire.Tag'),
        ),
    ]


#!/usr/bin/env/python

import re
import json

# Copyright 2017 Nokia
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

def string_name_value_helper(name, delimiter, string):
    ''' Matches "name <delimiter> <text_value>" in the string and returns <text_value>
    If no match, returns "None"
    '''
    VALUE_RE = "\s*" + delimiter + "\s*(\S+)\s+"
    scratch = re.search(name + VALUE_RE, string)
    if scratch:
        return scratch.group(1)
    else:
        return "None"

def cluster_status_to_json(string):
    WSREP_CONNECTED = "wsrep_connected"
    WSREP_LOCAL_STATE_COMMENT = "wsrep_local_state_comment"
    WSREP_READY = "wsrep_ready"

    WSREP_CLUSTER_SIZE = "wsrep_cluster_size"
    WSREP_CLUSTER_STATUS = "wsrep_cluster_status"
    WSREP_INCOMING_ADDRESSES = "wsrep_incoming_addresses"

    dict = {}

    dict[WSREP_CONNECTED] = string_name_value_helper(WSREP_CONNECTED, "\\|", string)
    dict[WSREP_LOCAL_STATE_COMMENT] = string_name_value_helper(WSREP_LOCAL_STATE_COMMENT, "\\|", string)
    dict[WSREP_READY] = string_name_value_helper(WSREP_READY, "\\|", string)
    dict[WSREP_CLUSTER_SIZE] = string_name_value_helper(WSREP_CLUSTER_SIZE, "\\|", string)
    dict[WSREP_CLUSTER_STATUS] = string_name_value_helper(WSREP_CLUSTER_STATUS, "\\|", string)
    dict[WSREP_INCOMING_ADDRESSES] = string_name_value_helper(WSREP_INCOMING_ADDRESSES, "\\|", string)

    return json.dumps(dict)

class FilterModule(object):

    def filters(self):
        return {
            'cluster_status_to_json': cluster_status_to_json
        }


import pytest

from distributed.deploy.cluster import Cluster

@pytest.mark.asyncio
async def test_eq(cleanup):
    clusterA = Cluster(asynchronous=True, name="A")
    clusterA2 = Cluster(asynchronous=True, name="A2")
    clusterB = Cluster(asynchronous=True, name="B")
    assert clusterA != "A"
    assert not (clusterA == "A")
    assert clusterA == clusterA
    assert not (clusterA != clusterA)
    assert clusterA != clusterA2
    assert not (clusterA == clusterA2)
    assert clusterA != clusterB
    assert not (clusterA == clusterB)

@pytest.mark.asyncio
async def test_repr(cleanup):
    cluster = Cluster(asynchronous=True, name="A")
    assert cluster.scheduler_address == "<Not Connected>"
    res = repr(cluster)
    expected = "Cluster(A, '<Not Connected>', workers=0, threads=0, memory=0 B)"
    assert res == expected

@pytest.mark.asyncio
async def test_logs_deprecated(cleanup):
    cluster = Cluster(asynchronous=True)
    with pytest.warns(FutureWarning, match="get_logs"):
        cluster.logs()


import sys
import time
import RPi.GPIO as GPIO

mode=GPIO.getmode()

GPIO.setwarnings(False)

Forward_left=20
Backward_left=21
Forward_right = 16
Backward_right = 26

# Speed control
speed_low = 33
speed_med = 66
speed_high = 100
speed = speed_med

# Motor setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(Forward_left, GPIO.OUT)
GPIO.setup(Backward_left, GPIO.OUT)
GPIO.setup(Forward_right, GPIO.OUT)
GPIO.setup(Backward_right, GPIO.OUT)

# PWM setup
pwm_frequency = 10000

pwm_forward_left = GPIO.PWM(Forward_left, pwm_frequency)
pwm_backward_left = GPIO.PWM(Backward_left, pwm_frequency)
pwm_forward_right = GPIO.PWM(Forward_right, pwm_frequency)
pwm_backward_right = GPIO.PWM(Backward_right, pwm_frequency)

pwm_forward_left.start(0)
pwm_backward_left.start(0)
pwm_forward_right.start(0)
pwm_backward_right.start(0)

def forward():
    pwm_forward_left.ChangeDutyCycle(speed)
    pwm_forward_right.ChangeDutyCycle(speed)

def backward():
    pwm_backward_left.ChangeDutyCycle(speed)
    pwm_backward_right.ChangeDutyCycle(speed)

def turn_right():
    pwm_backward_left.ChangeDutyCycle(speed)
    pwm_forward_right.ChangeDutyCycle(speed)

def turn_left():
    pwm_forward_left.ChangeDutyCycle(speed)
    pwm_backward_right.ChangeDutyCycle(speed)

def stop():
    pwm_forward_left.ChangeDutyCycle(0)
    pwm_forward_right.ChangeDutyCycle(0)
    pwm_backward_left.ChangeDutyCycle(0)
    pwm_backward_right.ChangeDutyCycle(0)

def set_speed_slow():
    global speed
    speed = speed_low

def set_speed_med():
    global speed
    speed = speed_med

def set_speed_fast():
    global speed
    speed = speed_high

# ---- Shoot stuff
shooter_a = 19
shooter_b = 13

GPIO.setup(shooter_a, GPIO.OUT)
GPIO.setup(shooter_b, GPIO.OUT)

def shoot_on():
    GPIO.output(shooter_b, GPIO.HIGH)
    GPIO.output(shooter_a, GPIO.LOW)
    time.sleep(0.98)
    shoot_off()

def shoot_off():
    GPIO.output(shooter_b, GPIO.LOW)
    GPIO.output(shooter_a, GPIO.LOW)


import logging
import os

from kuibit import argparse_helper as kah
from kuibit.simdir import SimDir

if __name__ == "__main__":
    desc = f"""{kah.get_program_name()} dumps a specific grid variable
    resampled to a given grid into a file. Saving as .npz files guarantees
    the best performances. For 3D data, the default resolution will lead to
    long processing times. """

    parser = kah.init_argparse(description=desc)
    parser.add_argument(
        "--variable", type=str, required=True, help="Variable to save."
    )
    parser.add_argument(
        "--iteration",
        type=int,
        default=-1,
        help="Iteration to plot. If -1, the latest.",
    )

    parser.add_argument(
        "--resolution",
        type=int,
        default=500,
        help=(("Resolution of the resampled data" "(default: %(default)s)")),
    )

    parser.add_argument(
        "--type",
        type=str,
        choices=["x", "y", "z", "xy", "xz", "yz", "xyz"],
        default="xyz",
        help="Type of data (default: %(default)s)",
    )

    parser.add_argument(
        "--outname",
        type=str,
        help="Name of the output file.",
    )

    parser.add_argument(
        "-x0",
        "--origin",
        type=float,
        nargs="+",
    )
    parser.add_argument(
        "-x1",
        "--corner",
        type=float,
        nargs="+",
    )

    args = kah.get_args(parser)

    if len(args.type) != len(args.origin):
        raise ValueError(
            f"x0 ({args.origin}) and type ({args.type}) are incompatible"
        )

    if len(args.type) != len(args.corner):
        raise ValueError(
            f"x1 ({args.corner}) and type ({args.type}) are incompatible"
        )

    if args.outname is None:
        outname = f"{args.variable}_{args.type}.npz"
    else:
        outname = args.outname

    output_path = os.path.join(args.outdir, outname)

    iteration = args.iteration
    x0, x1, res = args.origin, args.corner, args.resolution
    shape = [res] * len(args.type)

    logger = logging.getLogger(__name__)

    if args.verbose:
        logging.basicConfig(format="%(asctime)s - %(message)s")
        logger.setLevel(logging.DEBUG)

    logger.debug(f"Reading variable {args.variable}")
    with SimDir(
        args.datadir,
        ignore_symlinks=args.ignore_symlinks,
        pickle_file=args.pickle_file,
    ) as sim:
        reader = sim.gridfunctions[args.type]
        logger.debug(f"Variables available {reader}")
        var = reader[args.variable]
        logger.debug(f"Read variable {args.variable}")

        if iteration == -1:
            iteration = var.available_iterations[-1]

        logger.debug(f"Reading {iteration} and resampling")

        data = var[iteration].to_UniformGridData(
            shape, x0, x1, iteration=iteration
        )

        logger.debug(f"Saving to {output_path}")
        data.save(output_path)


from typing import Tuple
from uuid import uuid4

import streamlit as st

from mortgage_repayment_calculator.account import (
    ANZOffset,
    Offset,
    UbankOffset,
    Value,
)

def settings() -> Tuple[Offset, int, Value]:
    st.header("Offset Account")
    use_offset_account = st.selectbox("Use Offset Account", ["True", "False"])
    offset_account = None
    deposit_schedule = None
    deposit_amount = None
    if use_offset_account == "True":
        _, col, _ = st.columns([0.05, 0.9, 0.05])
        with col:
            offset_type = st.selectbox("Provider", ["Ubank", "ANZ"])
            starting_balance = st.number_input(
                "Starting Balance $", value=50000, step=10000
            )
            deposit_schedule = st.number_input(
                "Deposit Frequency (days)", value=15, step=1
            )
            deposit_amount = st.number_input(
                "Base Deposit Amount (this scales with salary) $",
                value=2000,
                step=100,
            )
            deposit_amount = Value.from_dollars(deposit_amount)

            if offset_type == "Ubank":
                offset_account = UbankOffset(
                    Value.from_dollars(starting_balance)
                )
            if offset_type == "ANZ":
                offset_account = ANZOffset(
                    Value.from_dollars(starting_balance)
                )

    return offset_account, deposit_schedule, deposit_amount


# 递归版本
def binarySearch(array, key, low, high):
    if high < low:
        return -1
    mid = (low + high)//2

    if array[mid] == key:
        return mid
    elif array[mid] > key:
        return binarySearch(array, key, low, mid-1)
    else:
        return binarySearch(array,key,mid+1,high)

# 非递归版本
def binarySearch_iter(array,key):
    low,high = 0,len(array)-1

    while low <= high:
        mid = (low + high)//2
        if array[mid] < key:
            low = mid+1
        elif array[mid] > key:
            high = mid-1
        else:
            return mid

    return -1

if __name__ == '__main__':
    array = [1,3,4,5,6,7,8,9]

    print(binarySearch(array,1,0,len(array)-1))
    print(binarySearch_iter(array,1))

# 变体1，查找第一个值等于给定值的元素
def binarySearch1(nums,key,low,high):
    if high < low:
        return -1
    mid = ((high - low) >> 1) + low

    if nums[mid] < key:
        return binarySearch1(nums,key,mid+1,high )
    elif nums[mid] > key:
        return binarySearch1(nums,key,low,mid-1)
    else:
        if mid == 0 or nums[mid-1] != key:
            return mid
        else:
            high = mid - 1
            return binarySearch1(nums,key,low,mid-1)

# 变体2，查找最后一个值等于给定值的元素
def binarySearch2(nums,key):
    low,high,n = 0, len(nums)-1, len(nums)-1

    while low <= high:
        mid = ((high-low) >> 1) + low

        if nums[mid] < key:
            low = mid + 1
        elif nums[mid] > key:
            high = mid - 1
        else:
            if mid == n or nums[mid+1] != key:
                return mid
            else:
                low = mid + 1

    return -1

# 变体3，查找第一个大于等于给定值的元素
def binarySearch3(nums,key,low,high):
    if high < low:
        return -1

    mid = ((high - low) >> 1) + low
    if nums[mid] >= key:
        if mid == 0 or nums[mid-1] < key: return mid
        else:   return binarySearch3(nums,key,low,mid-1)
    else:
        return binarySearch3(nums,key,mid+1,high)

# 变体4，查找第一个小于等于给定值的元素
def binarySearch4(nums,key):
    low,high,n = 0,len(nums)-1,len(nums)-1

    while low<= high:
        mid = ((high - low) >> 1) + low

        if nums[mid] <= key:
            if mid == n or nums[mid+1] > key:
                return mid
            else:
                low = mid + 1
        else:
            high = mid - 1

    return -1

# 变体5 查找第一个比某元素大的元素
def find_first_big(nums,key):
    low,high,n = 0,len(nums)-1,len(nums)-1
    while low <= high:
        mid = ((high-low)>>1) + low

        if nums[mid] <= key:
            low = mid + 1
        else:
            if mid == n or nums[mid-1] <= key:
                return nums[mid]
            else:
                high = mid - 1
    return -1

if __name__ == '__main__':
    nums = [1,2,3,4,5,6,8,8,8,11,18]
    print(binarySearch1(nums,8,0,len(nums)-1))
    print(binarySearch2(nums,8))
    print(binarySearch3(nums,12,0,len(nums)-1))
    print(binarySearch4(nums,12))

    print(find_first_big(nums,8))


# es.py
# This program reads in a file and counts how many e's are in it
# Author Michael Casey

# source  Youtube - https://www.youtube.com/watch?v=SJ2nWs4yl9k
import sys

filename = None
startingpoint = 0

#checking to mkae sure an argument/filename has been included in the command line
while len(sys.argv)<2:
#if there is only one name ie. "python .\es.py the below message pops up and closes the program"
    print ("Please include file name/path in command line")
    quit()

#I assume the second argument passed into the command line is a file/path
filename = sys.argv[1]

#filename = "test.txt"
#I assume file is in current directory or command line input includes the path
with open (filename, 'r') as f:
   data = f.read()
   #counting how many e's are in the text file - source geeksforgeeeks.org
   nume = data.count('e')
   numE = data.count('E')
   alle = nume + numE
   print ("There are", alle, "e's in", filename)


import cv2
import os
import numpy as np
import matplotlib.pyplot as plt
from photo_mosaic import *

# Declear types
types = ["manmade","natural"]

# Data augmentation for fast maching and better performance (optional)
for type in types:
    data_augmentation(type)

# Load target images
target_img_pth = os.path.join(COM_pth,"mao1.jpg")
img_target = cv2.imread(target_img_pth)

# Set tile size
tiles = (32,32)

# Composite
img_composited = mosaic(target_img_pth,tiles,types)

# Show the result with comparation
plt.figure(figsize=(15,15))
plt.subplot(1,2,1)
plt.imshow(img_composited[:,:,::-1])
plt.subplot(1,2,2)
plt.imshow(img_target[:,:,::-1])
plt.show()


from typing import List

from fastapi import APIRouter, status, Depends, HTTPException, Response

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.future import select
from sqlalchemy.exc import IntegrityError

from app.models.usuario_models import UsuarioModel
from app.models.licenca_models import LicencaModel
from app.models.vendedor_models import VendedorModel
from app.schemas.licenca_schemas import LicencaSchema, LicencaIdSchema
from app.config.deps import get_session, get_current_user

router = APIRouter()

@router.post('/registra-licenca', status_code=status.HTTP_201_CREATED, response_model=LicencaSchema)
async def create_licenca(licenca: LicencaSchema, db: AsyncSession = Depends(get_session), logado: UsuarioModel = Depends(get_current_user)):

    async with db as session:
        try:

            query = select(VendedorModel).filter(VendedorModel.usuario_id == logado.id)
            result = await session.execute(query)
            vendedor_id: VendedorModel = result.scalars().unique().one_or_none()

            if not vendedor_id:
                    raise HTTPException(detail='Usuário Vendedor não encontrado.', status_code=status.HTTP_404_NOT_FOUND)

            nova_licenca: LicencaModel = LicencaModel(validade=licenca.validade, quantidade=licenca.quantidade, produto_id=licenca.produto_id)

            session.add(nova_licenca)
            await session.commit()

            return nova_licenca
        except IntegrityError:
            raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE,
                                detail='Licença já cadastrada.')

@router.get('/licencas', response_model=List[LicencaIdSchema])
async def get_licencas(db: AsyncSession = Depends(get_session)):
    async with db as session:
        query = select(LicencaModel)
        result = await session.execute(query)
        licencas = result.scalars().unique().all()

        return licencas

@router.get('/licenca-id/{licenca_id}', response_model=LicencaSchema, status_code=status.HTTP_200_OK)
async def get_licenca_id(licenca_id: int, db: AsyncSession = Depends(get_session)):
    async with db as session:
        query = select(LicencaModel).filter(LicencaModel.id == licenca_id)
        result = await session.execute(query)
        licenca: LicencaModel = result.scalars().unique().one_or_none()

        if licenca:
            return licenca
        else:
            raise HTTPException(detail='Licença não encontrada.', status_code=status.HTTP_404_NOT_FOUND)

@router.put('/{licenca_id}', response_model=LicencaSchema, status_code=status.HTTP_202_ACCEPTED)
async def put_licenca(licenca_id: int, licenca: LicencaSchema, db: AsyncSession = Depends(get_session), usuario_logado: UsuarioModel = Depends(get_current_user)):
    async with db as session:
        query = select(LicencaModel).filter(LicencaModel.id == licenca_id)
        result = await session.execute(query)
        licenca_up: LicencaModel = result.scalars().unique().one_or_none()

        query_vendedor = select(VendedorModel).filter(VendedorModel.usuario_id == usuario_logado.id)
        result = await session.execute(query_vendedor)
        vendedor_id: VendedorModel = result.scalars().unique().one_or_none()

        if not vendedor_id:
            raise HTTPException(detail='Usuário Vendedor não encontrado.', status_code=status.HTTP_404_NOT_FOUND)

        if licenca_up:
            if licenca.validade:
                licenca_up.validade = licenca.validade

            if licenca.quantidade:
                licenca_up.quantidade = licenca.quantidade

            await session.commit()

            return licenca_up
        else:
           raise HTTPException(detail='Licença não encontrada.', status_code=status.HTTP_404_NOT_FOUND)

@router.delete('/{licenca_id}', status_code=status.HTTP_204_NO_CONTENT)
async def delete_licenca(licenca_id: int, db: AsyncSession = Depends(get_session), usuario_logado: UsuarioModel = Depends(get_current_user)):
    async with db as session:
        query = select(LicencaModel).filter(LicencaModel.id == licenca_id).filter(VendedorModel.usuario_id == usuario_logado.id)

        result = await session.execute(query)
        licenca_del: LicencaModel = result.scalars().unique().one_or_none()

        if licenca_del:
            await session.delete(licenca_del)
            await session.commit()

            return Response(status_code=status.HTTP_204_NO_CONTENT)
        else:
            raise HTTPException(detail='Licença não encontrada.', status_code=status.HTTP_404_NOT_FOUND)


import datetime
employees = list()
def add_new_employee():
    first = input("First name: ")
    last = input("Last name: ")
    while True:
        try:
            age = int(input("Age: "))
        except:
            print("You did not enter a proper age")
        else:
            break
    email = f"{first}.{last}{str(datetime.date.today().year - age)[-2:]}@company.com"
    print(f"{first} {last} added to records with the email '{email}'")
    employees.append({"first_name" : first, "last_name" : last, "age" : age, "email" : email})

cont = True
while(cont):
    try:
        print("How many employees will you be adding? ")
        num = input()
        num = int(num)
        print(num)
        if not num.isdigit():
            raise Exception
    except Exception:
        print("That is not a num")
    else:
        cont = False
for i in range(num):
    add_new_employee()


# -*- coding: utf-8 -*-
"""
Created on Thu Jun 11 17:39:20 2020

@author: chakanc
"""

import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder, LabelEncoder, StandardScaler, OrdinalEncoder
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import train_test_split

def main():

    dataset = pd.read_csv('Data.csv')
    print(dataset)

    X = dataset.iloc[:,:-1]  # dataset.iloc[:,0:2]
    y = dataset.iloc[:,-1]
    #y.columns = ['Purchased']

    # Fix missing data
    #imputerobj = SimpleImputer(missing_values=np.nan, strategy='most_frequent')
    #imputerobj.fit(X)

    imputerobj = SimpleImputer(missing_values=np.nan, strategy='mean')
    imputerobj.fit(X.iloc[:, 1:3])

    X.iloc[:, 1:3] = imputerobj.transform(X.iloc[:, 1:3])

    #oe = OrdinalEncoder(categories='auto', dtype=np.int)
    #y.iloc[:] = oe.fit_transform(np.array(y.iloc[:]))

    #encoding data
    le = LabelEncoder()
    y = le.fit_transform(y)

    cat_features = ['Country']
    ct = ColumnTransformer(transformers=[('enc1', OneHotEncoder(dtype=np.int32), cat_features)], remainder='passthrough')
    X = np.array(ct.fit_transform(X))

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state = 1)

    sc = StandardScaler()
    X_train[:,3:] = sc.fit_transform(X_train[:,3:])
    X_test[:,3:] = sc.transform(X_test[:,3:])

    print(X_train)
    print(X_test)

main()


class Student:
    def __init__(self,name,age,gender):
        self.name=name
        self.age=age
        self.gender=gender

    def print_all(self):
        print("\nname: " + self.name + " \nage:" + str(self.age) + " \ngender:" + self.gender)

    def add_marks(self,marks):
        self.marks=marks

ram=Student('Ram',27,'M')
shayam=Student("Shayam",43,'M')
print("this is for init function",ram.name)
ram.print_all()
shayam.print_all()

ram.add_marks([90,97,100])
print(ram.marks)


import math
import numpy as np
import sympy
from sympy import *
from tinydb import TinyDB, Query
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import random
from matplotlib import cm

def runlength(w):
    k = 1
    rl = []
    for i in range(len(w))[1:]:
        if w[i]-w[i-1] != 0:
            rl.append(k)
            k = 1
        else:
            k += 1
    rl.append(k)
    return rl

def compare_sequence(a, ap, b, bp):
    al = len(a)
    bl = len(b)
    for i in range(math.lcm(al, bl)):
        ia = i if i < al or ap == 0 else (al - ap) + (i- (al - ap)) % ap
        ib = i if i < bl or bp == 0 else (bl - bp) + (i- (bl - bp)) % bp
        va = math.inf
        vb = math.inf
        if ia < al:
            va = a[ia]
        if ib < bl:
            vb = b[ib]
        if va < vb:
            return pow(-1, i+1)
        elif va > vb:
            return pow(-1, i)
    return 0

def right_conjugate(s):
    t = s[:]
    if t[-1] == 1:
        t[-2] += 1
        t.pop()
    else:
        t[-1] -= 1
        t.append(1)
    return t

def center_point_ric(f1, f2, alpha):
    p = runlength(f1)
    s = runlength(f2)

    if compare_sequence([0] + p, len(p), alpha, 0) != -1:
        return p
    if compare_sequence(alpha, 0, [0] + right_conjugate(s) + s[::-1], len(s)) != -1:
        return s
    c = f1 + f2
    c_seq = runlength(c)
    r = compare_sequence(alpha, 0, c_seq, 0)
    if r == 0:
        return c_seq
    elif r == 1:
        return center_point_ric(c, f2, alpha)
    else:
        return center_point_ric(f1, c, alpha)

def rational_to_seq(a, b):
    s = []
    while b != 1:
        q, mod = divmod(a, b)
        a = b
        b = mod
        s.append(q)
    s.append(a)
    return s

def center_point(p, q):
    s = rational_to_seq(p, q)
    n = 2
    while True:
        r = compare_sequence(s, 0, [0, n], 0)
        if r == 0:
            return s
        elif r == 1:
            break
        n += 1
    return center_point_ric([0] * (n - 1) + [1], [0] * (n - 2) + [1], s)

def c_alpha(alpha, x):
    return floor(-x**(-1)+1-alpha)

def phi(alpha, p):
    c = c_alpha(alpha, p[1])
    x = simplify((c - p[0])**(-1))
    y = Integer(0)
    if p[1] != 0:
        y = simplify(-p[1]**(-1)-c)
    return x, y

def orbit(alpha, p, n):
    old = p
    r = [(float(p[0].evalf(5)), float(p[1].evalf(5)))]
    for i in range(n):
        p = phi(alpha, p)
        if p == old:
            break
        r.append((float(p[0].evalf(5)), float(p[1].evalf(5))))
        old = p

    return r

def fill_intermediate_points(l):
    ll = len(l)-1
    r = [0] * (ll * 2)
    for i in range(ll):
        r[i*2] = l[i]
        r[i*2+1] = (l[i+1][0], l[i][1])
    return r

def attractor(alpha):
    alpha = Rational(alpha)

    c = center_point(alpha.p, alpha.q)
    y = -continued_fraction_reduce([0, c])
    kl = list(reversed(c))
    x = continued_fraction_reduce([0, kl])
    n, m = sum(c[::2]), sum(c[1::2])
    xs = orbit(alpha, (x, alpha), m)
    ys = orbit(alpha, (y, alpha - 1), n)

    ys = sorted(ys)
    ys.append((float(x.evalf(5)), 0))
    ys = fill_intermediate_points(ys)

    xs = sorted(xs, reverse=True)
    xs.append((float(y.evalf(5)), 0))
    xs = fill_intermediate_points(xs)

    return xs, ys

def g(a, b, c, d):
    return ln(b*d+1)-ln(a*d+1)-ln(b*c+1)+ln(a*c+1)

def entropy(alp):
    xs, ys = attractor(alp)

    sol = 0
    for i in range(2, len(xs), 2):
        sol += g(xs[i+1][0], xs[i][0], alp-1, xs[i][1])

    for i in range(2, len(ys), 2):
        sol += g(ys[i][0], ys[i+1][0], ys[i][1], alp)

    sol += g(xs[1][0], ys[1][0], alp-1, alp)

    return float((pi**2/(3*sol)).evalf(5))

def induced_density_k(alpha,s):
    xs, ys = attractor(alpha)
    x0 = [(*x,0) for x in xs[::2]]
    x1 = [(*x,1) for x in xs[1::2]]
    y0 = [(*y,10) for y in ys[::2]]
    y1 = [(*y,11) for y in ys[1::2]]
    t = x0 + x1 + y0 + y1

    t=sorted(t,key=lambda k: (k[1],k[0]))

    r = []
    ca = ys[0][0]
    cb = ys[1][0]
    for i in range(2,len(t)):
        if t[i][2]==10:
            b=t[i][0]
            y=t[i][1]
            if len(r)==0 or r[-1][0] != y:
                r.append([y,ca,b])
        elif t[i][2]==11:
            cb = t[i][0]
        elif t[i][2]==0:
            ca = t[i][0]
        elif t[i][2]==1:
            a=t[i][0]
            y=t[i][1]
            r.append([y,a,cb])

    al = math.floor(alpha * 1000) / 1000
    m = gi(alpha-1,al-1.1,s)
    x = np.arange(al - 1.1, al + 0.1, s)
    y = np.zeros(len(x))

    for j in r:
        c = gi(j[0],al-1.1,s)
        xc = x[m:c]
        a = j[1]
        b = j[2]
        y[m:c] = list((b-a)/((a*xc+1)*(b*xc+1)))
        m = c

    plt.plot(x, y)
    plt.savefig("density_k.png", dpi=300)
    plt.close()
    #plt.ylim(bottom=0, top=3)
    #plt.savefig("induced_density_k.png",dpi=300)

    """
    y = k + np.sqrt(r ** 2 - (x - h) ** 2)
    d = (b-a)/((a*x+1)*(b*x+1))
    """

Todo = Query()
db = TinyDB('db.json')

def fill_data_db():
    config = db.get(Todo.type == "config")
    step = config['step']
    x = config['last'] - step
    while x > step:
        db.insert({'alpha': x, 'entr': entropy(x)})
        db.update({'last': x}, Todo.type == "config")
        x -= step

def plot_entropy():
    entropy = db.search(Todo.alpha.exists())
    print(entropy)
    xs, ys = [], []
    for v in entropy:
        xs.append(v['alpha'])
        ys.append(v['entr'])

    plt.plot(xs, ys)
    plt.ylabel('Entropy')
    plt.xlabel('Alpha')
    plt.show()

def get_xy(l):
    return [i[0] for i in l], [i[1] for i in l]

def interactive_plot():
    plt.subplots_adjust(bottom=0.35)
    plt.xlim([-1, 1])
    plt.ylim([-1, 1])

    l, = plt.plot([0], [0])

    axalpha = plt.axes([0.25, 0.15, 0.65, 0.03])

    alpha = Slider(axalpha, 'alpha', 0.0, 0.5, 4/15, valstep=0.01)

    def update_interactive_plot(_):
        a = alpha.val
        t = attractor(a)
        j = t[0]+t[1]+[t[0][0]]
        l.set_data(*get_xy(j))

    alpha.on_changed(update_interactive_plot)

    plt.show()

def show_region(alpha=4/15):
    xs, ys = attractor(alpha)

    plt.figure(figsize=(4, 4))
    for i in range(2, len(ys), 2):
        plt.plot(*get_xy([ys[i], ys[i + 1], (ys[i + 1][0], alpha), (ys[i][0], alpha), ys[i]]))

    for i in range(2, len(xs), 2):
        plt.plot(*get_xy([xs[i], xs[i + 1], (xs[i + 1][0], alpha-1), (xs[i][0], alpha-1), xs[i]]))

    plt.plot(*get_xy([xs[1],(xs[1][0], alpha-1),ys[1],(ys[1][0],alpha),xs[1]]))

    plt.savefig("attractor_regions.png", dpi=300)
    plt.close()

def check_ergodicity(alpha=4/15):
    alpha = Rational(alpha)
    px = []
    py = []

    for i in range(1000):
        x = Rational(random.random() * 0.6)
        y = Rational(-random.random() * 0.6)
        pxt,pyt = get_xy(orbit(alpha, (x, y), 100))
        px += pxt
        py += pyt

    plt.scatter(px, py, 0.3)
    plt.plot()#("ergodicity.png", dpi=400)

def plot(alpha=4/15):
    t = attractor(alpha)
    j = t[0]+t[1]+[t[0][0]]

    plt.figure(figsize=(4, 4))
    plt.plot(*get_xy(j))
    plt.savefig("attractor.png", dpi=300)
    plt.close()

def qumterval(s):
    r = runlength(s)
    sx = [0] + right_conjugate(r) + [r[::-1]]
    dx = [0, r]
    return (continued_fraction_reduce(sx),continued_fraction_reduce(dx))

def qumtervals(n):
    qumtervals = []
    fn = [[0], [1]]
    for i in range(n):
        l = len(fn)
        for x in range(l - 1):
            fn.insert(2 * x + 1, fn[2 * x] + fn[2 * x + 1])

    for i in fn[1:-1]:
        qumtervals.append(qumterval(i))
    return qumtervals

def semicircle(r, h, k):
    x0 = h - r
    x1 = h + r
    n = math.ceil(abs(x0-x1)/0.00001)
    if n<4:
        return None
    x = np.linspace(x0,x1,n,True)
    y = k + np.sqrt(r**2 - (x - h)**2)
    return x, y

def plot_qumtervals():
    qs = qumtervals(7)

    xs = []
    ys = []
    for q in qs:
        r = float(abs((q[0]-q[1])/2).evalf(5))
        c = float(abs((q[0]+q[1])/2).evalf(5))
        d = semicircle(r, c, 0)
        if d is not None:
            xs += list(d[0])
            ys += list(d[1])

    plt.plot(xs,ys,linewidth=0.5)
    plt.axis('scaled')
    plt.savefig('qumterval.png',dpi=500)

def k_alpha(alpha,x):
    if x == 0:
        return Integer(0)
    c = c_alpha(alpha, x)
    return (-x ** (-1) - c)

# get_index
def gi(x, start, step):
    return round((x-start)/step)

def num_density_k(alpha,s,rep):
    a = math.floor(alpha * 1000) / 1000
    x = np.arange(a - 1.1, a+0.1, s)
    st = np.zeros(len(x))

    alp = Rational(alpha)

    for i in range(rep):
        p = k_alpha(alp, Rational(alpha - 1 + random.random()))
        while p != 0:
            j = gi(p, a - 1.1, s)
            st[j] += 1
            p = k_alpha(alp, p)

    stf = np.copy(st)
    for j in range(2,8):
        for u in range(1,j):
            if math.gcd(j,u)==1:
                v = u/j
                if v > a-1 and v < a:
                    k = gi(v,a-1.1,s)
                    med = (stf[k - 1] + stf[k + 1]) / 2
                    stf[k]=med
                if -v > a-1 and -v < a:
                    k = gi(-v, a - 1.1, s)
                    med = (stf[k - 1] + stf[k + 1]) / 2
                    stf[k]=med

    sm = sum(st) * s / 1.07
    st = list(map(lambda x: x / sm, st))

    smf = sum(stf) * s / 1.07
    stf = list(map(lambda x: x / smf, stf))

    plt.plot(x, st)
    plt.savefig("num_density_k.png", dpi=300)
    plt.close()

    plt.plot(x, stf)
    plt.savefig("num_density_k_filtered.png", dpi=300)
    plt.close()

def num_density_phi(alpha, s, rep):
    a = math.floor(alpha * 1000) / 1000
    alpha = Rational(alpha)
    xs, ys = attractor(alpha)
    l, r = float(ys[0][0]), float(xs[0][0])

    x = np.arange(l-0.1, r+0.1, s)
    y = np.arange(a-1.1, a+0.1, s)
    X, Y = np.meshgrid(x, y)
    Z = X * 0

    for i in range(rep):
        p = phi(alpha, (Rational(random.uniform(l,r)), Rational(alpha - 1 + random.random())))
        while p[1] != 0:
            Z[gi(p[1], alpha - 1.1, s),gi(p[0], l - 0.1, s)] += 1
            p = phi(alpha, p)

    Zf = np.copy(Z)
    for j in range(2,8):
        for u in range(1,j):
            if math.gcd(j,u)==1:
                v = u/j
                if v > a-1 and v < a:
                    k = gi(v,a-1.1,s)
                    for d in range(len(Z[k])):
                        med = (Zf[k - 1,d] + Zf[k + 1,d]) / 2
                        Zf[k,d]=med
                if -v > a-1 and -v < a:
                    k = gi(-v, a - 1.1, s)
                    for d in range(len(Z[k])):
                        med = (Zf[k - 1, d] + Zf[k + 1, d]) / 2
                        Zf[k, d] = med

    plt.figure(figsize=(4,4))
    plt.pcolormesh(X, Y, Zf)
    plt.savefig("num_density_phi_filtered2.png", dpi=300)
    plt.close()

    plt.figure(figsize=(4, 4))
    plt.pcolormesh(X, Y, Z)
    plt.savefig("num_density_phi2.png", dpi=300)
    plt.close()

    r = np.zeros(len(y))
    for i in range(len(y)):
        r[i] = np.sum(Z[i])

    sm = sum(r) * s / 1.07
    r = list(map(lambda x: x / sm, r))

    rf = np.zeros(len(y))
    for i in range(len(y)):
        rf[i] = np.sum(Zf[i])

    smf = sum(rf) * s / 1.07
    rf = list(map(lambda x: x / smf, rf))

    plt.plot(y,r)
    plt.savefig("num_induced_density_k2.png",dpi=300)
    plt.close()

    plt.plot(y,rf)
    plt.savefig("num_induced_density_k_filtered2.png",dpi=300)
    plt.close()

def density_phi(alpha, step, margin):
    alpha = Rational(alpha)
    xs, ys = attractor(alpha)

    l, r = float(ys[0][0]), float(xs[0][0])
    ml, mr = l - margin, r + margin
    mb, mt = float(alpha) - 1 - margin, float(alpha) + margin
    x = np.arange(ml, mr, step)
    y = np.arange(mb, mt, step)
    X, Y = np.meshgrid(x, y)
    Z = X * 0

    for i in range(2, len(ys), 2):
        il = gi(ys[i][0], ml, step)
        ir = gi(ys[i + 1][0], ml, step)
        ib = gi(ys[i][1], mb, step)
        it = gi(alpha, mb, step)
        Z[ib:it,il:ir] = 1/(1 + X[ib:it,il:ir]*Y[ib:it,il:ir])**2

    for i in range(2, len(xs), 2):
        il = gi(xs[i+1][0], ml, step)
        ir = gi(xs[i][0], ml, step)
        ib = gi(alpha-1, mb, step)
        it = gi(xs[i][1], mb, step)
        Z[ib:it, il:ir] = 1 / (1 + X[ib:it, il:ir] * Y[ib:it, il:ir]) ** 2

    il = gi(xs[1][0], ml, step)
    ir = gi(ys[1][0], ml, step)
    ib = gi(alpha - 1, mb, step)
    it = gi(alpha, mb, step)
    Z[ib:it, il:ir] = 1 / (1 + X[ib:it, il:ir] * Y[ib:it, il:ir]) ** 2

    f, ax = plt.subplots(figsize=(4, 4))
    plt.pcolormesh(X,Y,Z)
    plt.savefig("density_phi.png",dpi=300)

def main():

    alpha = 4/15
    s = 0.005
    rep = 500
    margin = 0.1
    #num_density_phi(alpha, s, rep)
    #density_phi(alpha,s,margin)
    #plot()
    #show_region()
    #num_density_k(alpha, s, rep)
    #induced_density_k(alpha,s)
    #num_density_phi(alpha, s, rep)
    interactive_plot()

main()


import csv, sys, requests, json

def main():
    if len(sys.argv) != 3:
        return
    in_name = sys.argv[1]
    out_name = sys.argv[2]

    with open(in_name, mode='r') as read_file:
        reader = csv.DictReader(read_file)
        success = []
        failed = []
        counter = 1

        for row in reader:
            data = {}
            data['id'] = counter
            data['class'] = "Bot" if (int)(row['Class']) == 1 else "Human"

            try:
                text = row['Tweet'].encode('utf8', 'ignore').decode('utf8')
                data['text'] = text
                success.append(data)
            except UnicodeEncodeError as ex:
                data['text'] = row['Tweet']
                failed.append(data)

            counter += 1

        with open('errors.csv', 'w') as errorFile:
            writer = csv.writer(errorFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

            for data in failed:
                writer.writerow([data['id'], data['text'], data['isBot']])

        with open(sys.argv[2], 'w') as outfile:
            json.dump(success, outfile)

if __name__ == '__main__':
    main()


import logging
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from resilient_lib import ResultPayload
from fn_crowdstrike_falcon.util.cs_helper import CrowdStrikeHelper

class FunctionComponent(ResilientComponent):
    """Component that implements Resilient function 'fn_cs_falcon_get_devices_ioc_ran_on"""

    def __init__(self, opts):
        """constructor provides access to the configuration options"""
        super(FunctionComponent, self).__init__(opts)
        self.opts = opts
        self.function_opts = opts.get(CrowdStrikeHelper.app_config_section, {})

    @handler("reload")
    def _reload(self, event, opts):
        """Configuration options have changed, save new values"""
        self.opts = opts
        self.function_opts = opts.get(CrowdStrikeHelper.app_config_section, {})
        CrowdStrikeHelper.load_class_variables(self.function_opts)

    @function("fn_cs_falcon_get_devices_ioc_ran_on")
    def _fn_cs_falcon_get_devices_ioc_ran_on_function(self, event, *args, **kwargs):
        """Function: Function that uses the CrowdStrike Falcon '/indicators/queries/devices/v1' endpoint to get the list of Devices an IOC Ran On. Supported IOC types: sha256, sha1, md5 and domain."""
        try:
            err_msg = None
            log = logging.getLogger(__name__)

            # Map resilient artifact type to crowdstrike ioc type
            map_artifact_type_to_ioc_type = {
                "DNS Name": "domain",
                "Malware SHA-256 Hash": "sha256",
                "Malware SHA-1 Hash": "sha1",
                "Malware MD5 Hash": "md5"
            }

            # Instansiate helper (which gets appconfigs)
            cs_helper = CrowdStrikeHelper(self.function_opts)

            # Get the function inputs:
            fn_inputs = {
                "cs_ioc_type": cs_helper.get_function_input(kwargs, "cs_ioc_type"),  # text (required)
                "cs_ioc_value": cs_helper.get_function_input(kwargs, "cs_ioc_value"),  # text (required)
                "cs_return_limit": cs_helper.get_function_input(kwargs, "cs_return_limit", True)  # text (optional)
            }

            # Create new Function ResultPayload with appconfigs and function inputs
            payload = ResultPayload(CrowdStrikeHelper.app_config_section, **fn_inputs)

            # Get crowdstrike cs_ioc_type, cs_ioc_value and cs_return_limit
            cs_ioc_type = fn_inputs.get("cs_ioc_type")
            cs_ioc_value = fn_inputs.get("cs_ioc_value")
            cs_return_limit = fn_inputs.get("cs_return_limit")

            yield StatusMessage("> Function Inputs OK")

            # Convert Resilient Artifact Type to support CrowdStrike IOC type
            supported_ioc_type = map_artifact_type_to_ioc_type.get(cs_ioc_type, None)

            # If its a type that is not supported, raise error
            if supported_ioc_type is None:
                raise ValueError("{0} is not a supported IOC type. Supported types are {1}".format(cs_ioc_type, map_artifact_type_to_ioc_type))

            # Set request url and payload
            get_device_ioc_ran_on_url = "{0}{1}".format(cs_helper.bauth_base_url, "/indicators/queries/devices/v1")
            get_device_ioc_ran_on_payload = {
                "type": supported_ioc_type,
                "value": cs_ioc_value
            }

            # If the no. of devices to be returned limit is defined, set it in the payload
            if cs_return_limit:
                log.debug("cs_return_limit set to: %s", cs_return_limit)
                get_device_ioc_ran_on_payload["limit"] = cs_return_limit

            # Set the request
            get_device_ioc_ran_on_response = cs_helper.cs_api_request(
                method="GET",
                url=get_device_ioc_ran_on_url,
                basicauth=(cs_helper.bauth_api_uuid, cs_helper.bauth_api_key),
                params=get_device_ioc_ran_on_payload)

            # If there is a 'handled' error, handle it
            if get_device_ioc_ran_on_response.get("error"):
                err_msg = get_device_ioc_ran_on_response.get("err_msg")

                # If known error of no devices found for the IOC, handle gracefully
                if "Resource Not Found" in err_msg:
                    err_msg = "IOC {0}:{1} not found on any CrowdStrike Device.".format(cs_ioc_type, cs_ioc_value)
                    yield StatusMessage("> {0}".format(err_msg))
                    payload = payload.done(False, None, reason=err_msg)

                # Else raise the error
                else:
                    raise ValueError(err_msg)

            # Else if no errors, set build function results payload
            else:
                payload = payload.done(True, {
                    "meta": get_device_ioc_ran_on_response.get("meta"),
                    "device_ids": get_device_ioc_ran_on_response.get("resources")
                })

            results = payload
            log.debug("RESULTS: %s", results)
            log.info("> Complete")

            # Produce a FunctionResult with the results
            yield FunctionResult(results)
        except Exception:
            yield FunctionError()


import random

suits = ('Clubs', 'Diamonds', 'Hearts', 'Spades')
ranks = ('2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A')
values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9, 'T': 10, 'J': 10, 'Q': 10, 'K': 10, 'A': 1}
max_shoe_size = 12
shuffle_at_percentage = 0.25
blackjack_payout_ratio = 1.5

class Card:
    def __init__(self, suit, rank):
        self.suit = suit[0].lower()
        self.rank = rank
        self.value = values[rank]

    def __repr__(self):
        return self.rank + "" + self.suit

class Shoe:
    def __init__(self, decks):
        self.all_cards = []
        self.size = decks * 52
        for _ in range(decks):
            for suit in suits:
                for rank in ranks:
                    self.all_cards.append(Card(suit, rank))

    def shuffle(self):
        random.shuffle(self.all_cards)

    def deal_one(self):
        return self.all_cards.pop(0)

    def remaining_percentage(self):
        return len(self.all_cards) / self.size

    def __repr__(self):
        return str(self.all_cards)

class Hand:
    def __init__(self):
        self.hand = []

    def add_card(self, card):
        self.hand.append(card)

    def has_blackjack(self):
        if self.hand_size() == 2 and self.hand_total() == 21:
            return True
        return False

    def hand_size(self):
        return len(self.hand)

    def hand_total(self):
        num_aces = 0
        temp_total = 0
        current_hand = self.hand
        for current_card in current_hand:
            if current_card.rank == 'A':
                # give all Aces a minimum 1 point, 10 more will be added later if needed
                num_aces += 1
                temp_total += 1
            else:
                temp_total += current_card.value

        # add the extra 10 points from the Aces if beneficial
        while temp_total <= 11 and num_aces >= 1:
            temp_total += 10
            num_aces -= 1
        return temp_total

    def __repr__(self):
        return str(self.hand)

class Player:
    def __init__(self, player_name, balance):
        self.player_name = player_name.capitalize()
        self.hand = Hand()
        self.balance = balance

    def new_game(self):
        self.hand = Hand()

def evaluate_winner(player_human, player_dealer, bet_amount):
    player_hand_total = player_human.hand.hand_total()
    dealer_hand_total = player_dealer.hand.hand_total()
    print("{}'s total: {}".format(player_human.player_name, player_hand_total))
    print("Dealer total: {}".format(dealer_hand_total))
    print()

    if player_hand_total > 21:
        print("Bust!")
        player_human.balance -= bet_amount
    elif player_dealer.hand.has_blackjack():
        if player_human.hand.has_blackjack():
            print("Push! Dealer and player have blackjack!")
        else:
            print("Dealer blackjack! You lose!")
            player_human.balance -= bet_amount
    elif player_human.hand.has_blackjack():
        print("Blackjack!")
        player_human.balance += bet_amount * blackjack_payout_ratio
    elif dealer_hand_total < player_hand_total <= 21:
        print("You win!")
        player_human.balance += bet_amount
    elif player_hand_total < dealer_hand_total <= 21:
        print("You lose!")
        player_human.balance -= bet_amount
    elif dealer_hand_total == player_hand_total:
        print("Push!")
    else:
        print("Dealer busts! You win!")
        player_human.balance += bet_amount

def print_rules():
    print("Blackjack Rules:")
    print("Any number of decks from 1-12.")
    print("Shoe will shuffle after {}% usage.".format(shuffle_at_percentage*100))
    print("Double Down and Surrender are permitted.")
    print("Dealer must stand on soft 17. Blackjack pays 3:2")
    print()

if __name__ == '__main__':
    print_rules()
    # create players w/ starting balance
    name = input("Welcome to the table. What is your name? ")
    player_human = Player(name, 1000)
    player_dealer = Player("Dealer", 1000)

    while True:
        try:
            num_decks = int(input("How many decks to play with? "))
        except ValueError:
            print("Looks like you didn't enter an integer.")
            pass
        else:
            if num_decks > max_shoe_size:
                print("Let's not get crazy here. Choose between 1-12 decks.")
            elif num_decks <= 0:
                print("Choose a real value to play with.")
            else:
                break

    # create deck object and shuffle it
    new_shoe = Shoe(num_decks)
    new_shoe.shuffle()
    play_game = True
    while play_game:
        # check if current cards in shoe is below the threshold needed to reshuffle
        if new_shoe.remaining_percentage() < shuffle_at_percentage:
            new_shoe = Shoe(num_decks)
            new_shoe.shuffle()

        # reset player hands
        player_human.new_game()
        player_dealer.new_game()

        print()
        print("{}'s Balance: {}".format(name, player_human.balance))
        while True:
            try:
                bet_amount = int(input("How much to bet? "))
                print()
            except ValueError:
                print("Looks like you didn't enter an integer.")
                pass
            else:
                if bet_amount > player_human.balance:
                    print("You can't bet that much!")
                elif bet_amount <= 0:
                    print("Choose a real value to bet with.")
                else:
                    break

        # deal and display initial cards and totals
        player_human.hand.add_card(new_shoe.deal_one())
        player_human.hand.add_card(new_shoe.deal_one())
        player_dealer.hand.add_card(new_shoe.deal_one())
        print("Dealer has: {}".format(player_dealer.hand))
        print("{} has: {}".format(name, player_human.hand))
        print("{}'s total: {}".format(name, player_human.hand.hand_total()))

        # continue until player stands or busts
        stand = False
        skip_dealer = False
        while not stand and player_human.hand.hand_total() < 21:
            while True:
                if player_human.hand.hand_size() == 2:
                    response = input("[H]it, [S]tand, [D]ouble Down, or Su[R]render? ")
                    if response[0].capitalize() == 'H':
                        player_human.hand.add_card(new_shoe.deal_one())
                        break
                    elif response[0].capitalize() == 'S':
                        stand = True
                        break
                    elif response[0].capitalize() == 'D':
                        if bet_amount * 2 > player_human.balance:
                            print("You don't have enough to double down!")
                            continue
                        else:
                            print("Dealing one.")
                            bet_amount = bet_amount * 2
                            player_human.hand.add_card(new_shoe.deal_one())
                            stand = True
                            break
                    elif response[0].capitalize() == "R":
                        # a surrender immediately ends the game
                        print("Surrendered. Half the bet is returned. ")
                        player_human.balance -= bet_amount / 2
                        stand = True
                        skip_dealer = True
                        break
                    else:
                        print("Invalid response.")
                        continue

                else:
                    response = input("[H]it or [S]tand? ")
                    if response[0].capitalize() == 'H':
                        player_human.hand.add_card(new_shoe.deal_one())
                        break
                    elif response[0].capitalize() == 'S':
                        stand = True
                        break
                    else:
                        print("Invalid response.")
                        continue
            print()
            print("Dealer has: {}".format(player_dealer.hand))
            print("{} has: {}".format(name, player_human.hand))
            print("{}'s total: {}".format(name, player_human.hand.hand_total()))
            print()

        # dealer game play
        # must stand on soft 17 (any 17, including A + 6)
        if not skip_dealer:
            while player_dealer.hand.hand_total() < 17:
                player_dealer.hand.add_card(new_shoe.deal_one())
                print("Dealer has: {}".format(player_dealer.hand))
                print("Dealer total: {}".format(player_dealer.hand.hand_total()))
                print()

            evaluate_winner(player_human, player_dealer, bet_amount)


from PIL import Image
import math

img = Image.open('world.png')
width, height = img.size
img2 = Image.new('RGB', (width , height))

col=[(40,78,178),(124,235,68),(194,237,117),(229,185,95),(172,126,44),(81,61,34)]

def nearColor(c):
    r,g,b,a=c
    best=1000000
    bi=-1
    for i in range(len(col)):
        r1,g1,b1=col[i]
        sc=math.sqrt((r1-r)**2+(g1-g)**2+(b1-b)**2)
        if best>sc:
            best=sc
            bi=i
    return col[bi]

for y in range(height):
  for x in range(width):
    r,g,b = nearColor(img.getpixel((x,y)))
    img2.putpixel((x,y), (int(r), int(g), int(b)))

img2.show()
img2.save('worldout.png')


from flask import Flask, request, jsonify, render_template
import search_q
from search_q import search, process_query
from search_q_pure_text import search_text, process_query_text
from search_q_amb import search_amb, process_query_amb
from search_q_stem import search_stem, process_query_stem
import build_idx

app = Flask(__name__, template_folder='templates_folder', static_folder='static')

def format_results(hits):
    results = []
    for hit in hits:
        result = {
            "rank": hit["rank"],
            "score": hit["score"],
            "docno": hit["docno"],
            "snippet": hit["text"]
        }
        results.append(result)
    return results

@app.route('/')
def home():
    return render_template('index.html')

# search matched words
@app.route('/search', methods=['POST'])
def search_handler():
    query_str = request.form.get('query', '')
    n = int(request.form.get('n', 10))

    free_text, phrases = process_query(query_str)
    query_string = " ".join(free_text)
    for phrase in phrases:
        query_string += ' "{}"'.format(phrase)

    hits = search(query_string, n=n)
    results = format_results(hits)

    return render_template('results.html', query=query_str, results=results)

# search matched texts
@app.route('/search_text', methods=['POST'])
def search_handler_text():
    query_str = request.form.get('query', '')
    n = int(request.form.get('n', 10))

    free_text, phrases = process_query_text(query_str)
    query_string = " ".join(free_text)
    for phrase in phrases:
        query_string += ' "{}"'.format(phrase)

    hits = search_text(query_string, n=n)
    results = format_results(hits)

    return render_template('results.html', query=query_str, results=results)

# search with ambiguity
@app.route('/search_amb', methods=['POST'])  # add ambiguous matching
def search_handler_amb():
    query_str = request.form.get('query', '')
    n = int(request.form.get('n', 10))

    free_text, phrases = process_query_amb(query_str)
    query_string = " ".join(free_text)
    for phrase in phrases:
        query_string += ' "{}"'.format(phrase)

    hits = search_amb(query_string, n=n)
    results = format_results(hits)

    return render_template('results.html', query=query_str, results=results)

# search by stemming
@app.route('/search_stem', methods=['POST'])  # add stemming option
def search_handler_stem():
    query_str = request.form.get('query', '')
    n = int(request.form.get('n', 10))

    free_text, phrases = process_query_stem(query_str)
    query_string = " ".join(free_text)
    for phrase in phrases:
        query_string += ' "{}"'.format(phrase)

    hits = search_stem(query_string, n=n)
    results = format_results(hits)

    return render_template('results.html', query=query_str, results=results)

# build index
@app.route('/build-index', methods=['POST'])
def build_index():
    build_idx.create_index()
    return render_template('built.html')

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


# -*- coding: utf-8 -*-
"""
Created on Wed Feb 26 09:23:59 2020

@author: Administrator
"""

"""
不使用^操作实现异或运算.
"""

def xor(x , y):
    bx = bin(x)[2:]
    by = bin(y)[2:]
    obres = '' ; i = 0
    while i < len(bx) and i <len(by):
        if bx[len(bx) - 1 - i] == by[len(by) - 1 - i]:
            obres = '0' + obres
        else:
            obres = '1' + obres
        i += 1
    if i == len(bx) and i == len(by):
        return (int(obres , 2))
    elif i == len(bx) and i < len(by):
        for j in range(i , len(by)):
            if by[len(by) - 1 - j] == '0':
                obres = '0' + obres
            else:
                obres = '1' + obres
        return (int(obres , 2))
    elif i == len(by) and i < len(bx):
        for j in range(i , len(bx)):
            if bx[len(bx) - 1 - j] == '0':
                obres = '0' + obres
            else:
                obres = '1' + obres
        return (int(obres , 2))

if __name__ == "__main__":
    x = 3 ; y = 5
    print(x , " ^ " , y," is : " , xor(x , y))

python算法/6.14如何不使用^操作实现异或运算.py

6.14如何不使用^操作实现异或运算.py


import sys
import os

from xlog import getLogger

xlog = getLogger("launcher")

current_path = os.path.dirname(os.path.abspath(__file__))
default_path = os.path.abspath(os.path.join(current_path, os.pardir))

import global_var

if sys.platform.startswith("linux"):
    if os.path.isfile("/system/bin/dalvikvm") or os.path.isfile("/system/bin/dalvikvm64") or \
            "android.googlesource.com" in sys.version:
        xlog.info("This is Android")
        has_desktop = False
        platform = "android"
        platform_lib = ""

        def show_systray():
            from non_tray import sys_tray
            sys_tray.serve_forever()

        def on_quit():
            sys_tray.on_quit()

    else:
        def X_is_running():
            try:
                from subprocess import Popen, PIPE
                p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE)
                p.communicate()
                return p.returncode == 0
            except:
                return False

        def has_gi():
            try:
                import gi
                gi.require_version('Gtk', '3.0')
                from gi.repository import Gtk as gtk
                return True
            except Exception as e:
                xlog.warn("load gi fail:%r, SysTray will not show.", e)
                return False

        def has_pygtk():
            try:
                import pygtk
                pygtk.require('2.0')
                import gtk
                return True
            except:
                return False

        platform = "linux"
        platform_lib = os.path.join(default_path, 'lib', 'linux')
        sys.path.append(platform_lib)

        if X_is_running() and (has_pygtk() or has_gi()):
            has_desktop = True
        else:
            has_desktop = False

        def show_systray():
            global sys_tray
            if has_desktop:
                try:
                    from gtk_tray import sys_tray
                except:
                    from non_tray import sys_tray
            else:
                from non_tray import sys_tray

            sys_tray.serve_forever()

        def on_quit():
            global sys_tray
            if has_desktop:
                from gtk_tray import sys_tray
            sys_tray.on_quit()

elif sys.platform == "win32":
    has_desktop = True

    platform = "windows"
    platform_lib = os.path.join(default_path, 'lib', 'win32')
    sys.path.append(platform_lib)

    def show_systray():
        from win_tray import sys_tray
        sys_tray.serve_forever()

    def on_quit():
        from win_tray import sys_tray
        sys_tray.on_quit()

elif sys.platform == "darwin":
    has_desktop = True
    platform = "mac"
    platform_lib = os.path.abspath(os.path.join(default_path, 'lib', 'darwin'))
    sys.path.append(platform_lib)

    extra_lib = "/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjc"
    sys.path.append(extra_lib)

    def show_systray():
        global sys_tray
        try:
            import mac_tray as sys_tray
        except Exception as e:
            xlog.warn("import mac_tray except:%r, Please try run 'sudo pip3 install -U PyObjC Pillow' by yourself.", e)
            from non_tray import sys_tray
        sys_tray.serve_forever()

    def on_quit():
        global sys_tray
        sys_tray.on_quit()

elif sys.platform == "ios":
    xlog.info("This is iOS")
    has_desktop = False
    platform = "ios"
    platform_lib = ""

    import time
    import gc
    gc.set_threshold(200, 12, 12)

    def show_systray():
        while global_var.running:
            time.sleep(30)
            count = gc.get_count()
            c = gc.collect()
            xlog.debug("GC: count: %d,%d,%d Collect:%d", count[0], count[1], count[2], c)

    def on_quit():
        from non_tray import sys_tray
        sys_tray.on_quit()

else:
    xlog.warn(("detect platform fail:%s" % sys.platform))

    platform = "unknown"
    has_desktop = False
    platform_lib = ""
    from non_tray import sys_tray

    def show_systray():
        sys_tray.serve_forever()

    def on_quit():
        sys_tray.on_quit()


from os.path import dirname

class Properties(object):
	def readFromFile(self):
		routes_lst = []

		fname = dirname(__file__) + '/routes.conf'
		fname = fname.replace('router', 'conf')

		with open(fname, 'r') as stream:
			for line in stream:
				routes_lst.append(line.rstrip('\n'))
		return routes_lst


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

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

    def delete_end(self):
        if self.head is None:
            print ('empty list')
        temp = self.head.next
        prev = self.head
        while temp.next !=  None:
            temp = temp.next
            prev = prev.next
        prev.next = None # break the link of previous

    def traverse(self):
        if self.head is None:
            print('list is empty')
        temp = self.head
        while temp != None :
            print(temp.data)

            temp = temp.next

n = Node(10)
n1 = Node(104)
n2 = Node(103)
n3 = Node(120)
n4 = Node(110)

s = SLL()
s.head = n
n.next = n1
n1.next = n2
n2.next = n3
n3.next = n4

s.delete_end()
s.traverse()

# Output
# 10
# 104
# 103
# 120


import pandas as pd

def read_data(filename):
    NetworkData = pd.read_excel(filename, sheet_name='NetworkData')
    Line = [NetworkData.loc[i,'Unnamed: 0'] for i in NetworkData.index]
    Bus = set(list(NetworkData.FROM.unique()) + list(NetworkData.TO.unique()))
    X = {Line[i]: NetworkData.loc[i,'X'] for i in NetworkData.index}
    Capacity = {Line[i]: NetworkData.loc[i,'Capacity'] for i in NetworkData.index}

    WindGeneration = pd.read_excel(filename, sheet_name='WindGeneration')
    WindParks = pd.read_excel(filename, sheet_name='WindParks')
    T = [WindGeneration.loc[i,'Unnamed: 0'] for i in WindGeneration.index]
    W = [WindParks.loc[i,'Unnamed: 0'] for i in WindParks.index]
    W_G = {(j,WindGeneration.loc[i,'Unnamed: 0']): WindGeneration.loc[i,j] for i in WindGeneration.index for j in WindGeneration.columns[1:]}

    PVGeneration = pd.read_excel(filename, sheet_name='PVGeneration')
    PVParks = pd.read_excel(filename, sheet_name='PVParks')
    PV = [PVParks.loc[i,'Unnamed: 0'] for i in PVParks.index]
    PV_G = {(j,PVGeneration.loc[i,'Unnamed: 0']): PVGeneration.loc[i,j] for i in PVGeneration.index for j in PVGeneration.columns[1:]}

    StorageSystems = pd.read_excel(filename, sheet_name='StorageSystems')
    ESS = [StorageSystems.loc[i,'Unnamed: 0'] for i in StorageSystems.index]
    ESS_pmax = {ESS[i]: StorageSystems.loc[i,'Power'] for i in StorageSystems.index}
    ESS_energy = {ESS[i]: StorageSystems.loc[i,'Energy'] for i in StorageSystems.index}
    ESS_SOEini= {ESS[i]: StorageSystems.loc[i,'SOEini'] for i in StorageSystems.index}
    ESS_eff= {ESS[i]: StorageSystems.loc[i,'Eff'] for i in StorageSystems.index}
    ESS_loc= {ESS[i]: StorageSystems.loc[i,'Location'] for i in StorageSystems.index}

    SystemDemand = pd.read_excel(filename, sheet_name='SystemDemand')
    Loads = pd.read_excel(filename, sheet_name='Loads')
    Demand = {(j, SystemDemand.loc[i,'Unnamed: 0']): SystemDemand.loc[i,j] for i in SystemDemand.index for j in SystemDemand.columns[1:]}
    Load = [Loads.loc[i,'Unnamed: 0'] for i in Loads.index]

    Generators = pd.read_excel(filename, sheet_name='Generators')
    G = [Generators.loc[i, 'Unnamed: 0'] for i in Generators.index]
    G_pmax = {G[i]: Generators.loc[i,'Pmax'] for i in Generators.index}
    G_pmin = {G[i]: Generators.loc[i,'Pmin'] for i in Generators.index}
    G_SUC = {G[i]: Generators.loc[i,'SUC'] for i in Generators.index}
    G_SDC = {G[i]: Generators.loc[i,'SDC'] for i in Generators.index}
    G_RU = {G[i]: Generators.loc[i,'RU'] for i in Generators.index}
    G_RD = {G[i]: Generators.loc[i,'RD'] for i in Generators.index}
    G_uini = {G[i]: Generators.loc[i,'uini'] for i in Generators.index}
    G_pini = {G[i]: Generators.loc[i,'Pini'] for i in Generators.index}
    G_loc = {G[i]: Generators.loc[i,'Location'] for i in Generators.index}

    GeneratorStepSize = pd.read_excel(filename, sheet_name='GeneratorStepSize')
    G_B = [i for i in GeneratorStepSize.columns[1:]]
    G_Bpmax = {(Generators.loc[i,'Unnamed: 0'], j): GeneratorStepSize.loc[i,j] for i in GeneratorStepSize.index for j in GeneratorStepSize.columns[1:]}

    GeneratorStepCost = pd.read_excel(filename, sheet_name='GeneratorStepCost')
    G_Bcost = {(GeneratorStepCost.loc[i,'Unnamed: 0'],j): GeneratorStepCost.loc[i,j] for i in GeneratorStepCost.index for j in GeneratorStepCost.columns[1:]}

    orginal_data = [Line, Bus, X, Capacity, T, W, W_G, PV, PV_G, ESS, ESS_pmax, ESS_energy, ESS_SOEini, ESS_eff, ESS_loc, Demand, G, G_pmax, G_pmin, G_SUC,
    G_SDC, G_RU, G_RD, G_uini, G_pini, G_loc, G_B, G_Bpmax, G_Bcost, Load]

    return orginal_data


# Class used to create diseases
class Afflictions():
    def __init__(self, name, chance_to_infect, infectivity, prime_season, health_change, recovery_time):
        self.name = name
        self.chance_to_infect = chance_to_infect
        self.infectivity = infectivity
        self.prime_season = prime_season
        self.health_change = health_change
        self.recovery_time = recovery_time

    # Sets equality to self.name
    def __eq__(self, other):
        if isinstance(other, self.__class__):
            return self.name == other.name
        else:
            return False

    # Sets the inequality
    def __ne__(self, other):
        return not __eq__(self, other)


# Selected reproductions of full page illustrations from the book "Trick Eyes" (2002) by Akiyoshi Kitaoka

# "A Snake" spiral illusion appears on page 9
# reference image: http://www.psy.ritsumei.ac.jp/~akitaoka/hebis.jpg

output_name = "snake_1"
irad_1_ratio = 37/312.0
orad_1_ratio = 47.5/312.0
detail = 4
stripes = 18*2*detail
red_color = color(151,4,102)
white_color = color(255)
bg_color = color(200)

def setup():
    size(1024,1024)
    noLoop()

def draw():
    background(bg_color)
    nbr_rings = 0
    irad = width*irad_1_ratio*0.5
    orad = width*orad_1_ratio*0.5
    pushMatrix()
    translate(width/2,height/2)
    noStroke()
    while nbr_rings < 5:
        nbr_rings += 1
        # draw stuff
        strokeWeight(1)
        for s in xrange(stripes):
            fill(red_color if s/detail % 2 > 0 else white_color)
            stroke(red_color if s/detail % 2 > 0 else white_color)
            # noStroke()
            ang1 = s*TWO_PI/stripes
            ang2 = (s+1)*TWO_PI/stripes
            beginShape()
            vertex(cos(ang1)*irad,sin(ang1)*irad)
            vertex(cos(ang1)*orad,sin(ang1)*orad)
            vertex(cos(ang2)*orad,sin(ang2)*orad)
            vertex(cos(ang2)*irad,sin(ang2)*irad)
            endShape(CLOSE)
        noFill()
        sweight = width*2.5/624.0
        strokeWeight(sweight)
        strokeCap(PROJECT)
        for s in xrange(stripes):
            stroke(red_color if s/detail % 2 > 0 else white_color)
            aoffset = detail*PI/stripes
            ang1 = s*TWO_PI/stripes
            ang2 = (s+1)*TWO_PI/stripes
            irad2 = irad+sweight*.4
            orad2 = orad-sweight*.4
            line(cos(ang1+aoffset)*irad2,sin(ang1+aoffset)*irad2,cos(ang2+aoffset)*irad2,sin(ang2+aoffset)*irad2)
            line(cos(ang1-aoffset)*orad2,sin(ang1-aoffset)*orad2,cos(ang2-aoffset)*orad2,sin(ang2-aoffset)*orad2)

        irad = orad+(orad-irad)
        orad = irad*orad_1_ratio/irad_1_ratio
    popMatrix()
    saveFrame("../output/" + output_name + ".png")


import os
from setuptools import setup, find_packages

runtime_dependencies = [
]

build_dependencies = [
    'wheel',
]

dev_dependencies = build_dependencies + [
    'pylint',
    'flake8',
    'flake8-docstrings',
    'pytest',
    'pytest-cov',
    'pytest-html',
    'pytest-xdist',
    'coverage',
]

setup(
    name='pydoit-project-builder',
    version='0.1.0',
    author='Loïc Schneider',
    description='Templates to be used when creating projects.',
    long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
    license='Apache 2',
    url='https://github.com/schneiderlo/pydoit-project-builder',
    packages=find_packages(exclude=['tests*']),
    include_package_data=True,
    setup_requires=build_dependencies,
    install_requires=runtime_dependencies,
    extras_require={
        'dev': dev_dependencies
    }
)