import numpy as np
import pp
from pp.routing.connect import connect_strip
from pp.routing.connect import connect_elec
from pp.port import is_electrical_port
from pp.port import flipped

BEND_RADIUS = pp.config.BEND_RADIUS

def route_elec_ports_to_side(ports, side="north", wire_sep=20.0, x=None, y=None):
    return route_ports_to_side(
        ports, side=side, bend_radius=0, separation=wire_sep, x=x, y=y
    )

def route_ports_to_side(
    ports, side="north", x=None, y=None, routing_func=None, **kwargs
):
    """ Routes ports to a given side

    Args:
        ports: the list of ports to be connected to the side
            can also be a dictionnary, a <pp.Component> or a phidl
            <ComponentReference>
        side should be 'north', 'south', 'east' or 'west'

        x: only for east/west side routing: the x position where the ports should be sent
            If None, will use the eastest/westest value

        y: only for south/north side routing: the y position where the ports should be send
            If None, will use the southest/northest value

        routing_func: the routing function. By default uses either `connect_elec`
        or `connect_strip` depending on the ports layer.

        kwargs: may include:
            `bend_radius`
            `extend_bottom`, `extend_top` for east/west routing
            `extend_left`, `extend_right` for south/north routing
    """

    if not ports:
        return [], []

    # Accept list of ports, Component or dict of ports
    if isinstance(ports, dict):
        ports = list(ports.values())

    elif isinstance(ports, pp.Component) or isinstance(ports, pp.ComponentReference):
        ports = list(ports.ports.values())

    # Convenient default selection for connection function point to point
    if routing_func is None:
        if is_electrical_port(ports[0]):
            routing_func = connect_elec
        else:
            routing_func = connect_strip

    # Choose which
    if side in ["north", "south"]:
        func_route = connect_ports_to_y
        if y is not None:
            xy = y
        else:
            xy = side

    elif side in ["west", "east"]:
        if x is not None:
            xy = x
        else:
            xy = side

        func_route = connect_ports_to_x

    return func_route(ports, xy, routing_func=routing_func, **kwargs)

def route_ports_to_north(list_ports, **kwargs):
    return route_ports_to_side(list_ports, side="north", **kwargs)

def route_ports_to_south(list_ports, **kwargs):
    return route_ports_to_side(list_ports, side="south", **kwargs)

def route_ports_to_west(list_ports, **kwargs):
    return route_ports_to_side(list_ports, side="west", **kwargs)

def route_ports_to_east(list_ports, **kwargs):
    return route_ports_to_side(list_ports, side="east", **kwargs)

def connect_ports_to_x(
    list_ports,
    x="east",
    separation=10.0,
    bend_radius=BEND_RADIUS,
    extend_bottom=0,
    extend_top=0,
    extension_length=0,
    y0_bottom=None,
    y0_top=None,
    routing_func=connect_strip,
    routing_func_args={},
    backward_port_side_split_index=0,
):
    """
     * ``list_ports``: reasonably well behaved list of ports
            i.e
            ports facing north ports are norther than any other ports
            ports facing south ports are souther ...
            ports facing west ports are the wester ...
            ports facing east ports are the easter ...

     * ``x``: float or string:
                if float: x coordinate to which the ports will be routed
                if string: "east" -> route to east
                if string: "west" -> route to west

     * ``backward_port_side_split_index``: integer
            this integer represents and index in the list of backwards ports
                (bottom to top)
            all ports with an index strictly lower or equal are routed bottom
            all ports with an index larger or equal are routed top

    Returns:
        - a list of connectors which can be added to an element list
        - a list of the new optical ports

    """

    north_ports = [p for p in list_ports if p.angle == 90]
    south_ports = [p for p in list_ports if p.angle == 270]
    east_ports = [p for p in list_ports if p.angle == 0]
    west_ports = [p for p in list_ports if p.angle == 180]

    epsilon = 1.0
    a = epsilon + max(bend_radius, separation)
    xs = [p.x for p in list_ports]
    ys = [p.y for p in list_ports]

    if y0_bottom is None:
        y0_bottom = min(ys) - a
    y0_bottom -= extend_bottom

    if y0_top is None:
        y0_top = max(ys) + a
    y0_top += extend_top

    if x == "west" and extension_length > 0:
        extension_length = -extension_length

    if x == "east":
        x = max([p.x for p in list_ports]) + a
    elif x == "west":
        x = min([p.x for p in list_ports]) - a
    elif type(x) == float:
        pass
    else:
        pass
        # raise ValueError('``x`` should be a float or "east" or "west"')

    sort_key_west_to_east = lambda p: p.x
    sort_key_east_to_west = lambda p: -p.x

    sort_key_south_to_north = lambda p: p.y
    sort_key_north_to_south = lambda p: -p.y

    if x < min(xs):
        sort_key_north = sort_key_west_to_east
        sort_key_south = sort_key_west_to_east
        forward_ports = west_ports
        backward_ports = east_ports
        angle = 0

    elif x > max(xs):
        sort_key_south = sort_key_east_to_west
        sort_key_north = sort_key_east_to_west
        forward_ports = east_ports
        backward_ports = west_ports
        angle = 180
    else:
        raise ValueError("x should be either to the east or to the west of all ports")
    """
    First route the bottom-half of the back ports
        (back ports are the one facing opposite side of x)
    Then route the south ports
    then the front ports
    then the north ports
    """

    # forward_ports.sort()
    north_ports.sort(key=sort_key_north)
    south_ports.sort(key=sort_key_south)
    forward_ports.sort(key=sort_key_south_to_north)

    backward_ports.sort(key=sort_key_south_to_north)
    backward_ports_thru_south = backward_ports[0:backward_port_side_split_index]
    backward_ports_thru_north = backward_ports[backward_port_side_split_index:]
    backward_ports_thru_south.sort(key=sort_key_south_to_north)
    backward_ports_thru_north.sort(key=sort_key_north_to_south)

    elements = []
    ports = []

    def add_port(p, y, l_elements, l_ports, start_straight=0.01):
        new_port = p._copy()
        new_port.angle = angle
        new_port.position = (x + extension_length, y)
        l_elements += [
            routing_func(
                p,
                new_port,
                start_straight=start_straight,
                bend_radius=bend_radius,
                **routing_func_args
            )
        ]
        l_ports += [flipped(new_port)]

    y_optical_bot = y0_bottom
    for p in south_ports:
        add_port(p, y_optical_bot, elements, ports)
        y_optical_bot -= separation

    for p in forward_ports:
        add_port(p, p.y, elements, ports)

    y_optical_top = y0_top
    for p in north_ports:
        add_port(p, y_optical_top, elements, ports)
        y_optical_top += separation

    start_straight = 0.01
    start_straight0 = 0
    max_x = max(xs)
    min_x = min(xs)

    for p in backward_ports_thru_north:
        # Extend ports if necessary
        if angle == 0 and p.x < max_x:
            start_straight0 = max_x - p.x
        elif angle == 180 and p.x > min_x:
            start_straight0 = p.x - min_x
        else:
            start_straight0 = 0

        add_port(
            p,
            y_optical_top,
            elements,
            ports,
            start_straight=start_straight + start_straight0,
        )
        y_optical_top += separation
        start_straight += separation

    start_straight = 0.01
    start_straight0 = 0
    for p in backward_ports_thru_south:
        # Extend ports if necessary
        if angle == 0 and p.x < max_x:
            start_straight0 = max_x - p.x
        elif angle == 180 and p.x > min_x:
            start_straight0 = p.x - min_x
        else:
            start_straight0 = 0

        add_port(
            p,
            y_optical_bot,
            elements,
            ports,
            start_straight=start_straight + start_straight0,
        )
        y_optical_bot -= separation
        start_straight += separation

    return elements, ports

def connect_ports_to_y(
    list_ports,
    y="north",
    separation=10.0,
    bend_radius=BEND_RADIUS,
    x0_left=None,
    x0_right=None,
    extension_length=0,
    extend_left=0,
    extend_right=0,
    routing_func=connect_strip,
    routing_func_args={},
    backward_port_side_split_index=0,
):
    """
     * ``list_ports``: reasonably well behaved list of ports
            i.e
            ports facing north ports are norther than any other ports
            ports facing south ports are souther ...
            ports facing west ports are the wester ...
            ports facing east ports are the easter ...

     * ``y``: float or string:
                if float: y coordinate to which the ports will be routed
                if string: "north" -> route to north
                if string: "south" -> route to south

     * ``backward_port_side_split_index``: integer
            this integer represents and index in the list of backwards ports
                (sorted from left to right)
            all ports with an index strictly larger are routed right
            all ports with an index lower or equal are routed left

    Returns:
        - a list of connectors which can be added to an element list
        - a list of the new optical ports

    """

    if y == "south" and extension_length > 0:
        extension_length = -extension_length

    da = 45
    north_ports = [p for p in list_ports if p.angle > 90 - da and p.angle < 90 + da]
    south_ports = [p for p in list_ports if p.angle > 270 - da and p.angle < 270 + da]
    east_ports = [p for p in list_ports if p.angle < da or p.angle > 360 - da]
    west_ports = [p for p in list_ports if p.angle < 180 + da and p.angle > 180 - da]

    epsilon = 1.0
    a = bend_radius + max(bend_radius, separation)
    xs = [p.x for p in list_ports]
    ys = [p.y for p in list_ports]

    x0_right = x0_right or max(xs) + a
    x0_right += extend_right
    x0_left = x0_left or min(xs) - a
    x0_left -= extend_left

    if y == "north":
        y = (
            max([p.y + a * np.abs(np.cos(p.angle * np.pi / 180)) for p in list_ports])
            + epsilon
        )
    elif y == "south":
        y = (
            min([p.y - a * np.abs(np.cos(p.angle * np.pi / 180)) for p in list_ports])
            - epsilon
        )
    elif type(y) == float:
        pass
    else:
        pass
        # raise ValueError('``y`` should be a float or "north" or "south"')

    sort_key_west_to_east = lambda p: p.x
    sort_key_east_to_west = lambda p: -p.x
    sort_key_south_to_north = lambda p: p.y
    sort_key_north_to_south = lambda p: -p.y

    if y <= min(ys):
        sort_key_east = sort_key_south_to_north
        sort_key_west = sort_key_south_to_north
        forward_ports = south_ports
        backward_ports = north_ports
        angle = 90.0

    elif y >= max(ys):
        sort_key_west = sort_key_north_to_south
        sort_key_east = sort_key_north_to_south
        forward_ports = north_ports
        backward_ports = south_ports
        angle = -90.0
    else:
        raise ValueError("y should be either to the north or to the south of all ports")
    """
    First route the bottom-half of the back ports
        (back ports are the one facing opposite side of x)
    Then route the south ports
    then the front ports
    then the north ports
    """

    west_ports.sort(key=sort_key_west)
    east_ports.sort(key=sort_key_east)
    forward_ports.sort(key=sort_key_west_to_east)
    backward_ports.sort(key=sort_key_east_to_west)

    backward_ports.sort(key=sort_key_west_to_east)
    backward_ports_thru_west = backward_ports[0:backward_port_side_split_index]
    backward_ports_thru_east = backward_ports[backward_port_side_split_index:]

    backward_ports_thru_west.sort(key=sort_key_west_to_east)
    backward_ports_thru_east.sort(key=sort_key_east_to_west)

    elements = []
    ports = []

    def add_port(p, x, l_elements, l_ports, start_straight=0.01):
        new_port = p._copy()
        new_port.angle = angle
        new_port.position = (x, y + extension_length)

        if np.sum(np.abs((new_port.position - p.position) ** 2)) < 1e-12:
            l_ports += [flipped(new_port)]
            return

        try:
            l_elements += [
                routing_func(
                    p,
                    new_port,
                    start_straight=start_straight,
                    bend_radius=bend_radius,
                    **routing_func_args
                )
            ]
            l_ports += [flipped(new_port)]

        except Exception as e:
            print("**************************")
            print("Could not connect")
            print(p)
            print(new_port)
            print("**************************")
            raise e

    x_optical_left = x0_left
    for p in west_ports:
        add_port(p, x_optical_left, elements, ports)
        x_optical_left -= separation

    for p in forward_ports:
        add_port(p, p.x, elements, ports)

    x_optical_right = x0_right
    for p in east_ports:
        add_port(p, x_optical_right, elements, ports)
        x_optical_right += separation

    start_straight = 0.01
    for p in backward_ports_thru_east:
        add_port(p, x_optical_right, elements, ports, start_straight=start_straight)
        x_optical_right += separation
        start_straight += separation

    start_straight = 0.01
    for p in backward_ports_thru_west:
        add_port(p, x_optical_left, elements, ports, start_straight=start_straight)
        x_optical_left -= separation
        start_straight += separation

    return elements, ports

