# -*- coding: utf-8 -*-
"""
Created on Sat Dec 15 19:58:26 2018

@author: David Gaviria
"""

#%%
import folium
map = folium.Map(
    location=[45.372, -121.6972],
    zoom_start=12,
    tiles='Mapbox Bright'
)

map.save('map.html')


# Quiz 7: Write a Python program that prints out the number of minutes in seven weeks.
print (7 * 7 * 24 * 60)
# Quiz 14:Write Python code to print out how far light travels
print(299792458 * 100 * 1.0/1000000000)
# Quiz 18: Given the variables defined here, write Python
# code that prints out the distance, in meters,
# that light travels in one processor cycle.
speed_of_light = 299792458.0
cycles_per_second = 2700000000.0
print(speed_of_light/cycles_per_second)
# Quiz 22: Write python code that defines the variable
# age to be your age in years, and then prints
# out the number of days you have been alive
age = 42
print (age * 365)
# Quiz 26: Define a variable, name, and assign to it a string that is your name.
name = 'Saret Magnoslove'
# Quiz 31: Write Python code that prints out Udacity (with a capital U),
# given the definition of s below.
s = 'audacity'
print ('U' + s[2:])
# Quiz 39: Write Python code that initializes the variable
# start_link to be the value of the position
# where the first '<a href=' occurs in a page.
page = '''

 '''
start_link = page.find('<a href="')

# final Quiz!

# Write Python code that assigns to the
# variable url a string that is the value
# of the first URL that appears in a link
# tag in the string page.
# Your code should print http://udacity.com
# Make sure that if page were changed to

# page = 'Hello world'

# that your code still assigns the same value to the variable 'url',
# and therefore still prints the same thing.