def demo():
    from pp.component import Component
    from pp.layers import LAYER

    def dummy():
        cmp = Component()
        xs = [0.0, 10.0, 25.0, 50.0]
        ys = [0.0, 10.0, 25.0, 50.0]
        a = 5
        xl = min(xs) - a
        xr = max(xs) + a
        yb = min(ys) - a
        yt = max(ys) + a

        cmp.add_polygon([(xl, yb), (xl, yt), (xr, yt), (xr, yb)], LAYER.WG)

        for i, y in enumerate(ys):
            p0 = (xl, y)
            p1 = (xr, y)
            cmp.add_port(name="W{}".format(i), midpoint=p0, orientation=180, width=0.5)
            cmp.add_port(name="E{}".format(i), midpoint=p1, orientation=0, width=0.5)

        for i, x in enumerate(xs):
            p0 = (x, yb)
            p1 = (x, yt)
            cmp.add_port(name="S{}".format(i), midpoint=p0, orientation=270, width=0.5)
            cmp.add_port(name="N{}".format(i), midpoint=p1, orientation=90, width=0.5)

        return cmp

    def top_level():
        cmp = Component()
        _dummy_t = dummy()
        sides = ["north", "south", "east", "west"]
        positions = [(0, 0), (400, 0), (400, 400), (0, 400)]
        for pos, side in zip(positions, sides):
            dummy_ref = _dummy_t.ref(position=pos)
            cmp.add(dummy_ref)
            conns, ports = route_ports_to_side(dummy_ref, side)
            for e in conns:
                cmp.add(e)
            for i, p in enumerate(ports):
                cmp.add_port(name="{}{}".format(side[0], i), port=p)
        return cmp

    pp.show(top_level())

if __name__ == "__main__":
    demo()


import CalculatorGUI
import SyllabusReader
import TableExtractor
import os
import tkinter as tk
from tkinter import filedialog
from pathlib import Path

def process_grade_pair(grade_pairs):
    """Create a calculator instance for grading categories."""
    calc = CalculatorGUI.Calculator()
    for category, weight_list in grade_pairs:
        if len(weight_list) == 1: # Only 1 instance of category
            calc.addRow(category, weight_list[0])
        else:
            # (Test, [50, 25]) represents 2 midterms each worth 25%
            total_weight = float(weight_list[0])
            individual_weight = float(weight_list[1])
            end_val = int(total_weight/individual_weight)
            for i in range(1, 1+end_val):
                calc.addRow(category+ str(i), individual_weight) # Label each test
    calc.mainloop()

def create_grade_calulator(filename, tables=False):
    """Return a calculator given a filename.

    Args:
        filename (str): filename of the syllabus.
        tables (bool, optional): Indicates if grading stored in table in syllabus. Defaults to False.
    """
    if tables:
        grade_pairs = TableExtractor.extract_grade_pairs(filename)
    else:
        grade_pairs = SyllabusReader.extract_grade_pairs(filename)
    process_grade_pair(grade_pairs)

if __name__ == "__main__":
    root = tk.Tk()
    root.withdraw()
    folder = filedialog.askdirectory()
    path = Path(folder)
    root.destroy()
    if path.is_dir():
        gen = (filepath for filepath in path.glob('*') if filepath.is_file())
        for filepath in gen:
            fp = str(filepath)
            extension = os.path.splitext(fp)[-1].lower()
            if extension in ('.png', '.jpg', '.jpeg', '.gif'): # Ignore images
                break

            fn = os.path.basename(fp)
            tables = input("Does %s contain a table? Answer yes (y) or no (n). " %fn)
            if tables.lower() == "yes" or tables.lower() == "y":
                create_grade_calulator(fp, True)
            else:
                create_grade_calulator(fp)


#!/usr/bin/env python
import pandas as pd
import matplotlib.pyplot as plt

def day_of_year():
	try:

		df1 = pd.read_csv('C:\\Users\\Jen\\Desktop\\train.csv', parse_dates=['Dates'])
		df2 = pd.read_csv('C:\\Users\\Jen\\Desktop\\test.csv', parse_dates=['Dates'])

	except (IOError, OSError) as e:
		print (e, "Check input file path")
	except Exception as r:
		print (r)
	else:

		frames = [df1, df2]
		df = pd.concat(frames) #concat test and train data , because data is split between both and to get the correct estimates in the plots/results
	try:
		df['DayOfYear'] = df['Dates'].map(lambda x: x.day) #  for the day of the year from the dates column

		df['HourOfDay'] = df['Dates'].map(lambda x: x.hour)

		df2 = df[['Category', 'DayOfYear']].groupby(['DayOfYear']).count()

		df3 = df[['Category', 'HourOfDay']].groupby(['HourOfDay']).count()

	except (ValueError, TypeError, KeyError, IndexError) as e:
		print (e)
	except Exception as g:
		print(g)
	else:
		print (df3.sort('Category', ascending=False).head())
		print (df2.sort('Category', ascending=False).head())
		'''
		We can see that highest crime occurance on the first of the month
		Could be reporting differences or because of the salary correlation at the beginning of the month
		Even criminals have to pay rent..
		Its interesting though how crime rates peak on the 1st, after plummeting towards the end of the month
		'''

		df2.plot(figsize=(25,10))
		plt.title("Crimes peak at the start of the month")
		plt.ylabel('Number of crimes')
		plt.xlabel('Day of year')
		plt.savefig('Distribution_of_Crimes_by_DayofYear.png')
		plt.show()
		df3.plot(figsize=(25,10))
		'''
		Shows us that most crimes occur around 6PM
		'''
		plt.title("Highest crime rate around 6PM")
		plt.ylabel('Number of crimes')
		plt.xlabel('Hour of the Day')
		plt.savefig('Distribution_of_Crimes_by_Hour_of_Day.png')

		plt.show()
		testing_pandas(df2)
		testing_pandas(df3)

def testing_pandas(dff):
	try:
		if (dff.empty == False): #checking if dataframe is empty
			print ("Test passed!")
	except Exception as e:
		print(e, "Failed!..Recheck!")

if __name__ == "__main__":
		day_of_year()


import os,pickle,time
def moneyfmt(x): return "${:,.2f}".format(x)+''
class Transaction:
	def __init__(self,amt,nts):
		self.amount=amt
		self.notes=nts
		self.ts=time.time()

	def __repr__(self):
		return(moneyfmt(self.amount)+': '+str(self.notes)+', '+time.ctime(self.ts))

class TransactionHistory:
	def __init__(self):
		self.transactions=list()

	def pop(self): return self.transactions.pop()

	def delete(self,index):
		index=int(index)
		del self.transactions[index]

	def add(self,amount,notes):
		if type(amount) not in [int,float]:
			raise ValueError('Amount must be number')
		if type(amount)==float:
			amount=round(amount,2)
		a,d=amount,notes
		self.transactions.append(Transaction(a,d))

	def balance(self):
		return moneyfmt(sum([x.amount for x in self.transactions]))
	def edit(self,index,amount=None,notes=None):
		if amount == None:
			amount=self.transactions[index].amount
		if notes == None:
			notes=self.transactions[index].notes
		self.transactions[index].amount = amount
		self.transactions[index].notes=notes
	def __repr__(self):
		o='[\n'
		d='\n'.join([' ['+str(c)+'] '+str(x) for c,x in enumerate(self.transactions)])
		o+=d+'\n] balance:'+str(self.balance())
		return o

if __name__=='__main__':
	target='transaction_history'
	root='/storage/emulated/0/'
	file=os.path.join(root,target)

	hist=TransactionHistory()
	if os.path.isfile(file):
		hist=pickle.load(open(file,"rb"))
	def save():
		pickle.dump(hist,open(file,'wb'))
		print('saved to',file)
	while(True):
		print('-'*60)
		print(hist)
		i=input('\n\ncontrol codes:\n c to create new transaction, or\n s to save, or\n d to delete a transaction\n u to remove newest transaction\n e to edit a transaction\n delfile to delete save file: ')
		i=i.lower().strip()
		if i=='c':
			a=float(input('\nenter amount: '))
			if a-int(a) == 0: a=int(a)
			d=input('enter any notes youd like: ')
			hist.add(a,d)
		elif i=='s':
			save()
		elif i=='d':
			n=input('\nenter index to delete: ')
			hist.delete(n)
		elif i=='u':
			hist.pop()
		elif i=='delfile':
			try:
				os.remove(file)
			except:
				print('error thrown for file deletion')
		elif i == 'e':
			ind=input('enter the index to edit: ')
			ind=int(ind.strip())
			print('selected, '+str(hist.transactions[ind]))
			a=input('enter amount (press enter to keep same): ')
			n=input('enter notes (press enter to keep same): ')
			if a.lower().strip() == '': a=None
			if n.lower().strip() == '': n=None
			hist.edit(ind,a,n)


import sqlalchemy as db
from sqlalchemy import Table, Column, Integer, String, MetaData

#cria o banco
engine = db.create_engine('sqlite:///banco.db', echo=True)

#cria uma coleçao de objetos de tabela
meta = MetaData()

class Db_Model():

    user_tbl = Table(
        'Usuario', meta,
        Column('id', Integer, primary_key = True),
        Column('nome', String),
        Column('cpf', String),
        Column('email', String),
        Column('data_cadastro', String),

    )

    #inserir dados
    def insert(self, user):

        ins = self.user_tbl.insert()
        ins = self.user_tbl.insert().values(nome = user['nome'] , cpf = user['cpf'], email = user['email'] , data_cadastro = user['data_cadastro'])
        conn = engine.connect()
        result = conn.execute(ins)
        return result

    #atualizar dados
  #  def atualizar(self, user):

   #     att = self.user_tbl.update(user).where(user.c.nome['nome'] == user['nome']).values(nome = user['nome'])
    #    conn = engine.connect()
   #     conn.execute(att)
   #     s = user_tbl.select()
   #     conn.execute(s).fetchall()

    #deleta do banco pelo ID
    #delete = user_tbl.delete().where(user_tbl.c.id > 1)
    #conn.execute(delete)


# -*- coding: utf-8 -*-
from tests import settings
from tests.resources import BankingAliasIBAN, BankingAlias
from tests.test_base import BaseTest, BaseTestLive

import responses

class BankingAliasesTest(BaseTest):

    @responses.activate
    def test_banking_alias(self):
        self.mock_natural_user()
        self.mock_natural_user_wallet()

        self.register_mock([
            {
                'method': responses.POST,
                'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/wallets/1169420/bankingaliases/iban',
                'body': {
                    "OwnerName": "Victor",
                    "IBAN": "LU32062DZDP2JLJU9RP3",
                    "BIC": "MPAYFRP1EMI",
                    "CreditedUserId":"25337926",
                    "Country":"LU",
                    "Tag": "null",
                    "CreationDate":1494384060,
                    "Active": True,
                    "Type":"IBAN",
                    "Id":"25337928",
                    "WalletId":"1169420"
                },
                'status': 200
            },
            {
                'method': responses.GET,
                'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/bankingaliases/25337928',
                'body': {
                    "OwnerName": "Victor",
                    "IBAN": "LU32062DZDP2JLJU9RP3",
                    "BIC": "MPAYFRP1EMI",
                    "CreditedUserId":"25337926",
                    "Country":"LU",
                    "Tag": "null",
                    "CreationDate":1494384060,
                    "Active": True,
                    "Type":"IBAN",
                    "Id":"25337928",
                    "WalletId":"1169420"
                },
                'status': 200
            },
            {
                'method': responses.GET,
                'url': settings.MANGOPAY_API_SANDBOX_URL+settings.MANGOPAY_CLIENT_ID+'/wallets/1169420/bankingaliases',
                'body': [
                    {
                    "OwnerName": "Victor",
                    "IBAN": "LU32062DZDP2JLJU9RP3",
                    "BIC": "MPAYFRP1EMI",
                    "CreditedUserId":"25337926",
                    "Country":"LU",
                    "Tag": "null",
                    "CreationDate":1494384060,
                    "Active": True,
                    "Type":"IBAN",
                    "Id":"25337928",
                    "WalletId":"1169420"
                }
                ],
                'status': 200
            }])

        bankingAlias = BankingAliasIBAN(
            wallet = self.natural_user_wallet,
            credited_user = self.natural_user,
            owner_name = self.natural_user.first_name,
            country ='LU'
        )
        bankingAlias.save()

        self.assertEqual(bankingAlias.country, 'LU')
        self.assertEqual(bankingAlias.iban, 'LU32062DZDP2JLJU9RP3')

        walletBankingAliases = BankingAlias(
            wallet = self.natural_user_wallet
        )
        allBankingAliases = walletBankingAliases.all()

        self.assertEqual(allBankingAliases[0].id, bankingAlias.id)
        self.assertEqual(allBankingAliases[0].wallet_id, bankingAlias.wallet_id)


import six
import os
import signal

from io import open

from oslo_log import log as logging
from oslo_config import cfg

from fuel_agent import errors
from fuel_agent.utils import build as bu
from fuel_agent.utils import fs as fu
from fuel_agent.utils import utils as fuel_utils

from fuel_additive.drivers.os import build

LOG = logging.getLogger(__name__)
CONF = cfg.CONF

class Image(object):
    def __init__(self, chroot, config):
        self.chroot = chroot
        self.config = config

    def stop_chroot_processes(self, force=False):
        if not bu.stop_chrooted_processes(self.chroot, signal=signal.SIGTERM):
            if not bu.stop_chrooted_processes(
                    self.chroot, signal=signal.SIGKILL):
                if not force:
                    raise errors.UnexpectedProcessError(
                        'Stopping chrooted processes failed. '
                        'There are some processes running in chroot %s',
                        self.chroot)

    def make_temp_space(self):
        LOG.info('*** Preparing image space ***')
        for image in self.config.image_scheme.images:
            LOG.debug('Creating temporary sparsed file for the '
                      'image: %s', image.uri)
            img_tmp_file = bu.create_sparse_tmp_file(
                dir=CONF.image_build_dir, suffix=CONF.image_build_suffix,
                size=CONF.sparse_file_size)
            LOG.debug('Temporary file: %s', img_tmp_file)

            # we need to remember those files
            # to be able to shrink them and move in the end
            image.img_tmp_file = img_tmp_file

            image.target_device.name = \
                bu.attach_file_to_free_loop_device(
                    img_tmp_file,
                    max_loop_devices_count=CONF.max_loop_devices_count,
                    loop_device_major_number=CONF.loop_device_major_number,
                    max_attempts=CONF.max_allowed_attempts_attach_image)

            # find fs with the same loop device object
            # as image.target_device
            fs = self.config.partition_scheme.fs_by_device(
                image.target_device)

            LOG.debug('Creating file system on the image')
            fu.make_fs(
                fs_type=fs.type,
                fs_options=fs.options,
                fs_label=fs.label,
                dev=six.text_type(fs.device))
            if fs.type == 'ext4':
                LOG.debug('Trying to disable journaling for ext4 '
                          'in order to speed up the build')
                utils.execute('tune2fs', '-O', '^has_journal',
                              six.text_type(fs.device))

    def mount_target(self, chroot, treat_mtab=True, pseudo=True):
        """Mount a set of file systems into a chroot

        :param chroot: Directory where to mount file systems
        :param treat_mtab: If mtab needs to be actualized (Default: True)
        :param pseudo: If pseudo file systems
        need to be mounted (Default: True)
        """
        LOG.debug('Mounting target file systems: %s', chroot)
        # Here we are going to mount all file systems in partition scheme.
        for fs in self.config.partition_scheme.fs_sorted_by_depth():
            mount = chroot + fs.mount
            fuel_utils.makedirs_if_not_exists(mount)
            fu.mount_fs(fs.type, str(fs.device), mount)

        if pseudo:
            for path in ('/sys', '/dev', '/proc'):
                fuel_utils.makedirs_if_not_exists(chroot + path)
                fu.mount_bind(chroot, path)

        if treat_mtab:
            mtab = fuel_utils.execute(
                'chroot', chroot, 'grep', '-v', 'rootfs', '/proc/mounts')[0]
            mtab_path = chroot + '/etc/mtab'
            if os.path.islink(mtab_path):
                os.remove(mtab_path)
            with open(mtab_path, 'wt', encoding='utf-8') as f:
                f.write(six.text_type(mtab))

    def make_work_space(self):
        self.make_temp_space()

    def setup_work_space(self):
        self.mount_target(treat_mtab=False, pseudo=False)
        bu.suppress_services_start(self.chroot)

    def umount_target(self, pseudo=True):
        LOG.debug('Umounting target file systems: %s', self.chroot)
        if pseudo:
            for path in ('/proc', '/dev', '/sys'):
                fu.umount_fs(self.chroot + path)
        for fs in self.config.partition_scheme.fs_sorted_by_depth(
                reverse=True):
            fu.umount_fs(self.chroot + fs.mount)

    def detach_images(self):
        LOG.debug('Finally: umounting chroot tree %s', self.chroot)

        for image in self.config.image_scheme.images:
            if image.target_device.name:
                LOG.debug('Finally: detaching loop device: %s',
                          image.target_device.name)
                try:
                    bu.deattach_loop(image.target_device.name)
                except errors.ProcessExecutionError as e:
                    LOG.warning('Error occured while trying to detach '
                                'loop device %s. Error message: %s',
                                image.target_device.name, e)
            if image.img_tmp_file:
                LOG.debug('Finally: removing temporary file: %s',
                          image.img_tmp_file)
                try:
                    os.unlink(image.img_tmp_file)
                except OSError:
                    LOG.debug('Finally: file %s seems does not exist '
                              'or can not be removed', image.img_tmp_file)

    def post_install(self):
        build.set_root_password(
            self.chroot, self.config.operating_system.get_user_by_name('root'))
        build.set_cloud_init(self.chroot)
        #  set puppet
        build.set_puppet(self.chroot)
        #  set mcollective
        build.set_mcollective(self.chroot)
        #  set selinux
        build.set_selinux(self.chroot)
        # set policy
        build.set_policy(self.chroot)
        # set grub2
        build.set_grub2(self.chroot)
        # set hosts
        build.set_hosts(self.chroot)

    def mount_proc(self):
        # we need /proc to be mounted for apt-get success
        LOG.debug('Preventing services from being get started')
        bu.suppress_services_start(self.chroot)
        fuel_utils.makedirs_if_not_exists(os.path.join(self.chroot, 'proc'))

        # we need /proc to be mounted for apt-get success
        fu.mount_bind(self.chroot, '/proc')
        bu.populate_basic_dev(self.chroot)

    def clean(self):
        self.stop_chroot_processes(force=True)
        self.umount_target()
        self.detach_images()
        try:
            os.rmdir(self.chroot)
        except OSError:
            LOG.debug('Finally: directory %s seems does not exist '
                      'or can not be removed', self.chroot)

class Ubuntu(Image):

    @property
    def proxies(self):
        return self.config.operating_system.proxies

    def install_base_os(self):
        build.install_base_ubuntu(self.chroot)
        self.set_update_apt()
        bu.suppress_services_start(self.chroot)
        self.mount_proc()

    def set_update_apt(self):
        LOG.debug('Configuring apt inside chroot')
        LOG.debug('Setting environment variables')
        bu.set_apt_get_env()
        LOG.debug('Allowing unauthenticated repos')
        bu.pre_apt_get(self.chroot,
                       allow_unsigned_file=CONF.allow_unsigned_file,
                       force_ipv4_file=CONF.force_ipv4_file,
                       proxies=self.proxies.proxies,
                       direct_repo_addr=self.proxies.direct_repo_addr_list)

    @classmethod
    def create(cls):
        return cls()


"""
Tkinter UI Widgets for War

Created by Karl Miller, 3/20/21
"""

from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import random

class PlayerWidget:
    def __init__(self, name):
        self.name = StringVar()  # this allows the name to be changable, but that option isn't currently implemented
        self.name.set(name)
        self.cards = []
        self.card_count = IntVar(0)  # IntVar lets the label update whenever the card count changes

    def give_cards(self, card_array):
        self.cards = self.cards + card_array
        self.card_count.set(len(self.cards))

    def clear_cards(self):
        self.cards = []
        self.card_count.set(0)

    def take_card(self):
        self.card_count.set(self.card_count.get() - 1)
        if self.card_count.get() > -1:
            return self.cards.pop(0)
        else:   # this only happens if game ends on two cards matching - this return val will not be read
            return 0

    def draw_on_frame(self, a_frame):
        ttk.Label(a_frame, textvariable=self.name).grid(column= 0, row=0, columnspan=3, sticky = W)
        ttk.Label(a_frame, text="cards:").grid(column= 0, row=1, sticky = E, padx=10)
        ttk.Label(a_frame, textvariable = self.card_count).grid(column=1, row=1, sticky = W)

class Card:
    """
    Holds a value and a suit

    To test win condition logic quickly, set shuffle to False in static method get_deck
    """
    def __init__(self, val, suit):
        self.val = val
        self.suit = suit

    @staticmethod
    def get_deck(shuffle=True):
        deck = []
        suits = ['hearts','diamonds','spades','clubs']
        for i in range(1, 14):
            for s in range(0, 4):
                deck.append(Card(i, suits[s]))
        if(shuffle):
            random.shuffle(deck)
        return deck

    @staticmethod
    def compare(card1, card2):
        """
        Returns 1 if card1 > card2
        Returns -1 if card2 > card1
        Returns 0 if equal

        Accounts for 2s beating aces
        :param card1:
        :type card1: class Card
        :param card2:
        :type card2: class Card
        :return: 1, -1, or 0
        """
        if card1.val == 1 and card2.val != 2:
            return 1
        if card2.val == 1 and card1.val != 2:
            return -1
        if card1.val > card2.val:
            return 1
        if card2.val > card1.val:
            return -1
        return 0