# page = contents of a web page
page =('

'
'
')
start_link = page.find('<a href=')
start_url = start_link + 9
end_url = page.find('"',start_url)
url = page[start_url:end_url]
print (url)


#!/usr/bin/env python3.8

import rospy
from std_msgs.msg import Bool
from kivymd.app import MDApp
from kivy.lang import Builder
from jkprobot.msg import Ardubot

class TutorialApp(MDApp):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.slider_base_angle = 90
        self.slider_waist_angle = 90
        self.slider_shoulder_angle = 90

        self.screen = Builder.load_file('ros_gui.kv')

    def build(self, *args):
        return self.screen

    def my_function(self, *args):
        print('Botao pressionado!')

        self.screen.ids.my_label.text = 'Botao pressionado'

        msg = Ardubot() #Create a Ardubot message object
        msg.base_deg = self.slider_base_angle # base
        msg.waist_deg = self.slider_waist_angle # cintura
        msg.shoulder_deg = self.slider_shoulder_angle # ombro

        pub.publish(msg)

    def slider_base_function(self, slider_base_value):
        self.slider_base_angle = int(slider_base_value)
        print(self.slider_base_angle)

    def slider_waist_function(self, slider_waist_value):
        self.slider_waist_angle = int(slider_waist_value)
        print(self.slider_waist_angle)

    def slider_shoulder_function(self, slider_shoulder_value):
        self.slider_shoulder_angle = int(slider_shoulder_value)
        print(self.slider_shoulder_angle)

if __name__=='__main__':

    pub = rospy.Publisher('/button', Ardubot, queue_size=1)

    rospy.init_node('simple_gui',anonymous=True)

    TutorialApp().run()


from support import check_result, read_file, timing  # type: ignore

def compute(lines: list[str]) -> list[int]:
    calories: list[int] = []
    idx = 0
    prev = 0
    while idx < len(lines):
        if lines[idx] == "":
            calories.append(sum([int(x) for x in lines[prev:idx]]))
            prev = idx + 1
        idx += 1
    return sorted(calories)

@timing()
def part1(lines: list[str]) -> int:
    return compute(lines)[-1]

@timing()
def part2(lines: list[str]):
    return sum(compute(lines)[-3:])

def main() -> int:
    sample = read_file(__file__, "../../input/2022/01/sample.input")
    puzzle = read_file(__file__, "../../input/2022/01/puzzle.input")

    sample.append("")
    puzzle.append("")

    check_result(24000, part1(sample))
    check_result(71924, part1(puzzle))

    check_result(45000, part2(sample))
    check_result(210406, part2(puzzle))

    return 0

if __name__ == "__main__":
    raise SystemExit(main())


from tkinter import *
import tkinter as tk
from urllib.request import urlopen as req
from bs4 import BeautifulSoup as soup
import time
import requests #pip install requests

gui = tk.Tk()
gui.geometry("500x500")
gui.title("รายงาน COVID-19")

p1 = PhotoImage(file = 'covid48x48.png')
gui.iconphoto(False, p1)
# Setting icon of master window
# gui.iconphoto(False, 'covid19.png')
################################################
#function API
r = requests.get("https://covid19.th-stat.com/api/open/today")
data =r.json()

v_result_Con = StringVar()
result_Con = data['Confirmed']#ยอดผู้ป่วย
print(f'ผู้ป่วยยืนยันสะสม: {result_Con}')

v_result_Re = StringVar()
result_Re = data['Recovered']#รักษาหาย
print(f'หายป่วยแล้ว: {result_Re}')

v_result_Hos = StringVar()
result_Hos  = data['Hospitalized']#รับการรักษา
print(f'ผู้ป่วยรักษาอยู่: {result_Hos}')

v_result_De = StringVar()
result_De = data['Deaths'] #ตาย
print(f'เสียชีวิต: {result_De}')

v_result_NewCon = StringVar()
result_NewCon = data['NewConfirmed'] #เพิ่มใหม่
print(f'ผู้ป่วยรายใหม่ในวันนี้: {result_NewCon}')

v_result_ReCon = StringVar()
result_ReCon = data["NewRecovered"]
print(f'เพิ่มขึ้น: {result_ReCon}')

v_result_NewHos = StringVar()
result_NewHos = data['NewHospitalized']
print(f'เข้ารักษาใหม่ : {result_NewHos}')

v_result_NewDe = StringVar()
result_NewDe = data['NewDeaths']
print(f'เสียชีวิตเพิ่ม : {result_NewDe}')

v_Date = StringVar()
Date = data['UpdateDate']
print(f'อัพเดทข้อมูลล่าสุด : {Date}')

################################################
#เพิ่มภาพใน label
background_image = tk.PhotoImage(file='background.png')
background_label = tk.Label(gui, image=background_image)
background_label.place(width=1, height=1)

#-----------------FRAME1 ------------------------------------

##FE5000 สีส้ม
frame1 = tk.Frame(gui, bg='#454545' )#bd=5 กำหนดขอบ
frame1.place(x=2.5, #กำหนดขอบเริ่มต้นแนวนอน
			y=2.5, #กำหนดขอบเริ่มต้นแนวตั้ง
			width=246,  #กำหนดขนาดด้านกว้าง
			height=246) #กำหนดขนาดด้านสูง
#anchor='n' N, E, S, W, NE, NW, SE, or SW,
tk.Label(frame1, text='FRAME1').pack()
#ne-ชิดขวา /nw-ชิดซ้าย /n-กลาง /e-ชิดขวา /s-กลาง /w-ชิดซ้าย /sw-ชิดซ้าย /se=ชิดขวา

#----------------FRAME2-----------------------------------------#

frame2 = tk.Frame(gui, bg='#454545' )#bd=5 กำหนดขอบ
frame2.place(x=246, #กำหนดขอบเริ่มต้นแนวนอน
			y=2.5, #กำหนดขอบเริ่มต้นแนวตั้ง
			width=250,  #กำหนดขนาดด้านกว้าง
			height=250) #กำหนดขนาดด้านสูง
			#anchor='n' N, E, S, W, NE, NW, SE, or SW,
tk.Label(frame2, text='FRAME2').pack()

#----------------FRAME3-----------------------------------------#
frame3 = tk.Frame(gui, bg='#454545' )#bd=5 กำหนดขอบ
frame3.place(x=2.5, #กำหนดขอบเริ่มต้นแนวนอน
			y=246, #กำหนดขอบเริ่มต้นแนวตั้ง
			width=250,  #กำหนดขนาดด้านกว้าง
			height=250) #กำหนดขนาดด้านสูง
			#anchor='n' N, E, S, W, NE, NW, SE, or SW,
tk.Label(frame3, text='FRAME3').pack()

#----------------FRAME4-----------------------------------------#
frame4 = tk.Frame(gui, bg='#454545')#bd=5 กำหนดขอบ
frame4.place(x=246, #กำหนดขอบเริ่มต้นแนวนอน
			y=246, #กำหนดขอบเริ่มต้นแนวตั้ง
			width=250,  #กำหนดขนาดด้านกว้าง
			height=250) #กำหนดขนาดด้านสูง
			#anchor='n' N, E, S, W, NE, NW, SE, or SW,
#tk.Label(frame4, text='FRAME4').pack()

#--------------------LABEL1---------------------------------#
#bg='MediumSlateBlue'สีม่วงอ่อน
AL1 = tk.Label(frame1, text="ผู้ป่วยรายใหม่ในวันนี้",
				bg='#454545', font=('Tahoma', 12), fg='white')
AL1.place(width=250, height=25, x=0, y=0)

v_result_NewCon.set(f' {result_NewCon}')#ส่งออกแสดวผล frame1
BL1 = tk.Label(frame1, textvar=v_result_NewCon,  font=('Tahoma', 40, 'bold'),
					 bg='red', fg='white')##FE5000 สีส้ม
BL1.place(width=246, height=96, x=2, y=27)#663399 สีม่วง
##FE5000 สีส้ม

CL1 = tk.Label(frame1, text="จำนวน", font=('Tahoma', 12),
					 bg='#5DADE2', fg='black')
CL1.place(width=170, height=25, y=125, x=0)
CL11 = tk.Label(frame1, text="ราย", font=('Tahoma', 12),
					 bg='#5DADE2', fg='black')
CL11.place(width=80, height=25, y=125, x=170)

DL1 = tk.Label(frame1, text="ติดเชื้อภายในประเทศ", font=('Tahoma', 10),
					 bg='MediumSlateBlue', fg='white')
DL1.place(width=170, height=25, y=150)

EL1 = tk.Label(frame1, text="172", font=('Tahoma', 12),
					 bg='#663399', fg='white')
EL1.place(width=80, height=25, x=170, y=150)

FL1 = tk.Label(frame1, text="ผู้เดินทางไม่เข้า\nสถานที่กักกัน", font=('Tahoma', 8),
					 bg='#5DADE2', fg='black')
FL1.place(width=125, height=25, x=0, y=175)
FL11 = tk.Label(frame1, text="สถานที่กักกัน\nที่รัฐจัดให้", font=('Tahoma', 8),
					 bg='#5DADE2', fg='black')
FL11.place(width=125, height=25, x=125, y=175)

GL1 = tk.Label(frame1, text="-", font=('Tahoma', 25,'bold'),
					 bg='#FE5000', fg='white')
GL1.place(width=120, height=45, x=3, y=204)
GL11 = tk.Label(frame1, text="13", font=('Tahoma', 25,'bold'),
					 bg='#FE5000', fg='white',bd=10)
GL11.place(width=120, height=45, x=128, y=204)
#--------------------LABEL2---------------------------------#

AL2 = tk.Label(frame2, text="ผู้ป่วยยืนยันสะสม",
				bg='#454545', font=('Tahoma', 12), fg='white')
AL2.place(width=250, height=25, x=0, y=0)

#v_result_Con รับข้อมูลจาก data
v_result_Con.set(f' {result_Con}')#ส่งออกแสดงผล frame2
BL2 = tk.Label(frame2, textvar=v_result_Con,  font=('Tahoma', 40, 'bold'),
					 bg='#FE5000', fg='white')
BL2.place(width=246, height=96, x=2, y=27)

CL2 = tk.Label(frame2, text="ติดเชื้อภายในประเทศ", font=('Tahoma', 10),
					 bg='#5DADE2', fg='black')
CL2.place(width=170, height=25, y=125, x=0)
CL22 = tk.Label(frame2, text="4,869", font=('Tahoma', 12),
					 bg='#5DADE2', fg='black')
CL22.place(width=80, height=25, y=125, x=170)

DL22 = tk.Label(frame2, text="ติดเชื้อในแรงงานต่างด้าว\n(คัดกรองเชิงรุก)", font=('Tahoma', 8),
					 bg='MediumSlateBlue', fg='white')
DL22.place(width=170, height=25, y=150)

EL2 = tk.Label(frame2, text="1,392", font=('Tahoma', 12),
					 bg='#663399', fg='white')
EL2.place(width=80, height=25, x=170, y=150)

FL2 = tk.Label(frame2, text="ผู้เดินทางมาจากต่างประเทศ", font=('Tahoma', 8),
					 bg='#5DADE2', fg='black')
FL2.place(width=125, height=25, x=0, y=175)
FL22 = tk.Label(frame2, text="สถานที่กักกันที่รัฐจัดให้", font=('Tahoma', 8),
					 bg='#5DADE2', fg='black')
FL22.place(width=125, height=25, x=125, y=175)

GL2 = tk.Label(frame2, text="2,015", font=('Tahoma', 25,'bold'),
					 bg='#FE5000', fg='white')
GL2.place(width=120, height=45, x=2, y=204)
GL22 = tk.Label(frame2, text="1,481", font=('Tahoma', 25,'bold'),
					 bg='#FE5000', fg='white',bd=10)
GL22.place(width=120, height=45, x=127, y=204)

#--------------------LABEL3---------------------------------#

AL3 = tk.Label(frame3, text="หายป่วยแล้ว",
				bg='#3CB371', font=('Tahoma', 15), fg='black')
AL3.place(width=250, height=25, x=0, y=0)

v_result_Re.set(f' {result_Re}')
BL3 = tk.Label(frame3, textvar=v_result_Re,  font=('Tahoma', 40, 'bold'),
					 bg='#006400', fg='white')
BL3.place(width=250, height=100, x=0, y=25)
#-----------------------
CL3 = tk.Label(frame3, text="จำนวน", font=('Tahoma', 12),
					 bg='#3CB371', fg='black')
CL3.place(width=170, height=25, y=125, x=0)
CL33 = tk.Label(frame3, text="ราย", font=('Tahoma', 12),
					 bg='#3CB371', fg='black')
CL33.place(width=80, height=25, y=125, x=170)

DL3 = tk.Label(frame3, text="ผู้ป่วยรักษาอยู่", font=('Tahoma', 10),
					 bg='green', fg='white')
DL3.place(width=170, height=25, y=150)

#v_result_Hos ผู้ป่วยรักษาอยู่
v_result_Hos.set(f'  {result_Hos}')
EL3 = tk.Label(frame3, textvar=v_result_Hos, font=('Tahoma', 15, 'bold'),
					 bg='green', fg='white')
EL3.place(width=80, height=25, x=170, y=150)

#-----------------------
FL3 = tk.Label(frame3, text="เพิ่มขึ้น", font=('Tahoma', 10),
					 bg='#3CB371', fg='black')
FL3.place(width=125, height=25, x=0, y=175)
FL33 = tk.Label(frame3, text="เข้ารักษาใหม่", font=('Tahoma', 8),
					 bg='#3CB371', fg='black')
FL33.place(width=125, height=25, x=125, y=175)

#v_result_ReCon เพิ่มขึ้น
v_result_ReCon.set(f'  {result_ReCon}')
GL3 = tk.Label(frame3, textvar=v_result_ReCon, font=('Tahoma', 15,'bold'),
					 bg='green', fg='white')
GL3.place(width=120, height=45, x=2, y=204)

#v_result_NewHos เข้ารักษาใหม่
v_result_NewHos.set(f' {result_NewHos}')
GL33 = tk.Label(frame3, textvar=v_result_NewHos, font=('Tahoma', 15,'bold'),
					 bg='green', fg='white',bd=10)
GL33.place(width=120, height=45, x=127, y=204)

#--------------------LABEL4---------------------------------#

AL3 = tk.Label(frame4, text="เสียชีวิต",
				bg='black', font=('Tahoma', 15), fg='white')
AL3.place(width=125, height=30, x=0, y=0)
AL33 = tk.Label(frame4, text="เสียชีวิตเพิ่ม",
				bg='black', font=('Tahoma', 15), fg='white')
AL33.place(width=125, height=30, x=125, y=0)

#v_result_De เสียชีวิต
v_result_De.set(f'  {result_De}')
BL3 = tk.Label(frame4, textvar=v_result_De,  font=('Tahoma', 40, 'bold'),
					 bg='black', fg='white')
BL3.place(width=125, height=100, x=0, y=25)

#v_result_NewDe เสียชีวิตเพิ่ม
v_result_NewDe.set(f'  {result_NewDe}')
BL33 = tk.Label(frame4, textvar=v_result_NewDe,  font=('Tahoma', 40, 'bold'),
					 bg='black', fg='white')
BL33.place(width=125, height=100, x=125, y=25)

CL3 = tk.Label(frame4, text="อัพเดทข้อมูลล่าสุด",
				bg='#454545', font=('Tahoma', 12), fg='white')
CL3.place(width=250, height=30, x=0, y=150)

#v_Date อัพเดทข้อมูลล่าสุด
v_Date.set(f'  {Date}')
DL3 = tk.Label(frame4, textvar=v_Date,
				bg='#454545', font=('Tahoma', 12), fg='white')
DL3.place(width=250, height=30, x=0, y=180)
#-----------------------

gui.mainloop()


# -*- coding: utf-8 -*-
"""
Created on Sat Jan 13 17:29:54 2018

@author: alfaceor
"""
import numpy as np
import matplotlib.pyplot as plt
import os

class SimulData:
  def __init__(self):
    self.strF2B     = "" #strF2B
    self.strB2F     = "" #strB2F
    self.strB2B     = "" #strB2B
    self.strHrad    = "" #strHrad
    self.strBrad    = "" #strBrad
    self.strNtrials = "" #strNtrials
    self.flnPrefix  = "" #"rw3D_RegularPorousDepletion"
    self.arguments  = "" #" --pF2B "+self.strF2B+" --pB2F "+self.strB2F+" --pB2B "+self.strB2B+" --Hradius "+self.strHrad+" --Bradius "+self.strBrad
    self.qsubArgs   = ""
    self.netFile    = "" #self.flnPrefix+"_F2B_"+self.strF2B+"__B2F_"+self.strB2F+"__B2B_"+self.strB2B+"__Hrad_"+self.strHrad+"__Brad_"+self.strBrad+".net"
    self.dataFile   = "" #flnPrefix+"_F2B_"+strF2B+"__B2F_"+strB2F+"__B2B_"+strB2B+"__Hrad_"+strHrad+"__Brad_"+strBrad+"__nt_"+strNtrials+".dat"
    self.path       = ""

    # Converted values
    self.pF2B       = -1 #float(strF2B)
    self.pB2F       = -1 #float(strB2F)
    self.pB2B       = -1 #float(strB2B)
    self.Hrad       = -1 #float(strHrad)
    self.Brad       = -1 #float(strBrad)
    self.Ntrials    = -1 #int  (strNtrials)

    #calculated values
    #data             = [] #np.loadtxt(self.dataFile)
    self.ttime       = [] #data[:,0]
    self.DelR2       = [] #data[:,7]
    self.ttimeLambda = []
    self.EffecDiff   = []

    # FIT DATA
    self.fitparams = None
    self.tmin      = -1 #0
    self.tmax      = -1 #len(self.ttime)
    self.imin      = -1 #0
    self.imax      = -1 #len(self.ttime)
    self.DiffCoeff = -1 #0.0
    self.D_err_min = -1
    self.D_err_max = -1
    self.popt      = []
    self.pcov      = []

    # Fabio Method
    self.lambFlag  = False
    self.strLamb1  = ""
    self.strLamb2  = ""
    self.strLamb3  = ""
    self.lamb1     = -1
    self.lamb2     = -1
    self.lamb3     = -1
    self.DiffLamb1 = -1
    self.DiffLamb2 = -1
    self.DiffLamb3 = -1

  def metadata(self, flnPrefix, strF2B, strB2F, strB2B, strHrad, strBrad, strNtrials, loadData=False):
    self.flnPrefix  = flnPrefix
    self.strF2B     = strF2B
    self.strB2F     = strB2F
    self.strB2B     = strB2B
    self.strHrad    = strHrad
    self.strBrad    = strBrad
    self.strNtrials = strNtrials

    self.convertStrParams()
    self.defineFiles()
    if (loadData == True):
      self.getData()

  def metadataFromCSVentry(self, flnPrefix, csv_entry):
    self.flnPrefix  = flnPrefix
    self.strF2B     = csv_entry["strF2B"    ]
    self.strB2F     = csv_entry["strB2F"    ]
    self.strB2B     = csv_entry["strB2B"    ]
    self.strHrad    = csv_entry["strHrad"   ]
    self.strBrad    = csv_entry["strBrad"   ]
    self.strNtrials = csv_entry["strNtrials"]

    self.convertStrParams()
    self.defineFiles()

  def convertStrParams(self):
    self.pF2B       = float(self.strF2B)
    self.pB2F       = float(self.strB2F)
    self.pB2B       = float(self.strB2B)
    self.Hrad       = int  (self.strHrad)
    self.Brad       = int  (self.strBrad)
    self.Ntrials    = int  (self.strNtrials)

  def defineFiles(self):
    self.arguments  = " --pF2B "+self.strF2B+" --pB2F "+self.strB2F+" --pB2B "+self.strB2B+" --Hradius "+self.strHrad+" --Bradius "+self.strBrad
    self.netFile    = self.flnPrefix+"_F2B_"+self.strF2B+"__B2F_"+self.strB2F+"__B2B_"+self.strB2B+"__Hrad_"+self.strHrad+"__Brad_"+self.strBrad+".net"
    self.dataFile   = self.flnPrefix+"_F2B_"+self.strF2B+"__B2F_"+self.strB2F+"__B2B_"+self.strB2B+"__Hrad_"+self.strHrad+"__Brad_"+self.strBrad+"__nt_"+self.strNtrials+".dat"
    self.qsubArgs  =" -v F2B="+self.strF2B+",B2F="+self.strB2F+",B2B="+self.strB2B+",Hrad="+self.strHrad+",Brad="+self.strBrad

  def getData(self):
    #self.defineFiles()
    #calculated values
    data       = np.loadtxt(self.dataFile)
    self.ttime = data[:,0]
    self.DelR2 = data[:,7]

    # FIT DATA
    self.tmin  = 0
    self.tmax  = len(self.ttime)
    self.DiffCoeff  = 0.0
    self.popt  = []
    self.pcov  = []

  def isDone(self):
    self.defineFiles()
    if os.path.isfile(self.dataFile) :
      return True  #program+" "+self.arguments # "JOB TO RUN
    else:
      if os.path.isfile(self.netFile) :
        return  True #"echo JOB is RUNNING OR IMCOMPLETE!!"
      else:
        return False # "echo JOB is DONE"

  def isDatafile(self):
    self.defineFiles()
    if os.path.isfile(self.dataFile) :
      return True  #program+" "+self.arguments # "JOB TO RUN
    else:
      return False # "echo JOB is DONE"

  def getCMD(self, program):
    self.defineFiles()
    if os.path.isfile(self.netFile) :
      if os.path.isfile(self.dataFile) :
        return  "echo JOB is DONE"
      else:
        return "echo JOB is probabibly RUNNING OR IMCOMPLETE!!"
    else:
      return program+" "+self.arguments # "echo JOB TO SUBMIT!!!"

  def calcDiffCoeff(self, fitparams):
    self.getData()
    self.fitparams = fitparams
    tmin, tmax     = fitparams["fitrange"]
    self.imin, self.imax     = getLimits(self.ttime, tmin, tmax)
    self.popt, self.pcov = curve_fit(line, self.ttime[self.imin:self.imax], self.DelR2[self.imin:self.imax])
    self.DiffCoeff = self.popt[0]/6.0
    self.D_err_min = 0.5*self.pcov[0][0]/6.0#D_aux.mean() - D_aux.min()
    self.D_err_max = 0.5*self.pcov[0][0]/6.0#D_aux.mean() - D_aux.min()

  def calcDwithLamb(self, fitparams, colorcito, titulo):
    self.calcDiffCoeff(fitparams)
    #fitparams
    tmin, tmax     =  fitparams["fitrange"]
    imin, imax     =  getLimits(self.ttime, tmin, tmax)
    self.lamb1     =  fitparams["lamb1"]
    self.lamb2     =  fitparams["lamb2"]
    self.lamb3     =  fitparams["lamb3"]
    self.strLamb1  =  str(self.lamb1)
    self.strLamb2  =  str(self.lamb2)
    self.strLamb3  =  str(self.lamb3)
    EffecDiff      =  self.DelR2[imin:imax]/(6.*self.ttime[imin:imax])
    # lambda 1
    ttimeLambda1 = 1./self.ttime[imin:imax]**self.lamb1
    ttimeLambda2 = 1./self.ttime[imin:imax]**self.lamb2
    ttimeLambda3 = 1./self.ttime[imin:imax]**self.lamb3

    popt, pcov = fitLine(ttimeLambda1,EffecDiff)
    slope1 = popt[0]
    self.DiffLamb1 = popt[1]
    popt, pcov = fitLine(ttimeLambda2,EffecDiff)
    slope2 = popt[0]
    self.DiffLamb2 = popt[1]
    popt, pcov = fitLine(ttimeLambda3,EffecDiff)
    slope3 = popt[0]
    self.DiffLamb3 = popt[1]

    D_aux = np.array([self.DiffCoeff, self.DiffLamb1, self.DiffLamb2, self.DiffLamb3])
    self.D_err_min = D_aux.mean() - D_aux.min()
    self.D_err_max = D_aux.max()  - D_aux.mean()

    # plot the lambdas
    fig, ax = plt.subplots(2,2, figsize=(8,6))
    fig.suptitle(titulo)
    axR2    = ax[0][0]
    axDiff1 = ax[0][1]
    axDiff2 = ax[1][0]
    axDiff3 = ax[1][1]

    axR2   .tick_params(axis='both', labelsize=10)
    axDiff1.tick_params(axis='both', labelsize=10)
    axDiff2.tick_params(axis='both', labelsize=10)
    axDiff3.tick_params(axis='both', labelsize=10)

    axR2.set_xscale("log")
    axR2.set_yscale("log")
    axR2.tick_params(axis='x', labelsize=10)
    axR2.tick_params(axis='y', labelsize=10)

    axR2.plot(self.ttime, self.DelR2, linewidth=0,  color='b', marker="o", markersize=1)
    axR2.plot(self.ttime[imin:imax], line(self.ttime[imin:imax], self.popt[0], self.popt[1]), '--', color='k' )

    linea, = axR2. plot(self.ttime, self.ttime , '--', linewidth=2, color='r', alpha=0.5 )
    dr = DraggableLogLogLine(linea)
    dr.connect()

    Y1 = D_aux.min()   *np.ones(len(ttimeLambda1))
    Y2 = D_aux.max()   *np.ones(len(ttimeLambda1))
    XX = np.linspace(0, ttimeLambda1.max(), num=len(ttimeLambda1))
    axDiff1.fill_between(XX, Y1, Y2, facecolor="white", alpha=0.5, hatch="x", edgecolor='g', linestyle='dashed')
    XX = np.linspace(0, ttimeLambda2.max(), num=len(ttimeLambda2))
    axDiff2.fill_between(XX, Y1, Y2, facecolor="white", alpha=0.5, hatch="x", edgecolor='g', linestyle='dashed')
    XX = np.linspace(0, ttimeLambda3.max(), num=len(ttimeLambda3))
    axDiff3.fill_between(XX, Y1, Y2, facecolor="white", alpha=0.5, hatch="x", edgecolor='g', linestyle='dashed')

    axDiff1.set_xlabel("$ t^{-"+self.strLamb1+"}$")
    axDiff1.ticklabel_format( useMathText=True, style='sci', axis='both', scilimits=(0,0) )
    axDiff1.plot(ttimeLambda1, EffecDiff, color=colorcito, marker='o' )
    XX = np.linspace(0,ttimeLambda1.max(), num=100 )
    axDiff1.plot(XX, line(XX, slope1, self.DiffLamb1), '--', color='k' )
    axDiff1.axhline(y=self.DiffCoeff, color='k')

    axDiff2.set_xlabel("$ t^{-"+self.strLamb2+"}$")
    axDiff2.ticklabel_format( useMathText=True, style='sci', axis='both', scilimits=(0,0) )
    axDiff2.plot(ttimeLambda2, EffecDiff, color=colorcito, marker='o' )
    XX = np.linspace(0,ttimeLambda2.max(), num=100 )
    axDiff2.plot(XX, line(XX, slope2, self.DiffLamb2), '--', color='k' )
    axDiff2.axhline(y=self.DiffCoeff, color='k')

    axDiff3.set_xlabel("$ t^{-"+self.strLamb3+"}$")
    axDiff3.ticklabel_format( useMathText=True, style='sci', axis='both', scilimits=(0,0) )
    axDiff3.plot(ttimeLambda3, EffecDiff, color=colorcito, marker='o' )
    XX = np.linspace(0,ttimeLambda3.max(), num=100 )
    axDiff3.plot(XX, line(XX, slope3, self.DiffLamb3), '--', color='k' )
    axDiff3.axhline(y=self.DiffCoeff, color='k')

    axDiff1.xaxis.get_offset_text().set_fontsize(10)
    axDiff2.xaxis.get_offset_text().set_fontsize(10)
    axDiff3.xaxis.get_offset_text().set_fontsize(10)

    axDiff1.yaxis.get_offset_text().set_fontsize(10)
    axDiff2.yaxis.get_offset_text().set_fontsize(10)
    axDiff3.yaxis.get_offset_text().set_fontsize(10)

    fig.tight_layout()
    fig.savefig("FIT_F2B_"+self.strF2B+"__B2F_"+self.strB2F+"__B2B_"+self.strB2B+"__Hrad_"+self.strHrad+"__Brad_"+self.strBrad+"__nt_"+self.strNtrials+".png")

    return fig, dr

  def getCSVstrLine(self):
    return  \
    "\"" +self.strF2B    +"\","+ \
    "\"" +self.strB2F    +"\","+ \
    "\"" +self.strB2B    +"\","+ \
    "\"" +self.strHrad   +"\","+ \
    "\"" +self.strBrad   +"\","+ \
    "\"" +self.strNtrials+"\""

from scipy.optimize import curve_fit
from scipy.stats import norm

def line(x, m, b):
  return m*x+b

def fitLine(xdata, ydata):
  popt, pcov = curve_fit(line, xdata, ydata)
  return popt, pcov

def powLaw(x, m, b):
  return np.exp(b)*x**m

def fitPowLaw(xdata,ydata):
  popt, pcov = curve_fit(line, np.log(xdata), np.log(ydata))
  return popt, pcov

def fitPowLawFromTo(xdata,ydata, xmin=None, xmax=None, returnIndx=False):
  if (xmin == None) and (xmax == None):
    popt, pcov = curve_fit(line, np.log(xdata), np.log(ydata))
    return popt, pcov
  else:
    if xmin == None:
      xmin = xdata[0]
    if xmax == None:
      xmax = xdata[-1]
    i_min, i_max = getLimits(xdata, xmin, xmax)
    popt, pcov = curve_fit(line, np.log(xdata[i_min:i_max]), np.log(ydata[i_min:i_max]))
    if returnIndx:
      return popt, pcov, i_min, i_max
    else:
      return popt, pcov

def gaussian(x, loc, scale):
  return norm.pdf(x, loc, scale)

def fitGaussian(xdata, ydata):
  popt, pcov = curve_fit(gaussian, xdata, ydata)
  return popt, pcov

def getLimits(arr, amin, amax):
  # Array must be sorted from min to max
  i_min=0
  i_max=len(arr)-1
  #if arr[i_min] > amin or arr[i_max] < amax:
  #  print "Out of bounds!!"
  #  exit()
  ii    = i_min
  while (arr[ii] <= amin ):
    ii = ii+1
    i_min = ii

  ii    = i_max
  while (arr[ii] >= amax ):
    ii = ii-1
    i_max = ii

  return i_min, i_max

def latex_float(f):
  float_str = "{0:.2g}".format(f)
  if "e" in float_str:
    base, exponent = float_str.split("e")
    #print float_str, base, exponent
    if base == "1" :
      #print base
      return r"10^{{{0}}}".format(int(exponent))
    else:
      return r"{0} \times 10^{{{1}}}".format(base, int(exponent))
  else:
    return float_str

def latex_float02(f):
  float_str = "{0:.2e}".format(f)
  base, exponent = float_str.split("e")
  if (float(base) == 1):
    if (float(exponent) == 0):
      return r"1"
    return r"10^{{{0}}}".format(int(exponent))
  return r"10^X"

class DraggableLogLogLine:
  def __init__(self, linea):
    self.linea = linea
    self.press = None

  def connect(self):
    'connect to all the events we need'
    self.cidpress = self.linea.figure.canvas.mpl_connect(
      'button_press_event', self.on_press)
    self.cidrelease = self.linea.figure.canvas.mpl_connect(
      'button_release_event', self.on_release)
    self.cidmotion = self.linea.figure.canvas.mpl_connect(
      'motion_notify_event', self.on_motion)

  def on_press(self, event):
    'on button press we will see if the mouse is over us and store some data'
    if event.inaxes != self.linea.axes: return

    contains, attrd = self.linea.contains(event)
    if not contains: return
    #print('event contains', self.linea.xy)
    #x0, y0 = self.linea.xy
    x0 = self.linea.get_xdata()
    y0 = self.linea.get_ydata()
    self.press = x0, y0, event.xdata, event.ydata

  def on_motion(self, event):
    'on motion we will move the linea if the mouse is over us'
    if self.press is None: return
    if event.inaxes != self.linea.axes: return
    x0, y0, xpress, ypress = self.press
    dx = event.xdata / xpress
    dy = event.ydata / ypress
    #print('x0=%f, xpress=%f, event.xdata=%f, dx=%f, x0+dx=%f' %
    #   (x0, xpress, event.xdata, dx, x0+dx))
    self.linea.set_xdata(x0*dx)
    self.linea.set_ydata(y0*dy)

    self.linea.figure.canvas.draw()

  def on_release(self, event):
    'on release we reset the press data'
    self.press = None
    self.linea.figure.canvas.draw()

  def disconnect(self):
    'disconnect all the stored connection ids'
    self.linea.figure.canvas.mpl_disconnect(self.cidpress)
    self.linea.figure.canvas.mpl_disconnect(self.cidrelease)
    self.linea.figure.canvas.mpl_disconnect(self.cidmotion)


from app import app
from webapp import db
from webapp.auth.models import User, Role
from webapp.api.account_holder.models import AccountHolder
import sys

def add_user(login, password, name, lastname, user_type, role_id, verified=False):
    user = User(login, password, name, lastname, user_type, role_id, verified)
    db.session.add(user)
    db.session.commit()
    return user

def add_account_holder(
    login,
    password,
    name,
    lastname,
    user_type,
    role_id,
    identification_document,
    gender,
    civil_status,
    birthdate,
    phone,
    nationality,
    street,
    sector,
    city,
    country,
    province,
    township,
    address,
    employer_name,
    employer_rif,
    employer_phone,
    employer_city,
    employer_country,
    employer_province,
    employer_township,
    employer_address,
):
    ah = AccountHolder(
        login,
        password,
        name,
        lastname,
        user_type,
        role_id,
        identification_document,
        gender,
        civil_status,
        birthdate,
        phone,
        nationality,
        street,
        sector,
        city,
        country,
        province,
        township,
        address,
        employer_name,
        employer_rif,
        employer_phone,
        employer_city,
        employer_country,
        employer_province,
        employer_township,
        employer_address,
    )
    db.session.add(ah)
    db.session.commit()
    return ah

def add_users(users):
    db.session.add_all(users)
    db.session.commit()
    return users

def add_role(description):
    role = Role(description)
    db.session.add(role)
    db.session.commit()
    return role

def add_roles(roles):
    db.session.add_all(roles)
    db.session.commit()
    return roles

def get_user_by_id(id):
    return User.query.get(id)

def get_role_by_id(id):
    return Role.query.get(id)

def populate_db():
    # add roles
    add_role("admin")
    add_role("user")
    # add users
    add_user("admin", "admin", "admin", "admin", "admin", 1, True)  # admin_role.id)
    add_user("user", "user", "user", "user", "user", 2, True)  # user_role.id)
    # add Account holder
    add_account_holder(
        "login",
        "password",
        "name",
        "lastname",
        "user_type",
        2,
        "identification_document",
        "gender",
        "civil_status",
        "birthdate",
        "phone",
        "nationality",
        "street",
        "sector",
        "city",
        "country",
        "province",
        "township",
        "address",
        "employer_name",
        "employer_rif",
        "employer_phone",
        "employer_city",
        "employer_country",
        "employer_province",
        "employer_township",
        "employer_address",
    )

if __name__ == "__main__":
    with app.app_context():
        if len(sys.argv) > 1 and sys.argv[1] == "create":
            db.drop_all()
            # create the database and the db table
            db.create_all()
            # commit the changes
            db.session.commit()

        if len(sys.argv) > 1 and sys.argv[1] == "populate":
            populate_db()


# Aula 14 - while
n=1
p = i = 0 # p=par e i=impar
while n != 0:
    n = int(input('Digite um valor: '))
    if n != 0: # para desconsiderar o 0 como número par!
        if n % 2 == 0:
            p = p + 1
        else:
            i += 1
print('Você lançou {} números pares e {} números impares!'.format(p,i))
print('Acabou')

#r = 'S'
#while r == 'S': # != é o simbolo de 'diferente de'
#    n=int(input('Digite um valor: '))
#    r = str(input('Quer continuar inserino valores [S/N]? ')).upper()
#print('Fim')

#for c in range(1, 10):
#    print(c)
#print('Fim')

#c=1
#while c <10:
#    print(c)
#    c = c + 1
#print('Fim')


"""Defines a WSGI request context middleware."""
from .util import get_wsgi_request_context
from ..context import context

class RequestContextMiddleware:
    """WSGI middleware, that adds WSGI environ information to logging context.

    This is meant to ve used together with the `LoggingContextFilter`.

    The only thing this middleware does, is it wraps the
    `app(environ, start_response)` call within the `loggingex.context.context`
    context manager, where it sets configured WSGI information extracted from
    `environ` argument in the context.

    :param app: WSGI application to be wrapped by this middleware.
    :param headers: Include request headers in the context.
    :param wsgi_info: Include WSGI information in the context.
    """

    def __init__(self, app, headers: bool = True, wsgi_info: bool = False):
        self.app = app
        self.headers = headers
        self.wsgi_info = wsgi_info

    def __call__(self, environ, start_request):
        request_context = get_wsgi_request_context(
            environ, wsgi_info=self.wsgi_info, headers=self.headers
        )
        with context(**request_context):
            for item in self.app(environ, start_request):
                yield item


"""
Main Loop of simulation.
Here a problem and a solution are defined.
"""

import gym
from pyglet.window import key
import numpy as np

from tools import *
from base_solution import *

# Show preview
def key_press(k, mod):
    if k == key.SPACE:
        global preview
        preview = True

def key_release(k, mod):
    if k == key.SPACE:
        global preview
        preview = False

# Parameters
n_episodes = 50000
problem = 'CarRacing-v0'

gym.logger.set_level(40)
preview = False
best_result = 0
all_episode_reward = []

# Initialize simulation
env = gym.make(problem)
env.reset()
env.viewer.window.on_key_press = key_press
env.viewer.window.on_key_release = key_release

# Define custom standard deviation for noise
# We need lest noise for steering
noise_std = np.array([0.1, 4 * 0.2], dtype=np.float32)
solution = BaseSolution(env.action_space, model_outputs=2, noise_std=noise_std)

# Loop of episodes
for ie in range(n_episodes):
    state = env.reset()
    solution.reset()
    done = False
    episode_reward = 0
    no_reward_counter = 0

    # One-step-loop
    while not done:
        if preview:
            env.render()

        action, train_action = solution.get_action(state)

        # This will make steering much easier
        action /= 4
        new_state, reward, done, info = env.step(action)

        # Models action output has a different shape for this problem
        solution.learn(state, train_action, reward, new_state)
        state = new_state
        episode_reward += reward

        if reward < 0:
            no_reward_counter += 1
            if no_reward_counter > 200:
                break
        else:
            no_reward_counter = 0

    all_episode_reward.append(episode_reward)
    average_result = np.array(all_episode_reward[-10:]).mean()
    print('Last result:', episode_reward, 'Average results:', average_result)

    if episode_reward > best_result:
        print('Saving best solution')
        solution.save_solution()
        best_result = episode_reward


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

from setuptools import setup, find_packages

with open('README.rst') as readme_file:
    readme = readme_file.read()

with open('HISTORY.rst') as history_file:
    history = history_file.read()

requirements = ['PyYAML>=5.1', 'colorama>=0.4.1']

setup_requirements = []

test_requirements = []

setup(
    author='luphord',
    author_email='luphord@protonmail.com',
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: Developers',
        'License :: OSI Approved :: MIT License',
        'Natural Language :: English',
        'Programming Language :: Python :: 3',
        'Programming Language :: Python :: 3.5',
        'Programming Language :: Python :: 3.6',
        'Programming Language :: Python :: 3.7',
        'Programming Language :: Python :: 3.8',
    ],
    description='A command line tool for my image processing needs.',
    entry_points={
        'console_scripts': [
            'hyperdiary=hyperdiary.__main__:main',
        ],
    },
    data_files=[('hyperdiary/assets/css',
                 ['hyperdiary/assets/css/picnic.min.css'])],
    install_requires=requirements,
    license='MIT license',
    long_description=readme + '\n\n' + history,
    include_package_data=True,
    keywords='hyperdiary',
    name='hyperdiary',
    packages=find_packages(),
    setup_requires=setup_requirements,
    test_suite='tests',
    tests_require=test_requirements,
    url='https://github.com/luphord/hyperdiary',
    version='0.6.1',
    zip_safe=False,
)