class CardWidget:
    """
    Display the value of the card and a graphic for the suit
    """
    def __init__(self, a_frame):
        self.frame = ttk.Frame(a_frame, relief='ridge')
        self.spade_image = PhotoImage(file='spade.gif')
        self.club_image = PhotoImage(file='club.gif')
        self.heart_image = PhotoImage(file='heart.gif')
        self.diamond_image = PhotoImage(file='diamond.gif')
        self.spade = ttk.Label(self.frame, image=self.spade_image)
        self.club = ttk.Label(self.frame, image=self.club_image)
        self.heart = ttk.Label(self.frame, image=self.heart_image)
        self.diamond = ttk.Label(self.frame, image=self.diamond_image)
        self.value = StringVar()
        self.value.set('0')
        self.value_label = ttk.Label(self.frame, textvariable=self.value, padding=7)
        self.suit = self.spade
        self.first_run = True  # so we can safely call grid.forget and remove old card images after first one

    def load_card(self, card):
        val = card.val
        if val == 13:
            self.value.set('K')
        elif val == 12:
            self.value.set('Q')
        elif val == 11:
            self.value.set('J')
        elif val == 1:
            self.value.set('A')
        else:
            self.value.set(str(val))
        suit = card.suit
        self.suit.grid_forget()  # lose the old label
        if suit == 'hearts':
            self.suit = self.heart
        elif suit == 'diamonds':
            self.suit = self.diamond
        elif suit == 'spades':
            self.suit = self.spade
        else:
            self.suit = self.club
        self.redraw()  #  redraw the label for the new suit

    def draw_on_frame(self, target_row):
        self.frame.grid(row=target_row, columnspan=3)

    def redraw(self):
        if self.first_run:
            self.value_label.grid(column=0, row=0, sticky=E)
            self.first_run = False
        self.suit.grid(column=1, row=0, sticky=(N,S,W) )

class PlayAreaWidget:
    def __init__(self, a_frame, player, opponent):
        """
        The play area
        :param a_frame: class Tkinter Frame object
        :param player: class PlayerWidget
        :param opponent: class PlayerWidget
        """
        self.frame = a_frame  # needs reference for displaying card graphics
        self.new_game_button = ttk.Button(a_frame, text="New Game", command=self.new_game)
        self.player = player
        self.opponent = opponent
        self.draw_button = ttk.Button(a_frame, text="Draw", command=self.draw_card)
        self.opponent_card = CardWidget(a_frame)
        self.player_card = CardWidget(a_frame)
        self.last_result = StringVar()
        self.last_result.set('+0')  # how many cards were added and to what stack, player, the pile, or the opponent
        self.last_result_label = ttk.Label(a_frame, textvariable=self.last_result)
        self.stack = []
        self.stack_count = IntVar()
        self.stack_count.set(0)
        self.stack_label = ttk.Label(a_frame, textvariable=self.stack_count)  # how many cards are on the pile
        self.playing = False

    def new_game(self):
        """
        Resets player and opponent decks
        :return:
        """
        deck = Card.get_deck()
        half1 = deck[0:int(len(deck) / 2)]
        half2 = deck[int(len(deck) / 2):]
        self.player.clear_cards()
        self.opponent.clear_cards()
        self.stack = []
        self.player.give_cards(half1)
        self.opponent.give_cards(half2)
        self.playing = True
        self.draw()

    def draw(self):
        """
        Called after initialization to ensure proper positioning

        Not to be confused with draw_card; this method creates the UI widgets
        """
        if self.playing:
            self.new_game_button.grid_forget()
            self.draw_button.grid(row=1,columnspan=3)
            self.opponent_card.draw_on_frame(0)
            self.player_card.draw_on_frame(2)
            self.last_result_label.grid(row=1, column=4)
            self.stack_label.grid(row=1, column=5)
        else:
            self.draw_button.grid_forget()
            self.new_game_button.grid(row=1, columnspan=3)

    def draw_card(self):
        player_card = self.player.take_card()
        opponent_card = self.opponent.take_card()
        self.player_card.load_card(player_card)  # loads it into the card widget for display
        self.opponent_card.load_card(opponent_card)
        self.stack += [player_card, opponent_card]  # adds both cards to the stack
        result = Card.compare(player_card, opponent_card)
        if result > 0:
            self.player.give_cards(self.stack)
            self.last_result.set('+' + str(len(self.stack)-1)) # -1 because it doesn't include the card the opp just played
            self.last_result_label.grid(row=2)
            self.stack = []
        elif result < 0:
            self.opponent.give_cards(self.stack)
            self.last_result.set('+' + str(len(self.stack)-1))
            self.last_result_label.grid(row=0)
            self.stack = []
        else:
            card_1 = self.player.take_card()   # each player puts 2 cards on the stack when card values are equal
            card_2 = self.opponent.take_card()
            card_3 = self.player.take_card()
            card_4 = self.opponent.take_card()
            self.stack += [card_1,card_2,card_3,card_4]
            self.last_result.set('+6')
            self.last_result_label.grid(row=1)
        self.stack_count.set(len(self.stack)) # set the stack count to the number of cards there
        if self.player.card_count.get() <= 0:
            self.win(self.opponent)
        elif self.opponent.card_count.get() <= 0:
            self.win(self.player)

    def win(self, player):
        self.playing = False
        if player == self.player:
            message_text = 'Congratulations!'
            title_text = 'Victory'
        else:
            message_text = 'Sorry!'
            title_text = 'Defeat'
        messagebox.showinfo(message=message_text, title=title_text)
        self.draw()


# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 23:58:01 2020

@author: Apoorva
"""

#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the dayOfProgrammer function below.
def dayOfProgrammer(year):
    m=[31,28,31,30,31,30,31,31,30,31,30,31]
    d=256
    s=0
    if year>=1700 and year<=1917:
        z=0
        if year%4==0:
            z=1
        for i in range(8):
            s+=m[i]
        d=256-s-z
    if year==1918:
        return '26.09.1918'
    if year>=1919 and year<=2700:
        z=0
        if year%400==0 or (year%4==0 and year%100!=0):
            z=1
        for i in range(8):
            s+=m[i]
        d=256-s-z
    dd=str(d)
    yy=str(year)

    ddmmyy=dd+'.'+'09'+'.'+yy
    return ddmmyy

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    year = int(input().strip())

    result = dayOfProgrammer(year)

    fptr.write(result + '\n')

    fptr.close()


# 03 Handling Different Exceptions

try: # try block
    age = int(input("Age: "))
    xfactor = 10 / age # If age is 0 (a numeric value) this line will produce an error "ZeroDivisionError". We cann not divide a number by zero.
except (ValueError, ZeroDivisionError): # Better than add the another execption block below add the several exception between paranthesis.
    print("You did no enter a valid age.")
#except ZeroDivisionError: # We can add another exception, or add the "ZeroDivisionError" to the exception block above
#    print("Age can not be zero")
else: # An optional else block can be added. The code we add here will be executed if no execptions occur
    print('No exceptions where thrown')

print("Executions continues") # Because we are handeling this exeption properly the line will be executed, and the program will note crash

06 Exceptions/03 Handling Different Exceptions.py


import pygame, sys

from factory import Factory
from ui import Background, Button
from window import Window
from concepts import Creatable

class Game(Creatable):

    def __init__(self, *args, **kwargs):

        self.clock_ = None
        self._build(**kwargs)

    def _build_dict(self, list_):
        for l in list_:
            alias, value = l.popitem()
            if isinstance(value, dict):
                type_ = value.pop("type", None)
                if type_ is not None:
                    yield {f'{alias}': Factory.make(type_, value)}
                else:
                    yield {f'{alias}': value}
            else:
                yield {f'{alias}': value}

    def _build(self, *args, **kwargs):
        for item in kwargs.items():
            alias, value = item
            if isinstance(value, dict):
                type_ = value.pop("type", None)
                if type_ is not None:
                    self.__setattr__(alias, Factory.make(type_, value))
                else:
                    self.__setattr__(alias, value)
            elif isinstance(value, list):
                aliasdict = dict()
                for n in self._build_dict(value):
                    aliasdict.update(n)
                self.__setattr__(alias, aliasdict)
            else:
                self.__setattr__(alias, value)

    def __setattr__(self, alias, value):
        self.__dict__[alias]=value

    def setup(self):
        print(f"Setting up window...")
        self.window.setup()
        print(f"Window ok!")

        for key in self.ui.keys():
            print(f"Setting up {key}.")
            self.ui[key].setup()
            print(f"{key} ok!")

        self.clock_ = pygame.time.Clock()
        # for key in self.assets.keys():
        #     self.ui[key].setup()

    def clock(self):
        self.clock_.tick(self.tick)

    def event(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

            # if event.type == pygame.KEYDOWN:
            #     if event.key == pygame.K_RIGHT:
            #         x += 5
            #     if event.key == pygame.K_LEFT:
            #         x -= 5
            #     if event.key == pygame.K_DOWN:
            #         y += 5
            #     if event.key == pygame.K_UP:
            #         y -= 5

    def update(self):
        self.window.update()

    def render(self):
        for key in self.ui.keys():
            #print(f"Rendering {key}...")
            self.window.render(self.ui[key])


from collections import defaultdict

class ColMapBuilder(object):
    def __init__(self):
        self.value_map = defaultdict(set)

    def build(self):
        columns = sorted(self.value_map.keys(),
                         key=lambda c: (-len(self.value_map[c]), c))
        col_list = filter(lambda c : len(self.value_map[c]) > 1, columns)
        return ColMap(col_list, self.value_map)

    def try_add(self, column, value):
        self.value_map[column].add( value )

    def try_remove(self, column):
        if column in self.value_map:
            del(self.value_map[column])

class ColMap(object):
    def __init__(self, col_list, values = None):
        self.col_list = sorted(col_list)
        self.rev_map = {}
        self.values = values

        self.minimums = []
        for c in col_list:
            end = 1
            while c[:end] in self.minimums:
                end += 1
            self.minimums += [c[:end]]

        for i, col in enumerate(col_list):
            self.rev_map[col] = i

    def columns(self):
        return self.col_list

    def get_values(self):
        return self.values

    def get_key(self, kv):
        '''Convert a key-value dict into an ordered tuple of values.'''
        key = ()

        for col in self.col_list:
            if col not in kv:
                key += (str(None),)
            else:
                key += (str(kv[col]),)

        return key

    def get_kv(self, key):
        '''Convert an ordered tuple of values into a key-value dict.'''
        kv = {}
        for i in range(0, len(key)):
            kv[self.col_list[i]] = key[i]
        return kv

    def encode(self, kv, minimum=False):
        '''Converted a dict into a string with items sorted according to
        the ColMap key order.'''
        def escape(val):
            return str(val).replace("_", "-").replace("=", "-")

        vals = []

        if minimum:
            format = "%s:%s"
            join = ", "
        else:
            format = "%s=%s"
            join = "_"

        reverse = list(self.col_list)
        reverse.reverse()
        for key in reverse:
            if key not in kv:
                continue
            display = key if not minimum else self.minimums[self.rev_map[key]]
            k, v = escape(display), escape(kv[key])
            vals += [format % (k, v)]

        return join.join(vals)

    @staticmethod
    def decode(string):
        '''Convert a string into a key-value dict.'''
        vals = {}
        for assignment in string.split("_"):
            k, v = assignment.split("=")
            vals[k] = v
        return vals

    def __contains__(self, col):
        return col in self.rev_map

    def __str__(self):
        return "<ColMap>%s" % (self.rev_map)


import base64, cropresize, os
from boto.s3.connection import S3Connection
from boto.s3.key import Key
from PIL import Image
from flask import current_app
from werkzeug import LocalProxy, FileStorage

user_profile_image_store = LocalProxy(lambda: current_app.user_profile_image_store)

def init(app):
    """Initialize application file stores.
    """
    file_stores = {
        "local": LocalUserProfileImageStore,
        "s3": S3UserProfileImageStore
    }

    storage_type = app.config['CDW']['image_storage']['type']
    app.user_profile_image_store = file_stores[storage_type]()

class BaseUserProfileImageStore():
    """Base user profile file store
    """

    def set_photo(self, user, fullsize, thumbnail):
        user.webProfilePicture = fullsize
        user.webProfilePictureThumbnail = thumbnail
        current_app.cdw.users.save(user)

    def _save_images_to_local_disk(self, user, image, storage_dir):
        user_id = str(user.id)

        original_filename = "%s-%s.jpg" % (user_id, 'web')
        original_file_path = '%s/%s' % (storage_dir, original_filename)

        thumbnail_filename = '%s-%s.jpg' % (user_id, 'thumbnail')
        thumbnail_file_path = '%s/%s' % (storage_dir, thumbnail_filename)

        squareimg_filename = '%s-%s.jpg' % (user_id, 'square')
        squareimg_file_path = '%s/%s' % (storage_dir, squareimg_filename)

        msg = "Saving user profile image to: %s" % original_file_path
        current_app.logger.info(msg)

        f = open(original_file_path, 'wb')
        # We may receive a FileStorage type:
        if isinstance(image, FileStorage):
            if hasattr(image.stream, 'getvalue'):
                image = image.stream.getvalue()
            else:
                image = image.stream.read()
            f.write(image)
        else:
            f.write(base64.b64decode(image))
        f.close()

        im = Image.open(original_file_path);
        thumbnail_image = cropresize.crop_resize(im, (71, 96));
        square_image = cropresize.crop_resize(im, (71, 71));

        msg = "Saving user profile image thumbnail to: %s" % thumbnail_file_path
        current_app.logger.info(msg)

        thumbnail_image.save(thumbnail_file_path, 'JPEG', quality=100)
        square_image.save(squareimg_file_path, 'JPEG', quality=100)

        return {
            "original_filename": original_filename,
            "original_file_path": original_file_path,
            "thumbnail_filename": thumbnail_filename,
            "thumbnail_file_path": thumbnail_file_path,
            "squareimg_filename": squareimg_filename,
            "squareimg_file_path": squareimg_file_path,
        }

class LocalUserProfileImageStore(BaseUserProfileImageStore):
    """Local profile image file store
    """
    def saveProfileImage(self, user, image):
        folder = current_app.config['CDW']['image_storage']['user_images_dir']
        result = self._save_images_to_local_disk(user, image, folder)

        self.set_photo(user,
                       result['original_filename'],
                       result['thumbnail_filename'])

    def getProfileImages(self, user):
        return {
            "large": "large",
            "thumb": "thumb"
        }

class S3UserProfileImageStore(BaseUserProfileImageStore):
    """S3 profile image file store
    """
    def _save_to_s3(self, bucket, file_name, file_path):
        folder = current_app.config['CDW']['image_storage']['user_images_dir']
        k = Key(bucket)
        k.key = '%s/%s' % (folder, file_name)

        current_app.logger.info("Saving image to S3: %s >> %s%s" %
                                (file_path, bucket, k.key))

        k.set_contents_from_filename(file_path, policy='public-read')

    def saveProfileImage(self, user, image):
        temp_dir = current_app.config['CDW']['image_storage']['temp_dir']
        result = self._save_images_to_local_disk(user, image, temp_dir)

        key_id = current_app.config['CDW']['aws']['access_key_id']
        secret_key = current_app.config['CDW']['aws']['secret_access_key']
        bucket_name = current_app.config['CDW']['aws']['s3bucket']

        conn = S3Connection(key_id, secret_key)
        bucket = conn.get_bucket(bucket_name)

        # Send to S3 after storage

        self._save_to_s3(bucket,
                         result['original_filename'],
                         result['original_file_path']);

        self._save_to_s3(bucket,
                         result['thumbnail_filename'],
                         result['thumbnail_file_path']);

        # Update the user profile
        self.set_photo(user,
                       result['original_filename'],
                       result['thumbnail_filename'])

        # Delete from local
        os.unlink(result['original_file_path'])
        os.unlink(result['thumbnail_file_path'])


import requests
import pymysql
import json
from bs4 import BeautifulSoup
import re

def get_itemcode():
    liste = []
    url = "http://battlegrounds.inven.co.kr/dataninfo/item/"
    html = requests.get(url)
    soup = BeautifulSoup(html.text, 'html.parser')
    result1=soup.find_all('td', class_='title text_left')

    for i in result1:
        if int(i.find('a').attrs["href"].split("=")[1])>2000:
            pass
        else:
            liste.append(int(i.find('a').attrs["href"].split("=")[1]))

    return list(set(liste))

def crawler(itemcode):
    a=[]
    b=[]
    url = "http://battlegrounds.inven.co.kr/dataninfo/item/detail.php?itemcode=" + str(itemcode)
    html = requests.get(url)
    soup= BeautifulSoup(html.text,'html.parser')
    result1=soup.find('table', class_='detail_info').find_all('td')
    result2=soup.find_all('span', class_='bar')
    for i in result1:
        a.append(i.get_text())
    for i in result2:
        b.append(i["style"])

    name = a[0]
    ammunition = (a[3])
    type = a[1].split('(')[0]
    if type == 'Melee' or type == 'MISC' or type == 'Throwables':
        return 0
    else:
        recoil = int(b[2].split(':')[1].replace('%',''))
        if a[4]=='-':
            muzzleVelocity = -1
        else:
            muzzleVelocity = int(a[4].split()[0])
        magCapacity = int(re.findall("\d+", a[9])[0])
        deal = int(a[2])
        if a[7].count("초")==1:
            rateOfFire = a[7].replace('초','')
        elif a[7] == '-':
            rateOfFire = -1
        else:
            rateOfFire = a[7].replace('초', '').split()[1].split(')')[1]
    if type=='AR' or type == 'SMG':
        difficulty = float((recoil*5)/(muzzleVelocity*magCapacity*3*deal*2))
    elif type=='LMG':
        difficulty = float((recoil*4)/(muzzleVelocity*deal*3))
    elif type == 'DMR':
        difficulty = float((recoil*3)/(muzzleVelocity*3*magCapacity*deal*5))
    elif type == 'SG':
        difficulty = float((recoil*float(rateOfFire))/(magCapacity*deal*4))
    else:
        difficulty = float(100/(muzzleVelocity*5*magCapacity*deal*6))

    tuple = (name,ammunition,type,recoil,muzzleVelocity,magCapacity,deal,rateOfFire,float(difficulty*100000))

    return tuple

final = []
for i in get_itemcode():
    if i == 1106 or i>=1900 or (i>=1700 and i<1800) or (i>=1400 and i<1500):
        pass
    else:
        final.append(crawler(i))

for i in final:

    user_db = pymysql.connect(user='root',password='*****',host='127.0.0.1',db='user',charset='utf8')

    sql="INSERT INTO user.PUBG(gun_name,gun_ammunition,gun_type,gun_recoil,gun_muzzleVelocity,gun_magCapacity,gun_deal,gun_rateOfFire,gun_difficulty)VALUES('%s','%s','%s',%s,%s,%s,%s,%s,%s);" % i

    cursor = user_db.cursor()
    cursor.execute(sql)
    user_db.commit()

# difficulty = (recoil*rate of fire)/(ammo*muzzleVelocity*magCapacity*deal)


from nautilus_trader.model.data.ticker import Ticker
from nautilus_trader.test_kit.providers import TestInstrumentProvider

ETHUSDT_BINANCE = TestInstrumentProvider.ethusdt_binance()

class TestTicker:
    def test_fully_qualified_name(self):
        # Arrange, Act, Assert
        assert Ticker.fully_qualified_name() == "nautilus_trader.model.data.ticker:Ticker"

    def test_ticker_hash_str_and_repr(self):
        # Arrange
        ticker = Ticker(
            ETHUSDT_BINANCE.id,
            0,
            0,
        )

        # Act, Assert
        assert isinstance(hash(ticker), int)
        assert str(ticker) == "Ticker(instrument_id=ETHUSDT.BINANCE, ts_event=0)"
        assert repr(ticker) == "Ticker(instrument_id=ETHUSDT.BINANCE, ts_event=0)"

    def test_to_dict_returns_expected_dict(self):
        # Arrange
        ticker = Ticker(
            ETHUSDT_BINANCE.id,
            0,
            0,
        )

        # Act
        result = Ticker.to_dict(ticker)

        # Assert
        assert result == {
            "type": "Ticker",
            "instrument_id": "ETHUSDT.BINANCE",
            "ts_event": 0,
            "ts_init": 0,
        }

    def test_from_dict_returns_expected_tick(self):
        # Arrange
        ticker = Ticker(
            ETHUSDT_BINANCE.id,
            0,
            0,
        )

        # Act
        result = Ticker.from_dict(Ticker.to_dict(ticker))

        # Assert
        assert result == ticker


#1、在一个排序的链表中，存在重复的结点，请删除该链表中重复的结点，重复的结点不保留，返回链表头指针。 例如，链表1->2->3->3->4->4->5 处理后为 1->2->3->4->5
#2、在一个排序的链表中，存在重复的结点，请删除该链表中重复的结点，重复的结点不保留，返回链表头指针。 例如，链表1->2->3->3->4->4->5 处理后为 1->2->5
# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:
            return head
        cur = head
        while cur.next != None:
            if cur.val == cur.next.val:
                cur.next = cur.next.next
            else:
                cur = cur.next
        return head

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    def deleteDuplication(self, pHead):
        # write code here
        if pHead == None or pHead.next == None:
            return pHead
        pre = ListNode(0)
        pre.next = pHead
        last = pre
        cur = pHead
        while cur and cur.next != None:
            if cur.val != cur.next.val:
                cur = cur.next
                last = last.next
            else:
                value = cur.val
                while cur and cur.val == value:
                    cur = cur.next
                last.next = cur
        return pre.next


from types import NoneType
from talon import Module, Context, app, registry, skia, ui, actions, settings
from talon.canvas import Canvas
from talon.screen import Screen
from talon.skia.canvas import Canvas as SkiaCanvas
from talon.skia.imagefilter import ImageFilter
from talon.types import Rect
import json
from typing import assert_never

mod = Module()
ctx = Context()

hotspot_enabled = mod.setting(
    "hotspot_enabled",
    bool,
    desc="If true the hotspots are shown",
    default=True,
)

class Hotspot:
    x: float
    y: float
    radius: float
    color: str
    alpha: float
    gradient: float
    _uniqueID: int=1

    def __init__(self, rawConfigStr: str):
        self._uniqueID = Hotspot._uniqueID
        Hotspot._uniqueID += 1

        assert rawConfigStr is not None

        conf = {}
        split = rawConfigStr.split(" ")
        # convert groups of 2 to key value pairs
        for i in range(0, len(split), 2):
            conf[split[i]] = split[i + 1]

        self.x = float(conf["x"])
        self.y = float(conf["y"])
        self.diameter = float(conf["diameter"])
        self.color = str(conf["color"])
        self.alpha = float(conf["alpha"])
        self.gradient = float(conf["gradient"])

        self.canvas: Canvas = None

    def get_alpha_color(self) -> str:
        return f"{int(self.alpha * 255):02x}"

    def get_gradient_color(self, color: str) -> str:
        factor = self.gradient
        # hex -> rgb
        (r, g, b) = tuple(int(color[i : i + 2], 16) for i in (0, 2, 4))
        # Darken rgb
        r, g, b = int(r * factor), int(g * factor), int(b * factor)
        # rgb -> hex
        return f"{r:02x}{g:02x}{b:02x}"

    def get_colors(self):
        color_mode = self.color
        color_gradient = self.get_gradient_color(color_mode)
        color_alpha = self.get_alpha_color()
        return f"{color_mode}{color_alpha}", f"{color_gradient}"

    def show_indicator(self):
        self.canvas = Canvas.from_rect(Rect(0, 0, 0, 0))
        self.canvas.register("draw", on_draw_wrapper(self.canvas, self))

    def hide_indicator(self):
        self.canvas.unregister("draw", on_draw_wrapper(self.canvas, self))
        self.canvas.close()
        self.canvas = None

    # by default the coordinates are a percentage of the screen.
    # this function converts them to pixel coordinates
    def _getPlottingCoords(self):
        screen: Screen = ui.main_screen()
        rect = screen.rect
        radius = self.diameter * screen.scale / 2

        x = rect.left + min(
            max(self.x * rect.width - radius, 0),
            rect.width - 2 * radius,
        )

        y = rect.top + min(
            max(self.y * rect.height - radius, 0),
            rect.height - 2 * radius,
        )
        return (x, y, radius)

    def move_indicator(self):
        x, y, radius = self._getPlottingCoords()

        side = 2 * radius
        self.canvas.move(x, y)
        self.canvas.resize(side, side)

    def cursorInside(self) -> bool:
        cursor_y = actions.mouse_y()
        cursor_x = actions.mouse_x()

        x_coord_from_percentage, y_coord_from_percentage, radius = self._getPlottingCoords()

        # check if the cursor is in any of the hotspots. each hotspot has a x and y coordinate as well as a radius. they are all circles
        INSIDE_X = x_coord_from_percentage - radius <= cursor_x <= x_coord_from_percentage + radius
        INSIDE_Y = y_coord_from_percentage - radius  <= cursor_y <= y_coord_from_percentage + radius

        if INSIDE_X and INSIDE_Y:
            print('cursor is inside')
            return True
        return False
    def get_unique_id(self) -> int:
        return self._uniqueID

    def run_associated_action(self):
        functionName = f"actions.user.hotspot_{self.get_unique_id()}_focus"
        # run a python function from a string. eval is ok here because the string is not user input
        eval(functionName)()

def getHotSpots() -> list[Hotspot]:
    return hotspot_list

def makeHotspotList() -> list[Hotspot]:
    return [Hotspot("x 1 y 0 diameter 20 color 808280 alpha 0.9 gradient 0.9"),
            Hotspot("x 0 y 01 diameter 50 color 899841 alpha 0.9 gradient 0.9"),
            Hotspot("x 0.5 y 0.5 diameter 50 color 893880 alpha 0.4 gradient 0.9")

            ]

hotspot_list = makeHotspotList()

def on_draw_wrapper(c: SkiaCanvas, current_hotspot: Hotspot):

    def on_draw(c: SkiaCanvas):

        color_mode, color_gradient = current_hotspot.get_colors()
        x, y = c.rect.center.x, c.rect.center.y
        radius = c.rect.height / 2 - 2
        c.paint.shader = skia.Shader.radial_gradient(
            (x, y), radius, [color_mode, color_gradient]
        )
        c.paint.imagefilter = ImageFilter.drop_shadow(1, 1, 1, 1, color_gradient)
        c.paint.style = c.paint.Style.FILL
        c.paint.color = color_mode
        c.draw_circle(x, y, radius)

    return on_draw

def getHotspotIfFocused():
    hotSpots = getHotSpots()

    for hotSpot in hotSpots:
        if hotSpot.cursorInside():
            return hotSpot
    return None

def update_hotspots():
    global hotspot_list

    for hotspot in hotspot_list:
        canvas = hotspot.canvas

        if hotspot_enabled.get():
            if not canvas or canvas is None:
                hotspot.show_indicator()
                assert hotspot.canvas is not None and type(hotspot.canvas) is not NoneType

            hotspot.move_indicator()
            hotspot.canvas.freeze()
        elif canvas:
            hotspot.hide_indicator()

def on_update_settings(updated_settings: set[str]):
    if {hotspot_enabled.path} & updated_settings:
        update_hotspots()

def on_ready():
    update_hotspots()
    registry.register("update_settings", on_update_settings)
    ui.register("screen_change", lambda _: update_hotspots)

app.register("ready", on_ready)


# -*- coding: utf-8 -*-
"""
Created on Fri Nov 26 11:27:02 2021