import os

import numpy as np
import matplotlib.pyplot as plt
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import (OrdinalEncoder,
                                   FunctionTransformer,
                                   StandardScaler)
from sklearn.cluster import KMeans
from yellowbrick.cluster import KElbowVisualizer
from sklearn.decomposition import PCA

plt.style.use('ggplot')

class ClusterAnalysis:

    def __init__(self) -> None:
        """Cluster-analysis on Customer Data"""
        self.output_path = 'outputs/visuals/'
        self.data_path = 'data/customers.csv'

    def run(self, *args, verbose=True) -> None:
        data_col = ['CustomerID', 'Gender', 'Age', 'Annual Income (k$)',
                    'Spending Score (1-100)']
        data = np.genfromtxt(
            self.data_path, delimiter=',', dtype=object, skip_header=1)

        data = data[:, 1:]  # remove CustomerID

        pipe = Pipeline(steps=[
            ('GenderBinarizer', ColumnTransformer(
                [('oe', OrdinalEncoder(), [0])], remainder='passthrough')),
            ('ChangeDtype', FunctionTransformer(lambda X: X.astype(np.float32))),
            ('StandardScaler', ColumnTransformer(
                [('ss', StandardScaler(), [1,2,3])], remainder='passthrough')),

        ], verbose=False)

        transformed_data = pipe.fit_transform(data)

        self._visualize_optimal_K(
            X=transformed_data, filename='optimal_value_of_k')

        # Add KMeans clustering algorithm in pipeline
        k = 4
        model = KMeans(
            n_clusters=k, init='k-means++', max_iter=20, n_init=10,
            random_state=0)
        pipe.steps.append(('kmeans', model))

        # Fit and predict
        pipe.verbose = True
        labels = pipe.fit_predict(data)
        cluster_centers = pipe['kmeans'].cluster_centers_

        self._plot_clusters(
            transformed_data, cluster_centers, labels,
            title='Clusters Visualization')

        # (unscaled) Features mean of each cluster
        cluster_means = []
        pipe.verbose = False
        for i in range(k):
            cluster_means.append(
                pipe[:2].transform(data)[labels==i, :].mean(axis=0))
        cluster_means = np.array(cluster_means)

        # Observation: (Based on `cluster_means`)
        # Cluster-0 (or Segment-0) comprises those customers who has high
        # income and spend alot.
        # Customers in Cluster-1 earn high but they spend a little and
        # there average age is higher than the Cluster-0.
        # Cluster-2 comprises customers who has medium income and spend
        # at the same level. They are old people.
        # Cluster-3 comprises customers who has little income but they
        # spend a lot. They are young people.

        if verbose:
            print('Visuals have been saved to {} directory.'.format(self.output_path))

    def _visualize_optimal_K(self, X, filename=None):
        fig = plt.figure()
        visualizer = KElbowVisualizer(
            KMeans(random_state=0), k=(1,13), timing=False)
        visualizer.fit(X) #Fit the data to the visualizer
        visualizer.show()
        if filename:
            os.makedirs(self.output_path, exist_ok=True)
            fig.savefig(self.output_path+filename, dpi=fig.dpi)

    def _plot_clusters(self, transformed_X, centroids, labels, title):
        # Apply PCA and fit the features
        pca_2d = PCA(n_components=2).fit_transform(transformed_X)

        fig, ax = plt.subplots(figsize=(10, 6))
        plt.scatter(
            pca_2d[:, 0],
            pca_2d[:, 1],
            c=labels,
            cmap=plt.cm.get_cmap("Spectral_r", 5),
            alpha=0.5)
        ax.set_xlabel('PCA Component-1', fontsize=8, labelpad=10)
        ax.set_ylabel('PCA Component-2', fontsize=8, labelpad=10)

        fig.suptitle(title, fontweight ="bold", fontsize=16)
        plt.colorbar(ticks=list(range(len(centroids))))
        plt.show()


# Test consistency between galpy and NEMO
import os
import subprocess

import numpy

from galpy import potential
from galpy.orbit import Orbit
from galpy.util import conversion

def test_nemo_MN3ExponentialDiskPotential():
    mn = potential.MN3ExponentialDiskPotential(normalize=1.0, hr=0.5, hz=0.1)
    tmax = 3.0
    vo, ro = 215.0, 8.75
    o = Orbit([1.0, 0.1, 1.1, 0.3, 0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, mn, tmax, vo, ro)
    return None

def test_nemo_MiyamotoNagaiPotential():
    mp = potential.MiyamotoNagaiPotential(normalize=1.0, a=0.5, b=0.1)
    tmax = 4.0
    vo, ro = 220.0, 8.0
    o = Orbit([1.0, 0.1, 1.1, 0.3, 0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, mp, tmax, vo, ro)
    return None

def test_nemo_NFWPotential():
    np = potential.NFWPotential(normalize=1.0, a=3.0)
    tmax = 3.0
    vo, ro = 200.0, 7.0
    o = Orbit([1.0, 0.5, 1.3, 0.3, 0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, np, tmax, vo, ro)
    return None

def test_nemo_HernquistPotential():
    hp = potential.HernquistPotential(normalize=1.0, a=3.0)
    tmax = 3.0
    vo, ro = 210.0, 7.5
    o = Orbit([1.0, 0.25, 1.4, 0.3, -0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, hp, tmax, vo, ro)
    return None

def test_nemo_PowerSphericalPotentialwCutoffPotential():
    pp = potential.PowerSphericalPotentialwCutoff(normalize=1.0, alpha=1.0, rc=0.4)
    tmax = 2.0
    vo, ro = 180.0, 9.0
    o = Orbit([1.0, 0.03, 1.03, 0.2, 0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, pp, tmax, vo, ro)
    return None

def test_nemo_LogarithmicHaloPotential():
    lp = potential.LogarithmicHaloPotential(normalize=1.0)
    tmax = 2.0
    vo, ro = 210.0, 8.5
    o = Orbit([1.0, 0.1, 1.1, 0.3, 0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, lp, tmax, vo, ro, tol=0.03)
    return None

def test_nemo_PlummerPotential():
    pp = potential.PlummerPotential(normalize=1.0, b=2.0)
    tmax = 3.0
    vo, ro = 213.0, 8.23
    o = Orbit([1.0, 0.1, 1.1, 0.3, 0.1, 0.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, pp, tmax, vo, ro, tol=0.03)
    return None

def test_nemo_MWPotential2014():
    mp = potential.MWPotential2014
    tmax = 3.5
    vo, ro = 220.0, 8.0
    o = Orbit([1.0, 0.1, 1.1, 0.2, 0.1, 1.4], ro=ro, vo=vo)
    run_orbitIntegration_comparison(o, mp, tmax, vo, ro, isList=True)
    return None

def run_orbitIntegration_comparison(orb, pot, tmax, vo, ro, isList=False, tol=0.01):
    # Integrate in galpy
    ts = numpy.linspace(0.0, tmax / conversion.time_in_Gyr(vo, ro), 1001)
    orb.integrate(ts, pot)
    # Now setup a NEMO snapshot in the correct units ([x] = kpc, [v] = kpc/Gyr)
    numpy.savetxt(
        "orb.dat",
        numpy.array(
            [
                [
                    10.0**-6.0,
                    orb.x(),
                    orb.y(),
                    orb.z(),
                    orb.vx(use_physical=False) * conversion.velocity_in_kpcGyr(vo, ro),
                    orb.vy(use_physical=False) * conversion.velocity_in_kpcGyr(vo, ro),
                    orb.vz(use_physical=False) * conversion.velocity_in_kpcGyr(vo, ro),
                ]
            ]
        ),
    )
    # Now convert to NEMO format
    try:
        convert_to_nemo("orb.dat", "orb.nemo")
    finally:
        os.remove("orb.dat")
    # Integrate with gyrfalcON
    try:
        if isList:
            integrate_gyrfalcon(
                "orb.nemo",
                "orb_evol.nemo",
                tmax,
                potential.nemo_accname(pot),
                potential.nemo_accpars(pot, vo, ro),
            )
        else:
            integrate_gyrfalcon(
                "orb.nemo",
                "orb_evol.nemo",
                tmax,
                pot.nemo_accname(),
                pot.nemo_accpars(vo, ro),
            )
    finally:
        os.remove("orb.nemo")
        os.remove("gyrfalcON.log")
    # Convert back to ascii
    try:
        convert_from_nemo("orb_evol.nemo", "orb_evol.dat")
    finally:
        os.remove("orb_evol.nemo")
    # Read and compare
    try:
        nemodata = numpy.loadtxt("orb_evol.dat", comments="#")
        xdiff = numpy.fabs((nemodata[-1, 1] - orb.x(ts[-1])) / nemodata[-1, 1])
        ydiff = numpy.fabs((nemodata[-1, 2] - orb.y(ts[-1])) / nemodata[-1, 2])
        zdiff = numpy.fabs((nemodata[-1, 3] - orb.z(ts[-1])) / nemodata[-1, 3])
        vxdiff = numpy.fabs(
            (
                nemodata[-1, 4]
                - orb.vx(ts[-1], use_physical=False)
                * conversion.velocity_in_kpcGyr(vo, ro)
            )
            / nemodata[-1, 4]
        )
        vydiff = numpy.fabs(
            (
                nemodata[-1, 5]
                - orb.vy(ts[-1], use_physical=False)
                * conversion.velocity_in_kpcGyr(vo, ro)
            )
            / nemodata[-1, 5]
        )
        vzdiff = numpy.fabs(
            (
                nemodata[-1, 6]
                - orb.vz(ts[-1], use_physical=False)
                * conversion.velocity_in_kpcGyr(vo, ro)
            )
            / nemodata[-1, 6]
        )
        assert xdiff < tol, (
            "galpy and NEMO gyrfalcON orbit integration inconsistent for x by %g"
            % xdiff
        )
        assert ydiff < tol, (
            "galpy and NEMO gyrfalcON orbit integration inconsistent for y by %g"
            % ydiff
        )
        assert zdiff < tol, (
            "galpy and NEMO gyrfalcON orbit integration inconsistent for z by %g"
            % zdiff
        )
        assert vxdiff < tol, (
            "galpy and NEMO gyrfalcON orbit integration inconsistent for vx by %g"
            % vxdiff
        )
        assert vydiff < tol, (
            "galpy and NEMO gyrfalcON orbit integration inconsistent for vy by %g"
            % vydiff
        )
        assert vzdiff < tol, (
            "galpy and NEMO gyrfalcON orbit integration inconsistent for vz by %g"
            % vzdiff
        )
    finally:
        os.remove("orb_evol.dat")
    return None

def convert_to_nemo(infile, outfile):
    subprocess.check_call(
        ["a2s", "in=%s" % infile, "out=%s" % outfile, "N=1", "read=mxv"]
    )

def convert_from_nemo(infile, outfile):
    subprocess.check_call(["s2a", "in=%s" % infile, "out=%s" % outfile])

def integrate_gyrfalcon(infile, outfile, tmax, nemo_accname, nemo_accpars):
    """Integrate a snapshot in infile until tmax in Gyr, save to outfile"""
    with open("gyrfalcON.log", "w") as f:
        subprocess.check_call(
            [
                "gyrfalcON",
                "in=%s" % infile,
                "out=%s" % outfile,
                "tstop=%g" % tmax,
                "eps=0.0015",
                "step=0.01",
                "kmax=10",
                "Nlev=8",
                "fac=0.01",
                "accname=%s" % nemo_accname,
                "accpars=%s" % nemo_accpars,
            ],
            stdout=f,
        )
    return None


import face_recognition
import picamera
import numpy as np
camera = picamera.PiCamera()
camera.resolution = (320, 240)
output = np.empty((240, 320, 3), dtype=np.uint8)
# Load a sample picture and learn how to recognize it.
print("Loading known face image(s)")
obama_image = face_recognition.load_image_file("modelos/obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]
biden_image = face_recognition.load_image_file("modelos/biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]
stallman_image= face_recognition.load_image_file("modelos/richard.jpg")
stallman_face_encoding = face_recognition.face_encodings(stallman_image)[0]
chupetin_image= face_recognition.load_image_file("modelos/chupetin.jpg")
chupetin_face_encoding = face_recognition.face_encodings(chupetin_image)[0]
known_face_encodings = [obama_face_encoding,biden_face_encoding,stallman_face_encoding,chupetin_face_encoding]
# Initialize some variables
face_locations = []
face_encodings = []
known_face_names = [
    "Barack Obama",
    "Joe Biden",
    "Richard Stallman",
    "Chupetin Trujillo"
]
while True:
    print("Capturando imagen.")
    # Grab a single frame of video from the RPi camera as a numpy array
    camera.capture(output, format="rgb")
    # Find all the faces and face encodings in the current frame of video
    face_locations = face_recognition.face_locations(output)
    print("Encontradas {} caras en la imagen.".format(len(face_locations)))
    face_encodings = face_recognition.face_encodings(output, face_locations)
    # Loop over each face found in the frame to see if it's someone we know.
    face_names = []
    for face_encoding in face_encodings:
        # See if the face is a match for the known face(s)
        #match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
        match = face_recognition.compare_faces(known_face_encodings, face_encoding)
        name = "Persona Desconocida"
        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        best_match_index = np.argmin(face_distances)
        if match[best_match_index]:
            name = known_face_names[best_match_index]
            print("PERSONA DETECTADA: ",name)
        #face_names.append(name)


from . import configs
from flask import Flask
from flask_cors import CORS
from flask_redis import FlaskRedis
from celery import Celery
from etcd import Client
from kafka import KafkaProducer
import os, json

celery = Celery(__name__,
                broker=os.environ.get("CELERY_BROKER_URL",
                                        "amqp://admin:qazwsx@127.0.0.1:5672//"),
                backend=os.environ.get("CELERY_RESULT_BACKEND",
                                        "amqp://admin:qazwsx@127.0.0.1:5672//"))

etcd_host = os.environ.get("ETCD_HOST", os.getenv("ETCD_HOST"))
etcd_port = os.environ.get("ETCD_PORT", os.getenv("ETCD_PORT"))
etcd_client = Client(host=etcd_host, port=int(etcd_port))

redis_store = FlaskRedis()
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

kafka_host = os.environ.get("KAFKA_HOST", os.getenv("KAFKA_HOST"))
kafka_port = os.environ.get("KAFKA_PORT", os.getenv("KAFKA_PORT"))
kafka_broker = [kafka_host+":"+kafka_port]
producer = KafkaProducer(
                bootstrap_servers=kafka_broker,
                value_serializer=lambda m: json.dumps(m).encode('utf-8'))

def create_app():
    app = Flask(__name__)
    app.config.from_object(configs.Config)
    app.config['REDIS_URL'] = os.environ.get(
        "APP_REDIS_URL","redis://:@127.0.0.1:6379/0")

    redis_store.init_app(app)
    celery.conf.update(app.config)

    CORS(app, resources={r"/api/*": {"origins": "*"}})

    from .controllers import api_blueprint
    from .controllers import swaggerui_blueprint

    app.register_blueprint(swaggerui_blueprint,url_prefix=os.environ.get("/api/docs","/api/docs"))

    app.register_blueprint(api_blueprint)

    return app


import gensim
from gensim import corpora
from gensim.corpora import Dictionary
import pickle
import os
from spacy.lang.en import English
import nltk

from nltk.corpus import wordnet as wn
def get_lemma(word):
    lemma = wn.morphy(word)
    if lemma is None:
        return word
    else:
        return lemma

from nltk.stem.wordnet import WordNetLemmatizer
def get_lemma2(word):
    return WordNetLemmatizer().lemmatize(word)

en_stop = set(nltk.corpus.stopwords.words('english'))
parser = English()

eng_only_files = pickle.load(open('pickles/english_only_files.pkl','rb'))
eng_only_files=[i.strip('.doc.sdlxliff').replace('raw_data/','data_products/extracted/')+".txt" for i in eng_only_files]

NUM_TOPICS = 20

def tokenize(text):
    lda_tokens = []
    tokens = parser(text)
    for token in tokens:
        if token.orth_.isspace():
            continue
        elif token.like_url:
            lda_tokens.append('URL')
        elif token.orth_.startswith('@'):
            lda_tokens.append('SCREEN_NAME')
        else:
            lda_tokens.append(token.lower_)
    return lda_tokens

def load_data(files_list):
    text_data=[]
    for filename in files_list:
        text_data.append(prepare_text_for_lda(open(filename,'r').read()))
    return text_data

def get_dict_and_corpus(text_data):
    dictionary = corpora.Dictionary(text_data)
    corpus = [dictionary.doc2bow(text) for text in text_data]
    return dictionary,corpus

def prepare_text_for_lda(text):
    tokens = tokenize(text)
    tokens = [token for token in tokens if len(token) > 4]
    tokens = [token for token in tokens if token not in en_stop]
    tokens = [get_lemma(token) for token in tokens]
    return tokens

def predict_topics_from_file(filename, dictionary_file='dictionary.gensim',
        model='models/model30.gensim'):
    new_doc = open(filename,'r').read()
    predict_topic_from_text(new_doc, dictionary_file=dictionary_file,
            model=model)

def predict_topic_from_text(new_doc,  dictionary_file='dictionary.gensim',
        model='models/model30.gensim', printout=False):
    ldamodel = gensim.models.ldamodel.LdaModel.load(model)
    new_doc = prepare_text_for_lda(new_doc)
    dictionary=Dictionary.load( dictionary_file)
    new_doc_bow = dictionary.doc2bow(new_doc)
    doc_topics = sorted(ldamodel.get_document_topics(new_doc_bow),key=lambda x:x[1], reverse=True)
    all_topics = ldamodel.show_topics(30)
    thresh_topics=[]
    for topic in doc_topics:
        if topic[1]>0.1:
            thresh_topics.append({'topic #':all_topics[topic[0]][0],"topic probability":
                topic[1],'topic hot words': all_topics[topic[0]][1]})
    if printout:
        print(thresh_topics)
    return thresh_topics

#Loading corpus:
# corpus=pickle.load(open('pickles/corpus.pkl','rb'))
# Loading dictionary:
# dictionary = Dictionary.load('dictionary.gensim')
# downloading text data:
def visualize_model():
    import pyLDAvis.gensim
    import pyLDAvis
    pyLDAvis.enable_notebook()
    vis = pickle.load(open('pickles/firs_finished_vis.pkl','rb'))
    pyLDAvis.show(vis)


from app import create_app
from app.auth import auth
from app.models import tipoUsuario, usuario, empleado, proovedor, compra, cliente, pedido, pedidoProducto, compraProducto, producto, tipoProducto, imagenesProducto, db

app = create_app()

app.app_context().push()

db.create_all()

tipoUsuario1 = tipoUsuario('Empleado')
tipoUsuario2 = tipoUsuario('Cliente')
tipoUsuario3 = tipoUsuario('Admin')

usuario1 = usuario('admin', 'userImage_1.png', 'sadsad', 'davids.dvm@gmail.com', 'activo', None, '3')
usuario2 = usuario('santiago', 'userImage_1.png', 'sadsad', 'santiago@gmail.com', 'activo', None, '2')
usuario3 = usuario('juan', 'userImage_1.png', 'sadsad', 'juan@gmail.com', 'activo', None, '2')
usuario4 = usuario('prueba', 'userImage_1.png', 'sadsad', 'preuba@gmail.com', 'activo', None, '1')
usuario5 = usuario('preubapepito', 'userImage_1.png', 'sadsad', 'pepito@gmail.com', 'activo', None, '2')

empleado1 = empleado('Pepito Gonzales', 'Administrador', '3105628923', 'Activo', 'CE', '25252525', '3')
empleado2 = empleado('Lucia Cardenas', 'Gerente', '3198524759', 'Inactivo', 'CC', '1052628978', '2')
empleado3 = empleado('Santiago Perez', 'Pepo', '3122055247', 'Activo', 'CC', '1525457845', '1')

proovedor1 = proovedor('Flores C SAS', 'Raul', '1052487895', 'CC', 'flores@flores.com', '3189547569')
proovedor2 = proovedor('LasFloresdePedro', 'Pedro', '1030699585', 'CC', 'Pedro@Flowers.com', '3198274715')
proovedor3 = proovedor('Flowers CORP', 'Will', '1030574151', 'CE', 'FlowerC@gmail.com', '3165024147')

compra1 = compra('2021-06-25', '50000', '01', 'Compra de Tulipanes x100,Rosas x800', 'Activo', 1, 2)
compra2 = compra('2021-05-31', '600000','02', 'Compra orquideas x30, Compra azucenax 300', 'Activo', 2, 1)
compra3 = compra('2020-06-25', '500000','03', 'Compra Dalia x50, Compra hortensiax100', 'Activo', 3, 1)

cliente1 = cliente('cll 54 bs24-2', '31030445467', 'Ramiro Gonzalez','CC', '5465765489765432', None, '547', '06', '2023', 'Ramiro Gonzalez', '1')
cliente2 = cliente('Crr 28 v67-21', '3143143142', 'Calceto oliente','Paypal', None, 'calcetoRo@gmail.com', None, None, None, 'Calceto', '2')
cliente3 = cliente('Avenida 30 #24-2', '3213213215', 'Porfilo Rojas','CC', '4705234586872343', None, '665', '02', '2025', 'Carlo magno', '3')

pedido1 = pedido('2020-05-02', '50000', 'Pedido de un Boutique Matrimonial', 'Enviado', 1)
pedido2 = pedido('2021-06-03', '90000', 'Pedido de un Boutique cumpleaños', 'Empaquetando', 2)
pedido3 = pedido('2021-04-02', '60004', 'Pedido 41 Rosas Rojas', 'Entregado', 3)

tipProduct1 = tipoProducto ('Unitario')
tipProduct2 = tipoProducto ('Arreglos')
tipProduct3 = tipoProducto ('Boutique')
tipProduct4 = tipoProducto ('Jarron')

imagen1 = imagenesProducto('shop_flower_1.jpg', None, None, None, None)
imagen2 = imagenesProducto('shop_flower_2.jpg', None, None, None, None)
imagen3 = imagenesProducto('shop_flower_3.jpg', None, None, None, None)
imagen4 = imagenesProducto('Flor_Rosa_1.jpg', None, None, None, None)
imagen5 = imagenesProducto('shop_flower_1.jpg', None, None, None, None)
imagen6 = imagenesProducto('lilyIcon_1.jpg', None, None, None, None)
imagen7 = imagenesProducto('flowersIcon_1.jpg', None, None, None, None)
imagen8 = imagenesProducto('Flor_Carnation_1.jpg', None, None, None, None)
imagen9 = imagenesProducto('jarron_flores.jpg', None, None, None, None)
imagen10 = imagenesProducto('jarron_brillo_solar.jpg', None, None, None, None)
imagen11 = imagenesProducto('Luz _de_colores.jpg', None, None, None, None)
imagen12 = imagenesProducto('Rosas_Lirios_Blancos.jpg', None, None, None, None)
imagen13 = imagenesProducto('Bouquet_de_6_girasoles.jpg', None, None, None, None)
imagen14 = imagenesProducto('Arreglo_floral_marqueza.jpg', None, None, None, None)

producto1 = producto(12000, 'Rosa', 500, 'Flores en un jarron Arreglo Tulipanes Flor tipo tulipán de la familia Liliaceae flor con gran aroma, viene con jarrón Características: Tulipanes: Tulipa gesneriana Colores: A elección del usuario', 'Activo', 1, 1)
producto2 = producto(600000, 'Boutique cumpleaños', 600, 'Arreglo floral de cumpleaños','Activo', 2, 2)
producto3 = producto(646545, 'Boutique Matrimonial', 300, 'Arreglo floral Matrimonial','Activo', 3, 3)
producto4 = producto(14000, 'Jarron Brillo Solar', 14, 'Un jarron muy atractivo que a cualquier le encantara','Activo', 4, 4)
producto5 = producto(55000, 'Lavanda', 52, 'Unas flores con un olor increible','Activo', 5, 1)
producto6 = producto(85000, 'Flor Tipo tulipan', 58, 'Un tulipan alegra la vida de cualquiera, puede llegar a ser el regalo perfecto','Activo', 6, 2)
producto7 = producto(120000, 'Ramo de Flores Rojo', 10, 'Un precioso regalo que a cualquier persona le encatara','Activo', 7, 1)
producto8 = producto(58400, 'Rosa tipo Gardenia', 41, 'Las rosas perfectas para decorar el espacio adecuado','Activo', 8, 2)
producto9 = producto(152000, 'Jarron de 36 flores', 54, 'Un jarron increible con las 36 mejores flores de esta especie, sin duda una decoracion perfecta','Activo', 9, 2)
producto10 = producto(89000, 'Jarron Brillo Solar', 12, 'Un jarron de flores lleno de alegria; los mejores girasoles para hacer feliz a cualquiera','Activo', 10, 2)
producto11 = producto(162000, 'Lavanda', 23, 'Un jarron que tan solo de mirarlo ya huele, llena de este agradable perfume natural cualquier espacio de tu casa','Activo', 11, 1)
producto12 = producto(254000, 'Flor Tipo tulipan', 12, 'Un tipo de flor unico en su especie, conquista cualquier alma con esta preciosa flor casi imposible de conseguir','Activo', 12, 4)
producto13 = producto(23000, 'Ramo de Flores Feliz', 11, 'No hay nada como alegrar el dia de cualquiera con este increible ramo de flores','Activo', 13, 4)
producto14 = producto(260000, 'Arreglo de girasoles', 24, 'Un arreglo de girasoles unico e increible para tu hogar','Activo', 14, 3)

pedidoP1 = pedidoProducto(1, 1, 500000, 5)
pedidoP2 = pedidoProducto(2, 2, 1500000, 50)
pedidoP3 = pedidoProducto(3, 3, 2600000, 16)

compraP1 = compraProducto(1, 1, 600000, 1)
compraP2 = compraProducto(2, 2, 60000, 6)
compraP3 = compraProducto(3, 3, 400000, 5)

db.session.add(tipoUsuario1)
db.session.add(tipoUsuario2)
db.session.add(tipoUsuario3)
db.session.add(usuario1)
db.session.add(usuario2)
db.session.add(usuario3)
db.session.add(usuario4)
db.session.add(usuario5)
db.session.add(empleado1)
db.session.add(empleado2)
db.session.add(empleado3)
db.session.add(proovedor1)
db.session.add(proovedor2)
db.session.add(proovedor3)
db.session.add(compra1)
db.session.add(compra2)
db.session.add(compra3)
db.session.add(cliente1)
db.session.add(cliente2)
db.session.add(cliente3)
db.session.add(pedido1)
db.session.add(pedido2)
db.session.add(pedido3)
db.session.add(tipProduct1)
db.session.add(tipProduct2)
db.session.add(tipProduct3)
db.session.add(tipProduct4)
db.session.add(imagen1)
db.session.add(imagen2)
db.session.add(imagen3)
db.session.add(imagen4)
db.session.add(imagen5)
db.session.add(imagen6)
db.session.add(imagen7)
db.session.add(imagen8)
db.session.add(imagen9)
db.session.add(imagen10)
db.session.add(imagen11)
db.session.add(imagen12)
db.session.add(imagen13)
db.session.add(imagen14)
db.session.add(producto1)
db.session.add(producto2)
db.session.add(producto3)
db.session.add(producto4)
db.session.add(producto5)
db.session.add(producto6)
db.session.add(producto7)
db.session.add(producto8)
db.session.add(producto9)
db.session.add(producto10)
db.session.add(producto11)
db.session.add(producto12)
db.session.add(producto13)
db.session.add(producto14)
db.session.add(pedidoP1)
db.session.add(pedidoP2)
db.session.add(pedidoP3)
db.session.add(compraP1)
db.session.add(compraP2)
db.session.add(compraP3)

db.session.commit()


#!/usr/bin/env python
# coding: utf-8

import pandas as pd
import numpy as np
import os
from datetime import datetime
import locale

# Check if environmet variables are set otherwise use defaults
# Input variables
if 'GX_REALDATA_FILENAME_LOG' in os.environ:
    GX_REALDATA_FILENAME_LOG = os.environ['GX_REALDATA_FILENAME_LOG']
else:
    GX_REALDATA_FILENAME_LOG = '/app/data/01_gx/01_gx_realdata_logs.csv'
if 'GX_REALDATA_FILENAME_GRADES' in os.environ:
    GX_REALDATA_FILENAME_GRADES = os.environ['GX_REALDATA_FILENAME_GRADES']
else:
    GX_REALDATA_FILENAME_GRADES = '/app/data/01_gx/01_gx_realdata_grades.csv'

# Output variables
if 'DATAPREP_REALDATA_FILENAME' in os.environ:
    DATAPREP_REALDATA_FILENAME = os.environ['DATAPREP_REALDATA_FILENAME']
else:
    DATAPREP_REALDATA_FILENAME = '02_dataprep_realdata.csv'
if 'DATAPREP_REALDATA_FOLDERNAME' in os.environ:
    DATAPREP_REALDATA_FOLDERNAME = os.environ['DATAPREP_REALDATA_PATH']
else:
    DATAPREP_REALDATA_FOLDERNAME = '/app/data/02_dataprep'

if 'DATAPREP_REALDATA_FILENAME_LOG' in os.environ:
    DATAPREP_REALDATA_FILENAME_LOG = os.environ['DATAPREP_REALDATA_FILENAME_LOG']
else:
    DATAPREP_REALDATA_FILENAME_LOG = '02_dataprep_testdata.csv'
if 'DATAPREP_REALDATA_FOLDERNAME_LOG' in os.environ:
    DATAPREP_REALDATA_FOLDERNAME_LOG = os.environ['DATAPREP_REALDATA_FOLDERNAME_LOG']
else:
    DATAPREP_REALDATA_FOLDERNAME_LOG = '/app/data/02_dataprep'

# erstes CSV einlesen mit den Log-Daten
log_data = pd.read_csv(GX_REALDATA_FILENAME_LOG)

# zweites CSV einlesen mit den Abschlussnoten
grade_data = pd.read_csv(GX_REALDATA_FILENAME_GRADES)

# eindeutige Werte der Spalten 'Voll.Name', 'Komponente', 'Herkunft' von sim_data als array ausgeben

unique_name = log_data['Vollständiger Name'].unique()
unique_komponente = log_data['Komponente'].unique()
unique_herkunft = log_data['Herkunft'].unique()

# Länge der Arrays ausgeben

length_name = len(unique_name)
length_komponente = len(unique_komponente)
length_herkunft = len(unique_herkunft)

# neues df mit Auswertparameter von sim_data nach Spalte 'Vollständiger Name' erstellen
# pro eindeutiger Parameter in den Spalten 'Komponente' und 'Herkunft' soll eine neue Spalte in grouped_sim erstellen werden
# Hierzu beziehen wir uns auf die zuvor erstellen arrays mit der Anzahl der eindeutigen Werte einer Spalte unique_komponente
# Nur so viele neue Spalten werden generiert, wie es eindeutige Werte pro Spalte hat
# Der Name der neuen Spalte entspricht 'Anzahl' + Name eindeutiger Wert

# Spalten 'Komponente' und 'Herkunft' als String konvertieren
log_data['Herkunft'] = log_data['Herkunft'].astype(str)
log_data['Komponente'] = log_data['Komponente'].astype(str)

# Neues gruppiertes DataFrame erstellen und Index zurücksetzen
grouped_data = log_data.groupby('Vollständiger Name').agg({
    'Komponente': [(f'Anzahl {name}', lambda x, name=name: (x == name).sum()) for name in unique_komponente],
    'Herkunft': [(f'Anzahl {name}', lambda x, name=name: (x == name).sum()) for name in unique_herkunft],
    'IP-Adresse': 'nunique'
}).reset_index()

locale.setlocale(locale.LC_TIME, "de_DE.UTF-8") # german

# Anzahl der Vorkommen eines Users im ursprünglichen sim_data
user_counts = log_data['Vollständiger Name'].value_counts().rename('Anzahl_log_all')

# nur das Datum extrahieren
log_data['Zeit'] = pd.to_datetime(log_data['Zeit'], format='%d. %B %Y, %H:%M:%S').dt.date

# Definiere den Start- und Endzeitpunkt für den ersten Zeitraum
# Start: erster Log-Eintrag
start_date = log_data['Zeit'].min()

# 16 Wochen später als der erste Eintrag (Dauer eines Semesters)
end_date = start_date + pd.DateOffset(weeks=20)
# Beobachtung: teilweise Einträge nach 16 Wochen - Enddatum = Letzter Log-Eintrag der Logdatei
#end_date = log_data['Zeit'].max()

# Definiere den Zeitraumabstand
period_offset = pd.DateOffset(weeks=2)

# Liste zur Speicherung der Zeitraumgrenzen
period_boundaries = []

# Generiere die Zeitraumgrenzen mit einem Abstand von zwei Wochen
# pro Zeitraumgrenze wird es eine neue Spalte in dem DataFrame log_counts geben
# Wenn keine Werte für die Zeiträume z.B. bei 16 Wochen vorhanden sind, werden die Spalten mit dem Mittelwert der vorherigen
# Zeitraumsgrenzen aufgefüllt

current_date = start_date
# Error-Handling
current_date = pd.Timestamp(current_date)
while current_date <= end_date:
    period_boundaries.append(current_date)
    current_date += period_offset

# Erstelle das DataFrame log_counts mit den Zeitraumspalten
log_counts = pd.DataFrame()
log_counts['Vollständiger Name'] = user_counts.index.unique() # Eindeutige Namen im Index verwenden
log_counts['Anzahl_log_all'] = user_counts.reindex(log_counts['Vollständiger Name']).values # Werte entsprechend den eindeutigen Namen im Index reindexieren

# Überprüfung des letzten Datums in sim_data
last_date = log_data['Zeit'].max()
# Error-Handling
last_date = pd.Timestamp(last_date)

# Auffüllen der fehlenden Zeiträume basierend auf dem letzten Datum
for i in range(len(period_boundaries)):
    period_start = period_boundaries[i]
    if i == len(period_boundaries) - 1:
        # Letzter Zeitraum, fiktiven Wert verwenden - Mittelwert der vorherigen Zeiträume
        log_counts[f'Anzahl_log_f{i+1}'] = np.mean(log_counts[[f'Anzahl_log_f{j}' for j in range(1, i+1)]], axis=1).astype(int)
    else:
        period_end = period_boundaries[i + 1]

        if last_date >= period_end:
            # Datum liegt im Zeitraum, Log-Einträge zählen

            # Error-Handling
            period_start_date = period_start.date()
            period_end_date = period_end.date()
            log_entries_by_period = log_data[(log_data['Zeit'] >= period_start_date) & (log_data['Zeit'] < period_end_date)].groupby('Vollständiger Name').count()
            log_counts[f'Anzahl_log_f{i+1}'] = log_entries_by_period['Zeit'].reindex(log_counts['Vollständiger Name'], fill_value=0).values
        else:
            # Datum liegt außerhalb des Zeitraums, mit Mittelwert auffüllen als Ganzzahl
            log_counts[f'Anzahl_log_f{i+1}'] = np.mean(log_counts[[f'Anzahl_log_f{j}' for j in range(1, i+1)]], axis=1).astype(int)

print(log_counts.head())
print(grouped_data.head())

# Anzahl log-Einträge mit sim_data mergen nach 'Vollständiger Name'
grouped_data_log = grouped_data.merge(log_counts, on='Vollständiger Name')

# Vollständiger Name doppelt - zweite Spalte droppen
grouped_data_log = grouped_data_log.drop(('Vollständiger Name', ''), axis=1)
#grouped_data_log.rename(columns={'Vollständiger Name': 'Vollstaendiger Name'})

def check_grades(grade_csv):
    if grade_csv['bewertung'].isnull().all():
        # Wenn die Spalte 'bewertung' leer ist > Produktionsdaten, keine Trainingsdaten
        grouped_data_log_rename = grouped_data_log.rename(columns={'Vollständiger Name': 'Vollstaendiger Name', ('Komponente', 'Anzahl Geführte Touren'): ('Komponente', 'Anzahl Gefuehrte Touren'), ('Komponente', 'Anzahl Übersicht für Teilnehmer/in'): ('Komponente', 'Anzahl Uebersicht fuer Teilnehmer/in'), ('Komponente', 'Anzahl Übersicht'): ('Komponente', 'Anzahl Uebersicht')})
        # gleich als CSV file abspeichern
        filename = DATAPREP_REALDATA_FOLDERNAME_LOG + '/' + DATAPREP_REALDATA_FILENAME_LOG
        grouped_data_log_rename.to_csv(filename, index=False)
        print(f'CSV-Datei mit Testdaten wurde erstellt. Dateiname: {filename}')
        return grouped_data_log.head()
    else:
        # ansonsten Spalte mit den Noten anpassen:
        # Bewertung / 100 ergibt die Schulnote
        grade_csv['bewertung'] = grade_csv['bewertung']/100
        # Wenn es zu dem User keine Bewertung gibt - ersetzte NaN mit 5.0
        grade_csv['bewertung'] = grade_csv['bewertung'].fillna(5.0)
        # Abschlussnote aus dem zweiten df grade_data_log dem jeweiligen User zuordnen
        grouped_data_grade = pd.merge(grouped_data_log, grade_csv, on='Vollständiger Name', how='left')
        grouped_data_grade = grouped_data_grade.rename(columns={'Vollständiger Name': 'Vollstaendiger Name', ('Komponente', 'Anzahl Geführte Touren'): ('Komponente', 'Anzahl Gefuehrte Touren'), ('Komponente', 'Anzahl Übersicht für Teilnehmer/in'): ('Komponente', 'Anzahl Uebersicht fuer Teilnehmer/in'), ('Komponente', 'Anzahl Übersicht'): ('Komponente', 'Anzahl Uebersicht')})
        grouped_data_grade['bewertung'] = grouped_data_grade['bewertung'].fillna(5.0)
        # Als CSV-file abspeichern
        filename = DATAPREP_REALDATA_FOLDERNAME + '/' + DATAPREP_REALDATA_FILENAME
        grouped_data_grade.to_csv(filename, index=False)
        print(f'CSV-Datei mit Traindaten wurde erstellt. Dateiname: {filename}')
        return grouped_data_grade.head()

check_grades(grade_data)


def load_source(self):
        """Load the source for the specified file."""
        if self.filename in self.STDIN_NAMES:
            self.filename = "stdin"
            if sys.version_info[0] < 3:
                self.source = sys.stdin.read()
            else:
                self.source = TextIOWrapper(sys.stdin.buffer, errors="ignore").read()
        else:
            # Could be a Python 2.7 StringIO with no context manager, sigh.
            # with tokenize_open(self.filename) as fd:
            #     self.source = fd.read()
            handle = tokenize_open(self.filename)
            self.source = handle.read()
            handle.close()


N = int(input())
request = list(map(int, input().split()))
M = int(input())

left = M // N
right = max(request)

result = []
while not right < left :
  budget = 0
  mid = (left + right) // 2
  for i in request :
    if i <= mid :
      budget += i #요청액이 상한액보다 적은 경우 요청액을 배정
    else :
      budget += mid #요청액이 상한액보다 많은 경우 상한액을 배정
  if M - budget < 0 : #예산 범위를 넘어가면 상한액을 줄인다
    right = mid - 1
  else :
    result.append(mid) #예산 범위 안에 들어가면 상한액을 저장한다
    left = mid + 1

print(max(result))


#!/usr/bin/env python3

import re
import subprocess
import os

def touch(fname, times=None):
    with open(fname, 'a'):
        os.utime(fname, times)

def interface2embedded_interface(interface_cpp):
    v_re = re.compile(r'ui_interface->open\w*\("v(_bas|)(\d+)"\);')
    add_re = re.compile(r'ui_interface->add\w*\(("\w*", &\w*),')
    ch_lines = []
    cur_voice = ''
    cur_voice_type = ''
    max_voice = -1
    for line in interface_cpp:
        line = line.strip()
        if line.startswith('ui_interface->open'):
            v = v_re.findall(line)
            if v:
                cur_voice_type = v[0][0]
                cur_voice = v[0][1]
                if int(cur_voice) > max_voice:
                    max_voice = int(cur_voice)
        elif line.startswith('ui_interface->add'):
            par = add_re.findall(line)[0].split(',')
            name = par[0].strip('"')
            loc = par[1].strip()
            if name in ('acc_abs','acc_x','acc_y','acc_z','rot_x','rot_y','rot_z','pedal'):
                ch_lines.append('synth_interface.{} = {};'.format(name, loc))
            elif cur_voice and name in ('note','pres','vpres','but_x','but_y'):
                ch_lines.append('synth_interface{}.{}[{}] = {};'.format(
                    cur_voice_type, name, cur_voice, loc))

    return ch_lines, max_voice

def faust_postprocess(source):

    # disable cmath, gives compile error since ubuntu 15.10
    source = source.replace('#include <cmath>', '//#include <cmath>')

    # remove clone method as it uses the unsupported new operator
    source = source.replace('\tvirtual mydsp* clone() {\n\t\treturn new mydsp();\n\t}', '')

    # replace interface function with simpler version without strings
    start = source.find('virtual void buildUserInterface(UI* ui_interface) {')
    stop = source.find('}',start)
    interface_embedded, max_voice = interface2embedded_interface(source[start:stop].splitlines())

    new_source = ''.join((
        source[:start],
        'virtual void buildUserInterfaceEmbedded() {\n\t\t',
        '\n\t\t'.join(interface_embedded),
        '\n\t',
        source[stop:]))

    return new_source, max_voice

def faust_replace_fixed_sliders(faust_in):
    replace_slider = re.compile(r'hslider\(".*",([^,]*),[^)]*\)')
    return replace_slider.sub(r'\1',faust_in)

def main():
    faust_source = 'synth.dsp'
    faust_template = 'faust_synth_template.cpp'

    tmp_file = faust_source + '.tmp'

    # preprocess: replace hsliders with fixed values, useful for quick testing
    # of settings on the pc but compiling the as fixed on embedded platform.
    # vsliders stay variable.
    with open(tmp_file,'w') as f:
        f.write(faust_replace_fixed_sliders(open(faust_source).read()))

    # run faust compiler
    faust_cpp = subprocess.check_output(['faust','-a',faust_template,tmp_file,'-lang','ocpp']).decode()

    # do some postprocessing for efficient embedded use
    faust_cpp, max_voice = faust_postprocess(faust_cpp)
    with open('synth.cpp','w') as f:
        f.write(faust_cpp)

    # change VOICECOUNT in 'synth.h' if different from voicecount in synth.dsp
    synth_h = open('synth.h').readlines()
    vc_line = [n for n,line in enumerate(synth_h) if line.startswith('#define VOICECOUNT')][0]
    vc = int(synth_h[vc_line].split()[-1])
    if vc != max_voice + 1:
        synth_h[vc_line] = '#define VOICECOUNT {}\n'.format(max_voice+1)
        with open('synth.h', 'w') as f:
            f.writelines(synth_h)
        # make sure synth_contol gets compiled again
        touch('synth_control.cpp')

if __name__ == '__main__':
    main()


import time

from vkwave.bots import (
    TokenStorage,
    Dispatcher,
    BotLongpollExtension,
    DefaultRouter,
    GroupId,
    EventTypeFilter,
    ChatActionFilter,
    CommandsFilter,
    PayloadFilter,
)
from vkwave.types.objects import MessagesMessageActionStatus
from vkwave.types.bot_events import BotEventType
from vkwave.bots.core.dispatching.filters.base import BaseFilter, BaseEvent, FilterResult
from modules.commands.utils import *
from modules.databox import DataBox
from modules.commands import (
    kick,
    broadcast,
    utils,
    checkuser,
    test,
    chatcontrol,
    ban,
    system,
    chatstatuses,
    talker,
    keyboard,
    config,
    chattools,
    delete,
)

@log_and_respond_decorator
async def do_as_someone(box): # just cause
    target = box.get_id_from_word(box.text_list(2))
    if not target:
        return (False, 'Wrong target', 'Wrong target')

    new_text = ' '.join(box.text_list()[0:1] + box.text_list()[3:])
    old_from_id = box.event.object.object.message.from_id

    box.event.object.object.message.text = new_text
    box.event.object.object.message.from_id = target

    await command(box.event)
    box.event.object.object.message.from_id = old_from_id

    return (True, f"Done as {target}", f"Done as [id{target}|*id{target}]")

@log_and_respond_decorator
async def do_from_somewhere(box): # just cause
    if len(box.chats) > 1:
        return (False, 'Only one chat needed', 'Only one chat needed')

    if box.chats:
        target = box.chats[0]
    else:
        target = box.get_id_from_word(box.text_list(2))

    if not target:
        return (False, 'Wrong chat', 'Wrong chat')

    new_text = ' '.join(box.text_list()[0:1] + box.text_list()[3:])
    old_peer_id = box.event.object.object.message.peer_id

    box.event.object.object.message.peer_id = target
    box.event.object.object.message.text = new_text

    await command(box.event)
    box.event.object.object.message.peer_id = old_peer_id

    return (True, f"Done from {target}", f"Done from {target}")

command_dict = {
    'kick' : {'obj' : kick.kick_for_handle, 'level' : 1},
    'broadcast' : {'obj' : broadcast.broadcast, 'level' : 3},
    'op' : {'obj' : chatcontrol.add_admin, 'level' : 4},
    'deop' : {'obj' : chatcontrol.del_admin, 'level' : 4},
    'addchat' : {'obj' : chatcontrol.add_chat, 'level' : 3},
    'delchat' : {'obj' : chatcontrol.del_chat, 'level' : 3},
    'addgroup' : {'obj' : chatcontrol.add_group, 'level' : 3},
    'delgroup' : {'obj' : chatcontrol.del_group, 'level' : 3},
    'addchattogroup' : {'obj' : chatcontrol.add_chat_to_group, 'level' : 3},
    'delchatfromgroup' : {'obj' : chatcontrol.del_chat_from_group, 'level' : 3},
    'addadmin' : {'obj' : chatcontrol.add_admin_to_chat, 'level' : 3},
    'deladmin' : {'obj' : chatcontrol.del_admin_from_chat, 'level' : 3},
    'ban' : {'obj' : ban.add_ban, 'level' : 1},
    'forgive' : {'obj' : ban.del_ban, 'level' : 2},
    'permban' : {'obj' : ban.add_perm_ban, 'level' : 2},
    'delpermban' : {'obj' : ban.del_perm_ban, 'level' : 3},
    'uptime' : {'obj' : system.uptime, 'level' : 1},
    'stop' : {'obj' : system.stop, 'level' : 4},
    'log' : {'obj' : system.log, 'level' : 4},
    'clearlog' : {'obj' : system.clear_log, 'level' : 4},
    'mute' : {'obj' : chatstatuses.add_mute, 'level' : 2},
    'unmute' : {'obj' : chatstatuses.del_mute, 'level' : 2},
    'closegate' : {'obj' : chatstatuses.add_gate, 'level' : 2},
    'opengate' : {'obj' : chatstatuses.del_gate, 'level' : 2},
    'chatstatus' : {'obj' : chatstatuses.get_chat_statuses, 'level' : 1},
    'actt' : {'obj' : talker.activate_talker, 'level' : 3},
    'deactt' : {'obj' : talker.deactivate_talker, 'level' : 3},
    'setcatch' : {'obj' : config.set_enter_count, 'level' : 3},
    'settarget' : {'obj' : config.set_target_count, 'level' : 3},
    'targets' : {'obj' : config.get_target_count, 'level' : 1},
    'savebase' : {'obj' : system.base_save, 'level' : 4},
    'loadbase' : {'obj' : system.base_load, 'level' : 4},
    'chats' : {'obj' : chattools.aviable_chats, 'level' : 1},
    'loglevel' : {'obj' : config.log_level, 'level' : 4},
    'admins' : {'obj' : system.get_admins, 'level' : 3},
    'banlist' : {'obj' : system.get_banlist, 'level' : 3},
    'as' : {'obj' : do_as_someone, 'level' : 4},
    'from' : {'obj' : do_from_somewhere, 'level' : 4},
    'delete' : {'obj' : delete.delete_message, 'level' : 2},
    'clear' : {'obj' : delete.clean_conversation, 'level' : 2},
    's' : {'obj' : chattools.search, 'level' : 4}

}

async def test(event):
    box = DataBox(event)

async def new_user(event):
    box = DataBox(event)
    if box.msg.action.type is MessagesMessageActionStatus.CHAT_INVITE_USER\
        or box.msg.action.type is MessagesMessageActionStatus.CHAT_INVITE_USER_BY_MESSAGE_REQUEST:
        user_id = box.msg.action.member_id
    elif box.msg.action.type is MessagesMessageActionStatus.CHAT_INVITE_USER_BY_LINK:
        user_id = box.msg.from_id
    await checkuser.check_all(box, user_id)

async def simple_msg(event):
    box = DataBox(event)
    if base.is_muted(box.msg.from_id, box.msg.peer_id):
        if not base.is_chat_admin(box.msg.from_id, box.msg.peer_id):
            await kick.initiate_kicks(box.api, box.msg.peer_id, box.msg.from_id, msg_del=True)

    if box.msg.peer_id > 2*10**9:
        if box.msg.peer_id not in stor.vault['chats'].keys():
            await log_respond(box, f"VOID in {box.msg.peer_id-2*10**9} from {box.msg.from_id} - {box.msg.text}")

    await talker.talker_handle(box)

async def command(event):
    box = DataBox(event)
    if box.command in command_dict.keys():
        if box.admin_level >= command_dict[box.command]['level']:
            try:
                if box.admin_level <= 2 and command_dict[box.command]['level'] > 0:
                    box.targets = await base.handle_targets(box.msg.from_id, box.targets, int(time.time())+stor.time_day)
                await command_dict[box.command]['obj'](box)
            except Exception as e:
                raise SystemExit(e)
    if box.admin_level == 0:
        await simple_msg(event)

async def keyboard_msg(event):
    box = DataBox(event)
    if not await keyboard.handle_keyboard(box):
        await simple_msg(event)

class CommandFilter(BaseFilter):
    def __init__(self):
        pass

    async def check(self, event:BaseEvent) -> FilterResult:
        text = event.object.object.message.text.lower()
        from_id = event.object.object.message.from_id
        peer_id = event.object.object.message.peer_id
        result = False
        if text.startswith(f"[club{event.object.group_id}|"):
            result = True
        elif text.startswith("do") and peer_id == from_id:
            result = True
        return FilterResult(result)

async def initiate_router(router):
    # router.registrar.register(
    #     router.registrar.new()
    #     .handle(test)
    #     .ready()
    # )

    router.registrar.register(
        router.registrar.new()
        .with_filters(
            EventTypeFilter('message_new') & (
            ChatActionFilter(MessagesMessageActionStatus.CHAT_INVITE_USER) |
            ChatActionFilter(MessagesMessageActionStatus.CHAT_INVITE_USER_BY_LINK)
            )
        )
        .handle(new_user)
        .ready()
    )

    router.registrar.register(
        router.registrar.new()
        .with_filters(
            EventTypeFilter('message_new') & # without callback button support!
            PayloadFilter(None)
        )
        .handle(keyboard_msg)
        .ready()
    )

    router.registrar.register(
        router.registrar.new()
        .with_filters(
            EventTypeFilter('message_new') &
            CommandFilter()
        )
        .handle(command)
        .ready()
    )

    router.registrar.register(
        router.registrar.new()
        .with_filters(
            EventTypeFilter('message_new')
        )
        .handle(simple_msg)
        .ready()
    )
    return router


from pyspark.sql import SparkSession
import uuid
from com.db.fw.etl.core.Exception.EtlExceptions import InvalidParamsException
from com.db.fw.etl.core.common.Commons import Commons

class IOService:

    def __init__(self):
        self.spark = SparkSession.builder.getOrCreate()

    IO_SERVICE_STATUS= True

    def cleanup_msg(self,message):
        if message is not None:
            message = message.replace("'","")
        return message

    def store_pipeline_status(self, pipeline_name, pipeline_instance_id, status, time, error):
        if IOService.IO_SERVICE_STATUS == False :
            return None;

        tmp_uuid = str(uuid.uuid1())
        sql_stmt = "INSERT INTO  tata_poc.pipeline_status VALUES('{}', '{}', '{}','{}','{}','{}')".format(tmp_uuid,
                                                                                pipeline_name,
                                                                                pipeline_instance_id,
                                                                                status, time,
                                                                                self.cleanup_msg(str(error)))
        self.spark.sql(sql_stmt)

    def store_task_status(self,  pipeline_name, pipeline_instance_id, name, status, time, error):
        if IOService.IO_SERVICE_STATUS == False :
            return None;
        tmp_uuid =  str(uuid.uuid1())
        sql_stmt = "INSERT INTO  tata_poc.task_status VALUES('{}', '{}', '{}','{}','{}','{}','{}')".format(tmp_uuid,
                                                                                pipeline_name,
                                                                                pipeline_instance_id,
                                                                                name,
                                                                                status,
                                                                                time,
                                                                                self.cleanup_msg(str(error)))
        self.spark.sql(sql_stmt)

    def store_operational_stats(self, pipeline_instance_id, pipeline_name, task_name, stats ,time,batch_id):
        # if IOService.IO_SERVICE_STATUS == False :
        #     return None;
        print("store_operation_stats I am here inside")
        INSERT_STMT = "INSERT INTO  tata_poc.operational_stats VALUES "
        comma_sept_for_values =""
        for stat_name , state_value in stats.items():

            values_stmt  = "{} ( '{}', '{}','{}','{}','{}','{}',{})  ".format(comma_sept_for_values,
                pipeline_instance_id, pipeline_name, task_name, stat_name, state_value, time,batch_id)
            comma_sept_for_values = ","

            INSERT_STMT = INSERT_STMT + values_stmt

        Commons.printInfoMessage(INSERT_STMT)
        self.spark.sql(INSERT_STMT)

    def store_pipeline_metadata(self, out_pip_id, out_name, out_jsons):
        if IOService.IO_SERVICE_STATUS == False :
            return None;
        sql_stmt = "INSERT INTO  tata_poc.pipeline_metadata  VALUES('{}', '{}', '{}')".format(out_pip_id, out_name,
                                                                                out_jsons)
        self.spark.sql(sql_stmt)

    def get_pipeline_metadata(self, pipeline_name, task_name):

        sql_stmt = "select * from tata_poc.pipeline_metadata  where pipeline_name == '{}'".format(pipeline_name)
        meta_values = self.spark.sql(sql_stmt).collect()
        if len(meta_values) <= 0:
            raise InvalidParamsException(task_name, pipeline_name, {})

        pipeline_id = meta_values[0].pipeline_id
        pipeline_name = meta_values[0].pipeline_name
        node_defination = meta_values[0].node_defination
        return pipeline_id, pipeline_name, node_defination


import requests
import pandas as pd
import re
import json

pd.set_option('display.max_columns', None)

url = "https://ws.cso.ie/public/api.jsonrpc"

# Define a function to clean characters
def clean_string(s):
	return str(s).replace('\r', '').replace('"', '')

# Define the JSON-RPC request payload

# Define the JSON-RPC request payload
payload = {
	"jsonrpc": "2.0",
	"method": "PxStat.Data.Cube_API.ReadDataset",
	"params": {
		"class": "query",
		"id": [],
		"dimension": {},
		"extension": {
			"language": {
				"code": "en"
			},
			"format": {
				"type": "CSV",
				"version": "1.0"
			},
			"matrix": "RIA02"
		},
		"version": "2.0"
	}
}

# Make the POST request
response = requests.post(url, json=payload)

# Check if the request was successful (status code 200)
if response.status_code == 200:
	data = response.json()
	data_result = data['result']
	lines = data_result.split('\r')
	#print(lines)
	data_result = [re.findall(r'"([^"]*)"', line) for line in lines[1:]]
	#df = pd.DataFrame(data_result, columns=['Year Label', 'Year', 'Bedrooms Label', 'Property Type Label', 'Value'])
	print(data_result)
else:
	print(f"Error connecting to API. Status code: {response.status_code}")


import os

user_input = input('Dir: ')
directory = os.listdir(user_input)

searchstring = bytes(input('Bytes: '), 'utf-8').lower()

for fname in directory:
    if os.path.isfile(user_input + os.sep + fname):
        f = open(user_input + os.sep + fname, 'rb')

        if searchstring in f.read().lower():
            print('found string in file %s' % fname)
        f.close()


pets = []

pet = {'species': 'cat',
    'name': 'whisker',
    'owner': 'Theo',
    'weight': str(36)+ "kg",
    'eats': 'rats',}
pets.append(pet)

pet = {'species': 'parrot',
    'name': 'Rio',
    'owner': 'Bob',
    'weight': str(9)+ "kg",
    'eats': 'seeds',}
pets.append(pet)

pet = {'species': 'dog',
    'name': 'Bond',
    'owner': 'Anya',
    'weight': str(36)+ "kg",
    'eats': 'bones',}
pets.append(pet)

for pet in pets:
    print("\nAbout " + pet['name'].title() + ":")
    for key, value in pet.items():
        print("\t" + key + ": " + str(value))

Chapter 5- Dictionaries/Answers/exercise 5.py


# -*- coding: utf-8 -*-
"""
Created on Sun May 22 16:10:12 2022

@author: guido
"""

import pandas as pd
from one.api import ONE
one = ONE()

# Load in data
chan_volt = pd.read_parquet('C:\\Users\\guido\\Data\\EphysAtlas\\channels_voltage_features.pqt')
all_pids = chan_volt.index.get_level_values(level='pid').unique()

mm_coord = pd.DataFrame()
for i, pid in enumerate(all_pids):
    print(f'Insertion {i} of {len(all_pids)}')
    sess_info = one.alyx.rest('insertions', 'list', id=pid)
    traj = one.alyx.rest('trajectories', 'list', session=sess_info[0]['session'],
                         probe=sess_info[0]['name'], provenance='Micro-manipulator')
    if len(traj) != 1:
        continue
    mm_coord = pd.concat((mm_coord, pd.DataFrame(index=[pid], data={
        'x': traj[0]['x'],
        'y': traj[0]['y'],
        'depth': traj[0]['depth'],
        'theta': traj[0]['theta'],
        'phi': traj[0]['phi'],})))

# Save to disk
mm_coord.to_parquet('C:\\Users\\guido\\Data\\EphysAtlas\\coordinates.pqt')


# -*- coding: utf-8 -*-
"""
Carter Rhea <crhea@g.cofc.edu>
September 17, 2015
This will solve quadratics and then print out the roots!!!!!!
"""

from math import sqrt
## now we solve for roots that are real and imaginary...
def imaginary(a,b,c,d):
     real = -b/(2*a)
     imaginary = sqrt(abs(d))/(2*a)
     root0 = real+imaginary*1j
     root1 = real-imaginary*1j
     return [root0,root1]

def real(a,b,c,d):
    if (a==0 and b==0):
        if c ==0:
            print('0=0')
            return 0
        else:
            print('This isnt even true!')
            return 0
    elif a !=0:
        if d > 0:
            root0 = (-b + sqrt(b**2 - 4 * a * c))/(2 * a)
            root1 = (-b - sqrt(b**2 - 4 * a * c))/(2 * a)
            return [root0,root1]
        elif d == 0:
            root0 = -b/(2*a)
            return[root0,'since the discriminant equals 0 there is only 1 root']
    elif a==0:
        root0 = -c/b
        return [root0,'the equation is linear and only has 1 root!']
    elif a==0 and c==0 and b!=0:
        root0==0
        return[0,'the only root is 0']

def quadsolver(a,b,c):
    d = b**2-4*a*c
    if d <0:
        return imaginary(a,b,c,d)
    if d>=0:
        return real(a,b,c,d)
def main():
    for (x,y,z) in [[2,-10,8],[1,-2,1],[1,0,2],[1,6,25],[0,4,-10]]:
        roots = quadsolver(x,y,z)
        print('The roots of',x,'x^2+',y,'x+',z,'are',roots[0], 'and', roots[1])

main()


# Rejurhf
# 2.12.2018

import numpy
from matplotlib import pyplot as plt

# du/dt = v(d^2u)/(dx^2) 1d diffusion equation
# After discretizing
# (d^2u)/(dx^2) = (u[i+1]-2u[i]+u[i-1])/delx^2 + O(delx^2)

# Initial Conditions
nx = 41
dx = 2 / (nx - 1)
nt = 20    # the number of timesteps we want to calculate
nu = 0.3   # the value of viscosity
sigma = .2 # sigma is a parameter
dt = sigma * dx**2 /nu # dt is defined using sigm
print(dt)

u = numpy.ones(nx)      # a numpy array with nx elements all equal to 1.
#setting u = 2 between 0.5 and 1 as per our I.C.s
u[int(.5 / dx):int(1 / dx + 1)] = 2

# Calculation
un = numpy.ones(nx) # our placeholder array, un, to advance the solution in time
for n in range(nt):  # iterate through time
    un = u.copy() # copy the existing values of u into un
    for i in range(1, nx - 1):
        u[i] = un[i] + nu * dt / dx**2 * (un[i+1] - 2 * un[i] + un[i-1])

    plt.plot(numpy.linspace(0, 2, nx), u);
plt.show();


def product_list(n):
	product_list = []
	for i in range(1,10**n):
		for j in range(1,10**n):
			if i*j in product_list:
				continue
			else:
				product_list.append(i*j)
	return product_list

def rev(n):
	a = 0
	while n > 0:
		a = (a*10)+(n%10)
		n = n/10
	return a

def palindrome(n):
	palindrome_list = []
	for b in product_list(n):
		if rev(b) == b:
			palindrome_list.append(b)
		else:
			continue
	return palindrome_list

def main():
	number = input("largest palindromic product of how many digit numbers?")
	print(palindrome(number))

if __name__ == '__main__':
	main()


import os
os.system('cls' if os.name == 'nt' else 'clear')

# Calculation =
# ((income - expenses)*12) / Investment
#
# Investment

class Cart():

    def __init__(self, investment = 0, income = 0, expenses = 0, roi = 0.0):
        self.investment = investment
        self.income = income
        self.expenses = expenses
        self.roi = roi

    def addInvestment(self):

        investment = input("What is your investment in this property (in whole numbers)? ")
        if investment.isalpha():
            investment = input("Please enter a valid dollar amount: ")
        if int(investment) < 0:
            investment = input("Please enter a valid dollar amount: ")
        else:
            self.investment = investment
            print(f"The following investment amount was added: {self.investment}")
            print()

        income = input("What is your anticipated monthly income from this property? ")
        if income.isalpha():
            income = input("Please enter a valid dollar amount: ")
        if int(income) < 0:
            income = input("Please enter a valid dollar amount: ")
        else:
            self.income = income
            print(f"The following income amount was added: {self.income}")
            print()

        expenses = input("What are your anticipated monthly expenses for this property? ")
        if expenses.isalpha():
            expenses = input("Please enter a valid dollar amount: ")
        if int(expenses) < 0:
            expenses = input("Please enter a valid dollar amount: ")
        else:
            self.expenses = expenses
            print(f"The following expense amount was added: {self.expenses}")

        if int(self.investment) <=0:
            print("Investment is $0")
            self.roi = ((int(self.income) - int(self.expenses)) * 12) / .01
            print(f"The projected ROI for this property is {self.roi}%")
            print()

        elif int(self.investment) > 0 and int(self.income) >= 0 and int(self.expenses) >= 0:
            roi = ((int(self.income) - int(self.expenses)) * 12) / int(self.investment)
            print(f"The projected ROI for this property is {self.roi}%")
            print()

        print("Thank you for using the Wealth Builder app!")
        print("What would you like to do next?")

def run():

    my_portfolio = Cart({})

    print("Welcome to Real Estate Wealth Builder!")
    print("What would you like to do today?")

    while True:
        print('''
        C: Calculate property ROI
        Q: Quit
        ''')
        response = input("Enter choice here: ")

        if response.lower() not in ["c","q"]: #membership check
            response = input('Please enter a VALID choice: ')

        if response.lower() == "q":
            os.system('cls' if os.name == 'nt' else 'clear')
            break

        elif response.lower() == 'c':
               my_portfolio.addInvestment()

run()


import tensorflow as tf
from tensorflow.keras.layers import Layer

class ClusteringLayer(Layer):
    def __init__(self, centroids = None, n_clusters = None, n_features = None, alpha=1.0, **kwargs):
        """ The clustering layer predicts the a cell's class membership probability for each cell.

        Arguments:
        ------------------------------------------------------------------
        - centroids: `tf.Tensor`, Initial cluster ceontroids after pretraining the model.
        - n_clusters: `int`, Number of clusters.
        - n_features: `int`, The number of features of the bottleneck embedding space that the centroids live in.
        - alpha: parameter in Student's t-distribution. Default to 1.0.
        """

        super(ClusteringLayer, self).__init__(**kwargs)
        self.alpha = alpha
        self.initial_centroids = centroids

        if centroids is not None:
            n_clusters, n_features = centroids.shape

        self.n_features, self.n_clusters = n_features, n_clusters

        assert self.n_clusters is not None
        assert self.n_features is not None

    def build(self, input_shape):
        """ This class method builds the layer fully once it receives an input tensor.

        Arguments:
        ------------------------------------------------------------------
        - input_shape: `list`, A list specifying the shape of the input tensor.
        """

        assert len(input_shape) == 2

        self.centroids = self.add_weight(name = 'clusters', shape = (self.n_clusters, self.n_features), initializer = 'glorot_uniform')
        if self.initial_centroids is not None:
            self.set_weights([self.initial_centroids])
            del self.initial_centroids

        self.built = True

    def call(self, x, **kwargs):
        """ Forward pass of the clustering layer,

        ***Inputs***:
            - x: `tf.Tensor`, the embedding tensor of shape = (n_obs, n_var)

        ***Returns***:
            - q: `tf.Tensor`, student's t-distribution, or soft labels for each sample of shape = (n_obs, n_clusters)
        """

        q = 1.0 / (1.0 + (tf.reduce_sum(tf.square(tf.expand_dims(x, axis = 1) - self.centroids), axis = 2) / self.alpha))
        q = q**((self.alpha + 1.0) / 2.0)
        q = q / tf.reduce_sum(q, axis = 1, keepdims = True)

        return q

    def compute_output_shape(self, input_shape):
        """ This method infers the output shape from the input shape.

        Arguments:
        ------------------------------------------------------------------
        - input_shape: `list`, A list specifying the shape of the input tensor.

        Returns:
        ------------------------------------------------------------------
        - output_shape: `list`, A tuple specifying the shape of the output for the minibatch (n_obs, n_clusters)
        """

        assert input_shape and len(input_shape) == 2
        return input_shape[0], self.n_clusters