@author: hossa
"""

from flask import Flask
from flask import request, jsonify
from datetime import date
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app)
cors = CORS(app , resources={r"/*": {"origins": "*", "allow_headers": "*", "expose_headers": "*"}})

@app.route('/loginpat', methods=['POST'])
def patient_login():
  userName=(request.json["username"])
  password=(request.json["password"])
  if (userName==None):
      #return "FAILED"
      return jsonify(
        found=False
        )
  else:
      return jsonify(
          name="majd",
          city="Beirut")

@app.route('/addDose', methods=['POST'])
def dosee():
  pid=(request.json["pid"]) #patient id
  pname=(request.json["name"]) #patient name
  doseNumber=(request.json["doseNumber"])
  return jsonify(
               added=True,
               dayToBook=date.today(),
               Hour=8,
               Minute=120
               )

@app.route('/dummyfunction', methods=['GET'])
def he_world():
 return jsonify(
          found=True,
          ac="aa",
          )

@app.route('/loginmed', methods=['POST'])
def med_login():
   username=(request.json["username"])
   password=(request.json["password"])
   return jsonify(
          found=True,
          patients=[[
            "abdallah maarouf",
            1,
            3145654,
            "abd@gmail.com",
            "Saida",
            "Lebaon",
            "lactose intolerant",
            "am22",
            "abdmaa00",
            2000
        ],
        [
            "aa",
            2,
            70545124,
            "aa@gmail.com",
            "Saida",
            "Lebanon",
            "nut allergy",
            "aaa",
            "aaaa",
            2000
        ]
    ],
          incomplete_doses= [
        [
            1,
            1,
            1,
            "2021-11-25",
            0,
            "Pending"
        ],
        [
            2,
            55,
            1,
            "2021-11-25",
            30,
            "Pending"
        ]]
          )

@app.route('/', methods=['GET'])
def hello_world():
 return "sent from flask"

if __name__ == '__main__':
  print(__name__)
  app.debug=True
#app.run(host = '192.168.0.107')
#app.run(host = '0.0.0.0', port = 5000, debug = True, threaded = True)
app.run(host='0.0.0.0',port = 5000)


from sortedcontainers import SortedList
class Solution:
    def containsNearbyAlmostDuplicate(self, nums: List[int], indexDiff: int, valueDiff: int) -> bool:
        slist = SortedList()
        n = len(nums)
        l, r = 0, 0 # [l, r)
        while r < n:
            num = nums[r]
            r += 1

            while r-l-1 > indexDiff:
                slist.remove(nums[l])
                l += 1

            if r>l+1:
                i = slist.bisect_left(num)
                # sorted list = [XXXX i XXXX], binary search: list[i] >= num
                # check list[i]-num <= diff
                # also check num-list[i-1] <= diff
                if i != len(slist) and abs(slist[i]-num) <= valueDiff: return True
                if i > 0 and abs(num-slist[i-1]) <= valueDiff: return True
            slist.add(num)
        return False

# Bucket sort
class Solution:
    def containsNearbyAlmostDuplicate(self, nums, indexDiff, valueDiff):
        # Bucket sort. Each bucket has size of t. For each number, the possible
        # candidate can only be in the same bucket or the two buckets besides.
        # Keep as many as k buckets to ensure that the difference is at most k.
        buckets = {}
        for i, v in enumerate(nums):
            # t == 0 is a special case where we only have to check the bucket
            # that v is in.
            bucketNum, offset = (v // valueDiff, 1) if valueDiff else (v, 0)
            for idx in range(bucketNum - offset, bucketNum + offset + 1):
                if idx in buckets and abs(buckets[idx] - nums[i]) <= valueDiff:
                    return True

            buckets[bucketNum] = nums[i]
            if len(buckets) > indexDiff:
                # Remove the bucket which is too far away. Beware of zero t.
                del buckets[nums[i - indexDiff] // valueDiff if valueDiff else nums[i - indexDiff]]

        return False

Sliding Window/220. Contains Duplicate III/solution.py


from ticktactoematrix import TickTacToeMatrix

def create_tick_tack_toe_board(w, h):
    return TickTacToeMatrix(w, h)

def print_instructions():
    print("X player goes first. type in x,y as the input of where you want to put the X or O. ")
    print("Example, if I want to put my symbol at the middle, I would type 1,1 ")

def main():
    print_instructions()
    board = create_tick_tack_toe_board(3, 3)
    user_input = None
    while not board.is_complete():
        while user_input is None or board.has_played_symbol(width, height):
            board.start_turn()
            user_input = input()
            array_input = user_input.split(',')
            width = int(array_input[0])
            height = int(array_input[1])
        board.set_symbol_at(width, height)
    board.complete_game()

if __name__ == "__main__":
    main()


import random

class wordjumblegame:

    nplayers = 0

    def __init__(self, name):
        self.name = name
        self.points = 0
        self.words = self.initwords()
        wordjumblegame.nplayers += 1

    def showbanner(self):
        print("-"*60)
        print("\t\tWELCOME", self.name.upper(), "TO THE WORD JUMBLE GAME")
        print("The computer shows a jumbled word, You need to guess it")
        print("One attempt per word")
        print("-"*60)

    def initwords(self):
        words = ["apples", "monkey", "laptop", "mobile", "python", "random"]
        random.shuffle(words)
        return words

    def jumble(self, word):
        temp = list(word)
        random.shuffle(temp)
        return ''.join(temp)

    def run(self):

        self.showbanner()
        for word in self.words:

            # Select the word
            # Jumble the word
            jword = self.jumble(word)

            # Show the jumbled word
            print("Word --> ", jword)

            # Input the word from the user
            uword = input("Enter you guess: ")

            # Comparison between selected word and user input
            # Updates the point
            if(uword == word):
                self.points += 1
                print("Correct guess!")
            else:
                print("Incorrect....")

    def showresults(self):
        print("\n")
        print(self.name.upper())
        print("-"*60)
        print("SCORE : ", self.points)
        if(self.points >= 5):
            print("Excellent Playing!")
        elif(2 <= self.points < 5):
            print("Good")
        else:
            print("Good luck next time....")
        print("-"*60)


"""Swapping variables

Define a function named swap_values that takes four integers as parameters
and swaps the first with the second, and the third with the fourth values.
Then write a main program that reads four integers from input,
calls function swap_values() to swap the values,
and prints the swapped values on a single line separated with spaces.
"""

# The program must define and call the following function.
# def swap_values(user_val1, user_val2, user_val3, user_val4)

def swap_values(x1, x2, x3, x4):
    """Swaps two integers."""
    temp1, temp2 = x1, x3
    x1, x3 = x2, x4
    x2, x4 = temp1, temp2
    print(f"{x1} {x2} {x3} {x4}")
    return x1, x2, x3, x4

def main():
    """main _summary_"""
    val1 = int(input())
    val2 = int(input())
    val3 = int(input())
    val4 = int(input())
    swap_values(val1, val2, val3, val4)

if __name__ == '__main__':
    main()


from django.contrib import admin
from blog.models import Category, Location, Post

class PostAdmin(admin.ModelAdmin):
    list_display = ('is_published',
                    'created_at',
                    'title',
                    'text',
                    'pub_date',
                    'author',
                    'location',
                    'category',
                    )
    list_editable = ('is_published',
                     )
    search_fields = ('title',
                     'author',
                     'category',
                     )
    list_filter = ('category',
                   'is_published',
                   'created_at',
                   'pub_date',
                   'location',
                   'author',
                   )
    list_display_links = ('title',)

class CategoryAdmin(admin.ModelAdmin):
    list_display = (
        'is_published',
        'created_at',
        'title',
        'description',
        'slug',
    )

class LocationAdmin(admin.ModelAdmin):
    list_display = (
        'is_published',
        'created_at',
        'name',
    )

admin.site.empty_value_display = 'Не задано'
admin.site.register(Post, PostAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Location, LocationAdmin)


#-*- coding:utf-8 -*-
"""make_change_ls.py
"""
from __future__ import print_function
import sys, re,codecs
from parseheadline import parseheadline

class Entry(object):
 Ldict = {}
 def __init__(self,lines,linenum1,linenum2):
  # linenum1,2 are int
  self.metaline = lines[0]
  self.lend = lines[-1]  # the <LEND> line
  self.datalines = lines[1:-1]  # the non-meta lines
  # parse the meta line into a dictionary
  #self.meta = Hwmeta(self.metaline)
  self.metad = parseheadline(self.metaline)
  self.linenum1 = linenum1
  self.linenum2 = linenum2
  #L = self.meta.L
  L = self.metad['L']
  if L in self.Ldict:
   print("Entry init error: duplicate L",L,linenum1)
   exit(1)
  self.Ldict[L] = self
  self.lsarr = []

def init_entries(filein):
 # slurp lines
 with codecs.open(filein,encoding='utf-8',mode='r') as f:
  lines = [line.rstrip('\r\n') for line in f]
 recs=[]  # list of Entry objects
 inentry = False
 idx1 = None
 idx2 = None
 for idx,line in enumerate(lines):
  if inentry:
   if line.startswith('<LEND>'):
    idx2 = idx
    entrylines = lines[idx1:idx2+1]
    linenum1 = idx1 + 1
    linenum2 = idx2 + 1
    entry = Entry(entrylines,linenum1,linenum2)
    recs.append(entry)
    # prepare for next entry
    idx1 = None
    idx2 = None
    inentry = False
   elif line.startswith('<L>'):  # error
    print('init_entries Error 1. Not expecting <L>')
    print("line # ",idx+1)
    print(line.encode('utf-8'))
    exit(1)
   else:
    # keep looking for <LEND>
    continue
  else:
   # inentry = False. Looking for '<L>'
   if line.startswith('<L>'):
    idx1 = idx
    inentry = True
   elif line.startswith('<LEND>'): # error
    print('init_entries Error 2. Not expecting <LEND>')
    print("line # ",idx+1)
    print(line.encode('utf-8'))
    exit(1)
   else:
    # keep looking for <L>
    continue
 # when all lines are read, we should have inentry = False
 if inentry:
  print('init_entries Error 3. Last entry not closed')
  print('Open entry starts at line',idx1+1)
  exit(1)

 print(len(lines),"lines read from",filein)
 print(len(recs),"entries found")
 return recs

class Change(object):
 def __init__(self,metaline,lnum,old,new):
  self.metaline = metaline
  self.lnum = lnum
  self.old = old
  self.new = new

def init_strings(filein):
 with codecs.open(filein,encoding='utf-8',mode='r') as f:
  stringlist = [line.rstrip('\r\n') for line in f]
  stringset = set(stringlist) # handles duplicates, if any
 print(len(stringset),"strings read from",filein)
 return stringset

def change_ls_matching_given(line,stringset):
 def f(m):
  ans = m.group(0)
  ls = m.group(1)
  if ans in stringset:
   ans = '<ls>[%s]</ls>'%ls
  return ans
 newline = re.sub(r'<ls>(.*?)</ls>',f,line)
 return newline

def write_changes(fileout,changes):
 outrecs = []
 for change in changes:
  outarr = []
  outarr.append('; -------------------------------------')
  outarr.append('; ' + change.metaline)
  outarr.append('%s old %s' %(change.lnum,change.old))
  outarr.append('; ')
  outarr.append('%s new %s' %(change.lnum,change.new))
  outrecs.append(outarr)
 with codecs.open(fileout,"w","utf-8") as f:
  for outarr in outrecs:
   for out in outarr:
    f.write(out+'\n')
 print(len(outrecs),"records written to",fileout)

def change_ls_matching_given_1(line):
 def f(m):
  # <ls>(Spr. (II) ...) ((I)...)</ls>
  partII = m.group(1)
  partI = m.group(2)
  ls1 = '<ls>%s</ls>' % partII
  ls2 = '<ls n="Spr.">%s</ls>' % partI
  lsnew = '%s %s' %(ls1,ls2)
  return lsnew
 newline = re.sub(r'<ls>(Spr. \(II\)[^<]*?) (\(I\).*?)</ls>',f,line)
 flag = not (newline == line)
 return flag,newline

def change_ls_matching_given_2(line):
 def f(m):
  # <ls>Spr. (II) 2375. 2886. 3104. 7424.</ls>
  #  2375. 2886. 3104. 7424.

  #print(m.group(0))
  #print(m.group(1))
  #print()
  versedata = m.group(1)
  versedata1 = versedata.lstrip()  # remove leading ' '
  versenums = versedata1.split(' ')
  lsarr = []
  pfx = 'Spr. (II)'
  for iverse,verse in enumerate(versenums):
   if iverse == 0:
    ls = '<ls>%s %s</ls>' % (pfx,verse)
   else:
    ls = '<ls n="%s">%s</ls>' % (pfx,verse)
   lsarr.append(ls)
  lsnew = ' '.join(lsarr)
  return lsnew
 newline = re.sub(r'<ls>Spr. \(II\)(( [0-9]+[.]?){2,})</ls>',f,line)
 flag = not (newline == line)
 return flag,newline

def change_ls_matching_given_2a(line):
 replacements = [
  ('</ls> <ls>v. l.',' v. l.'),
  ('</ls> <ls>fgg.',' fgg.'),
  ('</ls> <ls>fg.',' fg.'),
  ]
 newline = line
 for old,new in replacements:
  newline = newline.replace(old,new)
 flag = not (newline == line)
 return flag,newline

def change_ls_matching_given_3(line):
 def f(m):
  # <ls>Spr. (II) 2375. 7424, v. l.</ls>
  versedata = m.group(1)
  extra = m.group(3) # v. l., or fgg?. Why is this not m.group(2) ?
  #versedata = m.group('verses')
  #extra = m.group('extra')
  versedata1 = versedata.lstrip()  # remove leading ' '
  versenums = versedata1.split(' ')
  lsarr = []
  pfx = 'Spr. (II)'
  iverselast  = len(versenums) - 1
  for iverse,verse in enumerate(versenums):
   if iverse == 0:
    ls = '<ls>%s %s</ls>' % (pfx,verse)
   elif iverse == iverselast:
    ls = '<ls n="%s">%s %s</ls>' % (pfx,verse,extra)
   else:
    ls = '<ls n="%s">%s</ls>' % (pfx,verse)
   lsarr.append(ls)
  lsnew = ' '.join(lsarr)
  return lsnew
 newline = re.sub(r'<ls>Spr. \(II\)(( [0-9]+[.,]?){2,}) ((v\. l\.)|(fg\.)|(fgg\.))</ls>',f,line)
 #newline = re.sub(r'<ls>Spr. \(II\)(?P<verses>( [0-9]+[.]?){2,}) (?P<extra>(v\. l\.)|(fg\.)|(fgg\.))</ls>',f,line)
 flag = not (newline == line)
 return flag,newline

def change_ls_matching_given_4(line):
 def f(m):
  # <ls>Spr. (II) 2375. 7424, v. l.</ls>
  versedata = m.group(1)
  #extra = m.group(3) # v. l., or fgg?. Why is this not m.group(2) ?
  #versedata = m.group('verses')
  #extra = m.group('extra')
  versedata1 = versedata.lstrip()  # remove leading ' '
  versedata2 = versedata1.replace(' v. l.','__1')
  versenums = versedata2.split(' ')
  lsarr = []
  pfx = 'Spr. (II)'
  iverselast  = len(versenums) - 1
  for iverse,verse in enumerate(versenums):
   if iverse == 0:
    ls = '<ls>%s %s</ls>' % (pfx,verse)
   else:
    ls = '<ls n="%s">%s</ls>' % (pfx,verse)
   lsarr.append(ls)
  lsnew = ' '.join(lsarr)
  lsnew = lsnew.replace('__1',' v. l.')
  return lsnew
 newline = re.sub(r'<ls>Spr. \(II\)(( [0-9]+[.,]?( (v\. l\.))?){2,})</ls>',f,line)
 flag = not (newline == line)
 return flag,newline

def change_ls_matching_given_5(line):
 def f(m):
  # <ls>Spr. (II) 2375. 7424, v. l.</ls>
  versedata = m.group(1)
  #extra = m.group(3) # v. l., or fgg?. Why is this not m.group(2) ?
  #versedata = m.group('verses')
  #extra = m.group('extra')
  versedata1 = versedata.lstrip()  # remove leading ' '
  versedata2 = versedata1.replace(' fgg.','__1')
  versedata3 = versedata2.replace(' fg.','__2')
  versenums = versedata3.split(' ')
  lsarr = []
  pfx = 'Spr. (II)'
  iverselast  = len(versenums) - 1
  for iverse,verse in enumerate(versenums):
   if iverse == 0:
    ls = '<ls>%s %s</ls>' % (pfx,verse)
   else:
    ls = '<ls n="%s">%s</ls>' % (pfx,verse)
   lsarr.append(ls)
  lsnew = ' '.join(lsarr)
  lsnew = lsnew.replace('__1',' fgg.')
  lsnew = lsnew.replace('__2',' fg.')
  return lsnew
 newline = re.sub(r'<ls>Spr. \(II\)(( [0-9]+[.,]?( (fgg?\.))?){2,})</ls>',f,line)
 flag = not (newline == line)
 return flag,newline

dataxraw = """
<ls>Spr. (II) 1091)</ls> viDA 91865
<ls>Spr. (II) 268).</ls> viDAtar 91866
<ls>Spr. (II) 1652)</ls> vftta 94757
<ls>Spr. (II) 701.fg.</ls> vftti 94793
<ls>Spr. (II) Vorwort S. XVI.</ls> vfdDacARakya 94861
<ls>Spr. (II)</ls> Satruka 97703
<ls>Spr. (II) 1009. 3482, v. l. 4029. (I) 2794.</ls> Silpa 99590
<ls>Spr. (II) 1073).</ls> Socis 101047
<ls>Spr. (II) 328)</ls> SOca 101170
<ls>Spr. (II) 3963 </ls> Sram 101446
<ls>Spr. (II) 2457,</ls> SrezWa 101916
<ls>Spr. (II) 5705)</ls> zaRqa 102570
<ls>Spr. (II) 6802).</ls> saktimant 103336
<ls>Spr. (II) 1650)</ls> saMkalpa 103442
<ls>Spr. (II) 751)</ls> saMkalpa 103442
<ls>Spr. (II) 5873)</ls> saMkzaya 103522
<ls>Spr. (II) 4111,</ls> satyavAcaka 104150
<ls n="Spr. (II)">4977,</ls> satyavAdin 104153
<ls>Spr. (II) 4600,</ls> sad 104247
<ls>Spr. (II) 6100. 6750. 6752 u.s.w.</ls> sadA 104294
<ls>Spr. (II) 4111,</ls> sadAkArin 104296
<ls>Spr. (II) 1929. 2071. 4287, v. l. 6206, v. l. 6767. fg. 7299.</ls> sadBAva 104380
<ls>Spr. (II) 2327. 2586. 5483. 6869. fgg. 6918, v. l.</ls> saMpatti 106026
<ls>Spr. (II) 881).</ls> saMpAdin 106069
<ls>Spr. (II) 1110. 5582. <is>Śiva</is></ls> sarvaBakza 106901
<ls>Spr. (II) 5264,</ls> sallApa 107288
<ls>Spr. (II) 6973)</ls> sahasra 107620
<ls>Spr. (II) 3669.7565.</ls> sAhasin 108968
<ls>Spr. (II)</ls> suBAzita 110848
<ls>Spr. (II) 2875. - 5606</ls> sumantrin 110951
<ls>Spr. (II) 639. 790. fg. 5860, v. l. 7187. 7581.</ls> staB 113579
<ls>Spr. (II)</ls> sparSa 114358
<ls>Spr. (II) 4781.7259.</ls> smartavya 114602
<ls>Spr. (II) 3274)</ls> svaBAva 115043
<ls>Spr. (II) 6781 </ls> svAti 115581
<ls>Spr. (II) 1584. -</ls> svAdu 115602
<ls>Spr. (II) 4736)</ls> svecCA 115801
<ls>Spr. (II)</ls> han 115989
<ls>Spr. (II) 6841,</ls> hayaSAstra 116065
<ls>Spr. (II) 5656 - 5678.</ls> hi 116887
<ls>Spr. (II) 6128)</ls> hita 116942
<ls>Spr. (II) 6629, v. l. -</ls> hInatas 117216
<ls>Spr. (II)</ls> utpAdaka 118984
<ls>Spr. (II)</ls> kfpAlutA 119576
<ls>Spr. (II) 2533,</ls> bAhya 121285
<ls>Spr. (II) 5249,</ls> rUpasanAtana 121798

"""
def get_datax():
 lines1 = dataxraw.splitlines()
 lines = []
 for line in lines1:
  line = line.strip()
  if line == '':
   continue
  line = re.sub('</ls>.*$','</ls>',line)
  lines.append(line)
 return lines

data4list = get_datax()

def change_ls_matching_given_x(line):
 for ls in data4list:
  if ls in line:
   return True,line
 return False,line

if __name__=="__main__":
 option = sys.argv[1]
 filein = sys.argv[2] #  xxx.txt (path to digitization of xxx
 fileout = sys.argv[3] # change_X

 entries = init_entries(filein)
 fname = 'change_ls_matching_given_%s' % option
 changef = locals()[fname]
 changes = []  # list of change records
 for entry in entries:
  for iline,line in enumerate(entry.datalines):
   flag,newline = changef(line)
   if flag: #
    lnum = entry.linenum1+iline+1
    metaline = re.sub(r'<k2>.*$','',entry.metaline)
    change = Change(metaline,lnum,line,newline)
    changes.append(change)

 write_changes(fileout,changes)


import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
    def handel(self):
        while True:
            try:
                self.data = self.request.recv(1024).strip()
                print('{}wrote：'.format(self.client_address[0]))
                print(self.data)
                self.request.sendall(self.data.upper())
            except ConnectionResetError as e:
                print('error',e)
                break

if __name__ =='__main__':
    HOST,PORT = 'localhost',9999
    #创建一个服务，将localhost绑定到9999端口
    server = socketserver.TCPServer((HOST,PORT),MyTCPHandler)
    server.serve_forever()


def dijkstrasAlgorithm(graph, costs, parents, processed):
    node = findLowestCostNode(costs, processed) # Find lowest cost node that hasnt been processed
    while node is not None: # Loop until all nodes have been processed
        cost = costs[node]
        neighbors = graph[node]
        for n in neighbors.keys(): # Go thru the neighbours of this node
            newCost = cost + neighbors[n]
            # If it's cheaper to get to this neighbor by going through the current node,
            # update the cost for this node
            if costs[n] > newCost: # If it's cheaper to get to this neighbor by going through the current node,
                costs[n] = newCost # update the cost for this node
                parents[n] = node # This node becomes the new parent for this neighbor
        processed.append(node) # Mark node as proccessed
        node = findLowestCostNode(costs, processed) # Find the next node to proccess, and loop

def findLowestCostNode(costs, processed):
    lowestCost = float("inf")
    lowestCostNode = None
    for node in costs:
        cost = costs[node]
        # If its the lowest cost so far and hasn't been processed yet,
        # set it as the new lowest cost node
        if cost < lowestCost and node not in processed:
            lowestCost = cost
            lowestCostNode = node
    return lowestCostNode

def makeGraph():
    graph = dict()
    graph["start"] = dict()
    graph["start"]["a"] = 6
    graph["start"]["b"] = 2

    graph["a"] = dict()
    graph["a"]["fin"] = 1

    graph["b"] = dict()
    graph["b"]["a"] = 3
    graph["b"]["fin"] = 5

    graph["fin"] = dict()

    return graph

def makeCosts(graph):
    costs = dict()
    costs["start"] = 0
    # Set the costs of all nodes that you can reach from the "start"
    for childNode in graph["start"].keys():
        costs[childNode] = graph["start"][childNode]

    # Set the costs of all the nodes you can't reach from the "start" node to infinity
    for node in graph.keys():
        if node not in costs:
            costs[node] = float("inf")

    return costs

def makeParents(graph):
    parents = dict()
    # Set the parent of all nodes that you can reach from the "start"
    for childNode in graph["start"].keys():
        parents[childNode] = "start"

    # Set the parent of all the nodes you can't reach from the "start" node to None
    for node in graph.keys():
        if node not in parents:
            parents[node] = None

    return parents

def main():
    graph = makeGraph()
    costs = makeCosts(graph)
    parents = makeParents(graph)
    processed = []
    dijkstrasAlgorithm(graph, costs, parents, processed)
    print("COSTS: " + str(costs))
    print("PARENTS: " + str(parents))

if __name__ == "__main__":
    main()


"""

Este programa es un juego de gato.

"""
from random import randint

def players_choice():
    """
    Definicion de la funcion
    :return:
    """

    char = ''
    player1_choice, player2_choice = '', ' '
    i = int(randint(0, 1))

    while char not in ('X', 'O'):
        # os.system('cls')
        player1_choice = input("\nSeleccione con que figura desea jugar 'X' o 'O': ")
        char = player1_choice.upper()
        if char not in ('X', 'O'):
            # os.system('cls')
            print('Opcion no valida, intente de nuevo.')
        else:
            player1_choice = char

    if char == 'X':
        player2_choice = 'O'
    elif char == 'O':
        player2_choice = 'X'

    if i == 1:
        print(f'Jugador {player1_choice}, inicia.')
        marker = player1_choice
    else:
        print(f'Jugador {player2_choice}, inicia.')
        marker = player2_choice

    display_board([])

    return marker

def player_turn(player):
    """
        Definicion de la funcion
        :return:
        """

    if player == 'X':
        return 'O'

    return 'X'

def display_board(board):
    """
        Definicion de la funcion
        :return:
        """
    print_board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
    if 'X' in board or 'O' in board:
        for index in range(0, len(board), 2):
            if board[index] == 'X' or board[index] == 'O':
                print_board[board[index+1]-1] = board[index]
            else:
                pass
    else:
        pass

    print('     |     |    ')
    print(f'  {print_board[6]}  |  {print_board[7]}  |  {print_board[8]} ')
    print('-----|-----|----')
    print(f'  {print_board[3]}  |  {print_board[4]}  |  {print_board[5]} ')
    print('-----|-----|----')
    print(f'  {print_board[0]}  |  {print_board[1]}  |  {print_board[2]} ')
    print('     |     |    \n')

    return print_board

def place_holder(marker, position, board):
    """
        Definicion de la funcion
        :return:
    """

    if position in board:
        print('Casilla ya ocupada, vuelva a seleccionar...')
        marker, num = player_input(marker)
        place_holder(marker, num, board)
    else:
        board.append(marker)
        board.append(position)

    return board

def player_input(marker):
    """
        Definicion de la funcion
        :return:
    """

    print(f'Jugador {marker}, su turno...')
    num = 0
    while num not in range(1, 10):
        option = input('Seleccione una celda de 1-9: ')
        # print(option.isdigit())
        if option.isdigit():
            num = int(option)
            if num not in range(1, 10):
                print('Opcion no valida, por favor seleccione un numero entre 1-9.\n')
            else:
                continue
        else:
            print('Opcion no valida, por favor seleccione un numero entre 1-9.\n')
        # else:
        # num = int(option)
    return marker, num

def check_victory(board, marker):
    """
            Definicion de la funcion
            :return:
    """

    if board[0] == board[1] == board[2] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[3] == board[4] == board[5] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[6] == board[7] == board[8] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[0] == board[3] == board[6] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[1] == board[4] == board[7] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[2] == board[5] == board[8] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[0] == board[4] == board[8] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif board[6] == board[4] == board[2] == marker:
        print(f'Felicidades jugador {marker}, usted ha ganado!')
    elif ' ' not in board:
        print('Empate!')
        return True
    else:
        return False
    return True

def keep_playing():
    """
        Definicion de la funcion
        :return:
    """
    char = ''

    while char not in ('X', 'O'):
        # os.system('cls')
        opcion = input("\nDesea seguir jugando? Y/N: ")
        char = opcion.upper()
        if char not in ('Y', 'N'):
            # os.system('cls')
            print('Opcion no valida, intente de nuevo.')
        elif char == 'N':
            return False
        else:
            pass
    return True

'''
## PROGRAMA ##
import TicTacToe as ttt

KEEP = True
while KEEP:
    MARCADOR = ttt.players_choice()
    TABLERO = []
    GANADOR = False
    while not GANADOR:
        FIGURA, POSICION = ttt.player_input(MARCADOR)
        TABLERO = ttt.place_holder(FIGURA, POSICION, TABLERO)
        BOARD = ttt.display_board(TABLERO)
        GANADOR = ttt.check_victory(BOARD, FIGURA)
        MARCADOR = ttt.player_turn(MARCADOR)

    KEEP = ttt.keep_playing()
'''


from django.shortcuts import render, redirect
from .models import Receipt, ExpenseCategory, Account
from django.contrib.auth.decorators import login_required
from receipts.forms import ReceiptForm, CategoryForm, AccountForm

# Create your views here.

# @login_required
# def receipt_list(request):
#     receipts = Receipt.objects.all()
#     context = {
#         "receipts": receipts,
#     }
#     return render(request, "receipts/list.html", context)

@login_required
def receipt_list(request):
    receipts = Receipt.objects.filter(purchaser=request.user)
    context = {
        "receipts": receipts,
    }
    return render(request, "receipts/list.html", context)

@login_required
def create_receipt(request):
    if request.method == "POST":
        form = ReceiptForm(request.POST)
        if form.is_valid():
            receipt = form.save(False)
            receipt.purchaser = request.user
            receipt.save()
            return redirect("home")
    else:
        form = ReceiptForm()
    context = {
        "form": form,
    }
    return render(request, "receipts/create.html", context)

@login_required
def category_list(request):
    categories = ExpenseCategory.objects.filter(owner=request.user)
    context = {
        "categories": categories,
    }
    return render(request, "categories/list.html", context)

@login_required
def account_list(request):
    accounts = Account.objects.filter(owner=request.user)
    context = {
        "accounts": accounts,
    }
    return render(request, "accounts/list.html", context)

@login_required
def create_category(request):
    if request.method == "POST":
        form = CategoryForm(request.POST)
        if form.is_valid():
            category = form.save(False)
            category.owner = request.user
            category.save()
            return redirect("category_list")
    else:
        form = CategoryForm()
        context = {"form": form}
    return render(request, "categories/create.html", context)

@login_required
def create_account(request):
    if request.method == "POST":
        form = AccountForm(request.POST)
        if form.is_valid():
            account = form.save(False)
            account.owner = request.user
            account.save()
            return redirect("account_list")
    else:
        form = AccountForm()
        context = {
            "form": form,
        }
    return render(request, "accounts/create.html", context)