import csv
import sys
import os

class ToDoApp():

    def __init__(self):
        self.file_name = 'C:/Users/Gáspár/Desktop/Greenfox/szuri92/week-05/day-5/tasks.csv'
        self.mode = sys.argv
        self.loop()

    def file_opener(self, permission):
        try:
            f = open(self.file_name, permission)
        except FileNotFoundError:
            f = open(self.file_name, 'a')
            f.close()
            f = open(self.file_name, permission)
        return f

    def csv_to_list(self):
        f = self.file_opener('r')
        csv_f = csv.reader(f, delimiter = ';')
        lista = list(csv_f)
        f.close()
        return lista

    def csv_delete(self):
        f = self.file_opener('w')
        csv.writer(f)
        f.close()

    def write_task(self, a_task):
        f = self.file_opener('a')
        lista = ['doing']
        lista.append(a_task)
        writer = csv.writer(f, delimiter=';', lineterminator ='\n')
        writer.writerow(lista)
        f.close()

    def display_list(self):
        f = self.file_opener('r')
        csv_f = csv.reader(f, delimiter = ';')
        lista = list(csv_f)
        if len(lista) <= 0:
            print('No todos toady! :)')
        for i in range(len(lista)):
            if lista[i][0] == 'done':
                #print( str( i + 1 ) + ' - [X] ' + lista[i][1])
                print('{} - [X] {}'.format(i+1, lista[i][1]))
            else:
                #print( str( i + 1 ) + ' - [ ] ' + lista[i][1])
                print('{} - [ ] {}'.format(i+1, lista[i][1]))

    def delete(self, number):
        lista = self.csv_to_list()
        if number in range(1, len(lista)+1):
            lista.remove(lista[number-1])
            self.csv_delete()
            c = self.file_opener('a')
            csv_a = csv.writer(c, delimiter =';', lineterminator = '\n')
            for i in range(len(lista)):
                csv_a.writerow(lista[i])
            c.close()
        else:
            print('Unable to remove: Index is out of bound')

    def check_task(self, number):
        lista = self.csv_to_list()
        if number in range(1, len(lista)+1):
            self.csv_delete()
            for i in range(len(lista)):
                if i == number-1:
                    lista[i][0] = 'done'
            c = self.file_opener('a')
            csv_a = csv.writer(c, delimiter = ';', lineterminator = '\n')
            for i in range(len(lista)):
                csv_a.writerow(lista[i])
            c.close()
        else:
            print('Unable to check: Index is out of bound')

    def loop(self):
        if len(self.mode) <= 1:
            os.system('cls' if os.name == 'nt' else 'clear')
            print('Python Todo application')
            print('=======================\n')
            print('Command line arguments:')
            print(' -l   Lists all the tasks')
            print(' -a   Adds a new task')
            print(' -r   Removes an task')
            print(' -c   Completes an task')
        elif len(self.mode) == 2:
            if self.mode[1] == '-l':
                os.system('cls' if os.name == 'nt' else 'clear')
                self.display_list()
            elif self.mode[1] == '-a':
                print('Unable to add: No task is provided')
            elif self.mode[1] == '-r':
                print('Unable to remove: No index is provided')
            elif self.mode[1] == '-c':
                print('Unable to check: No index is provided')
            else:
                print('Unsupported argument')
        elif len(self.mode) > 2:
            if self.mode[1] == '-a' and self.mode[2] != '' and len(self.mode) > 2:
                for i in range(3, len(self.mode)):
                    self.mode[2] += ' ' + self.mode[i]
                self.write_task(self.mode[2])
            elif self.mode[1] == '-r' and self.mode[2] != '':
                try:
                    self.delete(int(self.mode[2]))
                except ValueError:
                    print('Unable to remove: Index is not a number')
            elif self.mode[1] == '-c' and self.mode[2] != '':
                try:
                    self.check_task(int(self.mode[2]))
                except ValueError:
                    print('Unable to check: Index is not a number')

application1 = ToDoApp()


import os
from fastapi import HTTPException
import jwt
import functools
from configparser import ConfigParser

def verify_jwt(func):
    """verifies the JWT token is valid"""
    @functools.wraps(func)
    def wrapper_verify_jwt(*args, **kwargs):
        token = kwargs['token']
        jwt_verify_result = TokenHelper(token.credentials).verify()
        if jwt_verify_result.get("status"):
            print("JWT invalid")
            raise HTTPException(status_code=401, detail=jwt_verify_result.get("message"))
        return func(*args, **kwargs)
    return wrapper_verify_jwt

def verify_jwt_with_scope(*expected_scopes):
    """verifies the JWT token is valid and has the required scopes"""
    def require_scope_actual(func):
        @functools.wraps(func)
        def wrapper_require_scope(*args, **kwargs):
            token = kwargs['token']
            jwt_verify_result = TokenHelper(token.credentials).has_scopes(*expected_scopes)
            if jwt_verify_result.get("status"):
                print("scope invalid")
                raise HTTPException(status_code=403, detail=jwt_verify_result.get("message"))
            return func(*args, **kwargs)
        return wrapper_require_scope
    return require_scope_actual

def set_up():
    """Sets up configuration for the app"""

    env = os.getenv("ENV", ".config")

    if env == ".config":
        config = ConfigParser()
        config.read(".config")
        config = config["AUTH0"]
    else:
        config = {
            "DOMAIN": os.getenv("DOMAIN", "your.domain.com"),
            "API_AUDIENCE": os.getenv("API_AUDIENCE", "your.audience.com"),
            "ISSUER": os.getenv("ISSUER", "https://your.domain.com/"),
            "ALGORITHMS": os.getenv("ALGORITHMS", "RS256"),
        }
    return config

class TokenHelper():
    """Does all the token verification using PyJWT"""

    def __init__(self, token):
        self.token = token
        self.config = set_up()

        # This gets the JWKS from a given URL and does processing so you can
        # use any of the keys available
        jwks_url = f'https://{self.config["DOMAIN"]}/.well-known/jwks.json'
        self.jwks_client = jwt.PyJWKClient(jwks_url)

    def verify(self):
        # Verify the JWT token and extract the payload
        try:
            self.signing_key = self.jwks_client.get_signing_key_from_jwt(
                self.token
            ).key
        except jwt.exceptions.PyJWKClientError as error:
            return {"status": "error", "msg": error.__str__()}
        except jwt.exceptions.DecodeError as error:
            return {"status": "error", "msg": error.__str__()}

        try:
            payload = jwt.decode(
                self.token,
                self.signing_key,
                algorithms=self.config["ALGORITHMS"],
                audience=self.config["API_AUDIENCE"],
                issuer=self.config["ISSUER"],
            )
        except Exception as e:
            return {"status": "error", "message": str(e)}

        print("JWT payload: %s" % payload)
        return payload

    def has_scopes(self, *expected_scopes):
        """Checks if the token is valid (see verify) and has the required scopes"""
        payload = self.verify()
        scope = payload.get("scope", "")
        if len(expected_scopes) == 0:
            return {}
        if scope == "":
            return {"status": "error", "message": "Invalid scope"}
        token_scopes = scope.split(" ")
        # print("Token scopes: %s" % token_scopes)
        # print ("Expected scopes: %s" % expected_scopes)
        for expected_scope in expected_scopes:
            if expected_scope not in token_scopes:
                return {"status": "error", "message": "Invalid scope"}
        return {}


# from pprint import pprint
# a = [["test", 12], ["test_1", 23], ["test)", 234]]
# c = dict(a)
# pprint(c)
person = {}
s = "Ivanow Ivan Kharkiv KPY 5 5 5 5 5 5"
s = s.split()
person['Last_Name'] = s[0]
person['First_Name'] = s[1]
person["Sity"] = s[2]
person["University"] = s[3]
person["marks"] = []
for i in s[4:]:
    person["marks"].append(int(i))

print(s)
print(person)
print(len(person))
for i in person:
    print(i, person[i])


"""
    Purpose: This program is to demostrate one dimensional
            finite difference time domain electromagnetic simulation.
             This program os simply demostrate one dimensional electromagnetic
             wave propagates along z direction.
             This code is an implementation of examples in Sullivan's FDTD textbook.
"""
sd
import numpy as np
import scipy.constants as const
import matplotlib.pyplot as plt
import sys
import time

#output field data to a text file
class FieldOutput:
    def __init__(self, fileName, xpt, v):
        self.prefixName = fileName
        self.xPoints = xpt
        self.field = v
        self.dumpSteps = set()

    def addDumpStep(self, step):
        self.dumpSteps.add(step)

    #perform output actions
    def dump(self, nowStep):
        if not (nowStep in self.dumpSteps):
            return
        nm = self.prefixName + "_" + str(nowStep) + ".txt"
        f = open(nm, 'w')
        for i in range(len(self.xPoints)):
            f.write(str(self.xPoints[i]) + "," + str(self.field[i]) + "\n")
        f.close()

#update electric field and magnetic field according to FDTD algorithm
class FDTDUpdater:
    def __init__(self, exField, hyField, dtt, dtCoeff):
        self.ex = exField
        self.hy = hyField
        self.nowTime = 0.0
        self.dtCoeffecient = dtCoeff
        self.dt = dtt
        self.numberOfGrids = len(exField)
        self.src = None

    def update(self):
        if (self.src is None):
            print("source of the FDTD simulation is not given!n")
            sys.exit(-1)

        self.nowTime = self.nowTime + self.dt
        ##update electric field
        self.ex[1:len(self.ex) - 1] = self.ex[1:len(self.ex) - 1] + self.dtCoeffecient * (
                self.hy[0:len(self.hy) - 1] - self.hy[1:len(self.hy)])

        ##update source
        self.ex[0] = self.src(self.nowTime)

        ##update magnetic field
        self.hy[0:len(self.hy)] = self.hy[0:len(self.hy)] + self.dtCoeffecient * (
                self.ex[0:len(self.ex) - 1] - self.ex[1:len(self.ex)])

    def setSource(self, inp):
        self.src = inp

    def getNowTime(self):
        return self.nowTime

    def printNowTime(self):
        print("nowTime = " + str(self.nowTime) + "n")

##generate a time sequential 1D Gaussian beam
def GaussianBeam(e0, t0In, tau_in, wc_in):
    E0 = e0  ##amplitude
    t0 = t0In  ##time when center appeared
    tau = tau_in  ##Gaussian beam half-width
    wc = wc_in  ##radial frequency

    def inner(T):
        ##update source
        if (abs(t0 - T) < 2.0 * tau):
            return E0 * np.exp(-1.0 * np.power((t0 - T) / tau, 2.0)) * np.cos(wc * (t0 - T))
        return 0

    return inner

def main():
    startTime = time.time()
    #Define used parameters
    ##nitialize simulation and laser parameters
    wavelength = 810e-9  ## laser wavelength
    tau = 29.72e-15  ##half temporal width of simulated electromagnetic gaussian beam in second.

    ##radial frequency of the simulated electromagnetic wave, corresponding wavelength is 810 nm.
    wc = const.c / wavelength * const.pi * 2.0
    ##define simulation resolution parameters
    dtCoeffecient = 0.99  ##for Courant condition
    dz = wavelength / 32.0  ##spatial grid interval in meter
    dt = dz * dtCoeffecient / const.c  ##time step interval used in the sumulation
    numberOfGrids = int(
        np.floor(4.0 * tau * const.c / dz)) + 200  ##grid number is 4 times half temporal width and extra 200 cell.
    t0 = 2.0 * tau + 100.0 * dt  ##The time when pulse peak appeared in the simulation domain
    NSTEPS = int(np.floor(4.0 * tau / dt))  ##Maximum number of steps
    E0 = 1.0  ##maximum amplitude of the electric field in V/m

    ##declare and initialize field data
    ex = np.zeros(numberOfGrids)  ##electric field data
    hy = np.zeros(numberOfGrids - 1)  ##magnetic field data
    updater = FDTDUpdater(ex, hy, dt, dtCoeffecient)
    src = GaussianBeam(E0, t0, tau, wc)
    updater.setSource(src)

    ##setup dump related setting
    xGridPt = np.zeros(numberOfGrids)  ##grid coordinates
    xCellPt = np.zeros(numberOfGrids - 1)  ##grid coordinates
    ##Initialize x grid points data
    for k in range(numberOfGrids):
        xGridPt[k] = k * dz
    ##Initialize x cell points data
    for k in range(numberOfGrids - 1):
        xCellPt[k] = (k + 0.5) * dz

    exOut = FieldOutput("gaussian_Ex", xGridPt, ex)  ##electric field is on grid point.
    hyOut = FieldOutput("gaussian_Hy", xCellPt, hy)  ##magnetic field is at half cell.
    ##setup dump time
    dumpNumber = 5.0  ##total number of data dump
    interval = int(np.floor(NSTEPS / dumpNumber))  ##get interval between data dump according to dumpNUmber
    for i in range(int(np.floor(dumpNumber))):
        exOut.addDumpStep(interval * (i + 1))
        hyOut.addDumpStep(interval * (i + 1))

    ##main loop
    for n in range(NSTEPS):
        updater.update()
        ##updater.printNowTime()
        exOut.dump(n)
        hyOut.dump(n)

    endTime = time.time()
    print("Execution time = " + str(endTime - startTime) + " (s)")
    return 0

if __name__ == "__main__":
    main()


import math

def is_prime(num):
    if num == 1:
        return False

    for i in range(2, round(math.sqrt(num)) + 1):
        if (num % i) == 0:
            return False

    return True

found_primes = 0
i = 1
while True:
    if is_prime(i):
        found_primes += 1
        # print(i)

    if found_primes == 10001:
        print(i)
        break

    i += 1


import asyncio
from aiosmtpd.controller import Controller
from aiosmtpd.smtp import Envelope, Session, SMTP
from email.message import Message
import spf
import time

import botlog as log
import config
import exceptions
import email_server.exceptions as email_exc
import email_server.email_storage as store
import email_server.email_processor as proc
import email_server.integrity as dupe_c
import email_server.whitelist as whitelist
from email_server.models import InboundMessage

SentMessages = {}

# SMTP Reply Codes: https://www.greenend.org.uk/rjk/tech/smtpreplies.html
# aiosmtpd handlers: https://aiosmtpd.readthedocs.io/en/latest/aiosmtpd/docs/handlers.html
class Hermes_EmailHandler:
    async def handle_EHLO(self, server: SMTP, session: Session, envelope: Envelope, hostname: str):
        log.LogConsoleInfoVerbose('EHLO Received from ' + hostname)
        session.host_name = hostname
        return '250 HELP'

    # SPF implementation found here: https://github.com/denself/simple_mail_server
    async def handle_MAIL(self, server: SMTP, session: Session, envelope: Envelope, address: str, mail_options: list):
        try:
            ip_address = session.peer[0]

            if not proc.VerifySymphonyConnection():
                return '421 Symphony is currently unavailable. Try again later.'

            if config.UseSPFChecking:
                result, description = spf.check2(ip_address, address, session.host_name)
                log.LogConsoleInfoVerbose('SPF Check [' + ip_address + ', ' + address + ', ' + session.host_name +
                                          ' ]: ' + result + ' | ' + description)

                valid_spf = result == 'pass'
                envelope.spf = valid_spf

                if not valid_spf:
                    log.LogSystemErrorVerbose('SPF Check failed - email rejected.')
                    return '550 SPF validation failed.'
            else:
                envelope.spf = True

            if config.UseInboundWhitelist and not whitelist.IsWhitelistedIP(ip_address):
                log.LogSystemErrorVerbose('Whitelist Check failed - email rejected.')
                return '550 Origin blocked.'

            # Check that the user is a valid Symphony user or room
            log.LogSystemInfoVerbose('SMTP MAIL: Checking sender(' + address + ') is valid...')
            sender_rcp = proc.ValidateSender(address.lower())  # proc.ValidateUser(address)

            if config.EnforceSenderRestriction and not sender_rcp:
                log.LogSystemErrorVerbose('Sender is not recognized. (' + address + ')')
                return '550 Sender is not recognized.'

            envelope.mail_from = address
            envelope.mail_options.extend(mail_options)

        except email_exc.SymphonyUserLookupException as user_ex:
            log.LogSystemErrorVerbose('Sender is not recognized. Error: ' + str(user_ex))
            return '550 Sender is not recognized.'
        except Exception as ex:
            exceptions.LogException(ex)
            return '500 Unexpected server malfunction'

        return '250 OK'

    async def handle_RCPT(self, server: SMTP, session: Session, envelope: Envelope, address: str, rcpt_options: list):
        rcpt_domain = address.split('@')[1]

        log.LogSystemInfoVerbose('SMTP RCPT: Verifying recipient (' + address + ')')
        log.LogSystemInfoVerbose('SMTP RCPT: Recipient verification is disabled.')

        try:
            # reject recipients with domains not found in valid_domains
            if config.ValidDomains and rcpt_domain not in config.ValidDomains:
                log.LogSystemErrorVerbose('Recipient Domain invalid. Recipient rejected.')
                return '550 recipient domain is invalid.'

            # Check that the recipient is a valid Symphony user or room
            # if the recipient is valid, append the address to the envelope recipients list and return OK
            # if proc.ValidateUser(address):

            envelope.rcpt_tos.append(address)

        except email_exc.SymphonyUserLookupException as user_ex:
            exceptions.LogException(user_ex, 'Recipient not found in Symphony.')
            # return '554 Recipient not recognized'

        return '250 OK'

    async def handle_DATA(self, server: SMTP, session: Session, envelope: Envelope):
        log.LogSystemInfoVerbose('SMTP DATA: Processing inbound email message.')
        peer = session.peer
        mail_from = envelope.mail_from
        rcpt_tos = envelope.rcpt_tos
        data = envelope.content  # type: bytes

        # TODO: Possibly implement DKIM here
        inbound = InboundMessage(peer, mail_from, rcpt_tos, data)

        try:
            if config.SaveInboundEmail:
                store.SaveInboundEmail(mail_from, data)

            proc.ProcessInboundEmail(inbound)

        except email_exc.SymphonyEmailBodyParseFailedException as mail_ex:
            exceptions.LogException(mail_ex, 'Email content was unreadable or uninteresting.')
            return '500 Email content was unreadable or uninteresting.'
        except Exception as ex:
            exceptions.LogException(ex)
            return '500 Could not process your message'

        return '250 OK'

def start_server():
    handler = Hermes_EmailHandler()
    controller = Controller(handler, hostname=config.SMTPServerHost, port=config.SMTPServerPort)
    heartbeat_index = 1

    try:
        # Run the event loop in a separate thread
        log.LogSystemInfo('Starting SMTP server on dedicated thread...')
        controller.start()

        while True:
            time.sleep(60)
            heartbeat_index += 1

            dupe_c.ClearExpired()

            if heartbeat_index == 30:
                log.LogSystemInfoVerbose('Heartbeat...ba-dump...')
                heartbeat_index = 0

        # TODO: Create a better handler for exiting from the server
        # controller.stop()
    except Exception as ex:
        exceptions.LogException(ex)
    finally:
        log.LogSystemInfo('Stopping SMTP server...')
        # controller.stop()


from oslo_log import log as logging
from tempest import config
from tempest import test

from contrail_tempest_plugin.services.contrail.json.namespace_client import \
    NamespaceClient

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

class BaseContrailTest(test.BaseTestCase):
    """Base class for Contrail tests."""
    credentials = ['primary', 'admin']

    '''
    @classmethod
    def skip_checks(cls):
        super(BaseContrailTest, cls).skip_checks()
        if not CONF.service_available.contrail:
            raise cls.skipException("Contrail support is required")
    '''

    @classmethod
    def setup_credentials(cls):
        super(BaseContrailTest, cls).setup_credentials()

    @classmethod
    def setup_clients(cls):
        super(BaseContrailTest, cls).setup_clients()
        cls.auth_provider = cls.os.auth_provider
        cls.namespace_client = NamespaceClient(
            cls.auth_provider,
	    CONF.sdn.catalog_type,
	    CONF.identity.region,
	    CONF.sdn.endpoint_type)
        cls.admin_client = cls.os_adm.network_client


#loading the inverted_index to the program
import pickle
fileObject=open("Inverted_index",'rb')
inverted = pickle.load(fileObject)

_STOP_WORDS = frozenset([
"and", "but", "is", "the", "to"])

def word_split(text):
    """
    Split a text in words. Returns a list of
    (word, positions) location is a list of position of the word.
    """
    word_list = []
    wcurrent = []
    windex = None
    o_w_list=text.split()
    for i in range (len(o_w_list)):
        word_list.append((i,o_w_list[i]))

    return word_list

def words_normalize(words):
    """
    Do a normalization precess on words. In this case is just a to lower(),
    """
    normalized_words = []
    for word in words:
        wnormalized = word.lower()
        normalized_words.append((wnormalized))
    return normalized_words

def words_cleanup(words):
    """
    Remove words stopwords.
    """
    cleaned_words = []
    for word in words:
        if word in _STOP_WORDS:
            continue
        cleaned_words.append((word))
    return cleaned_words

def search(inverted, query):
#     """
#     Returns a set of documents id that contains all the words in your query.
#     """
    result = {}
    if query in inverted.keys():
        result[query]=inverted[query]
    return result

# Update the list of positions by deleting the common id.
def delete_id (dic,common_id):
    for key in dic.keys():
        for i in list(dic[key].keys()):
            if i in common_id:
                dic[key].pop(i)
    return dic

#return the list of positions inside a dic
def find_id (dic):
    res=[]
    for key in dic:
        res.extend(list(dic[key].keys()))
    return res

#find the list of id doesnot belongs to lst1 or lst2
def find_delete_id(lst1,lst2):
    return list(set(lst1) ^ set(lst2))

import copy
def boolean_search(inverted_new,q_str):
    q_lst=q_str.split()
    q_lst=words_normalize(q_lst)
    c_res={}
    i=0
    inverted=copy.deepcopy(inverted_new)
    while i<len(q_lst):
        if q_lst[i]=='and' and i+1<len(q_lst):
            s_next=search(inverted,q_lst[i+1])
            if s_next=={} or c_res=={}:
                for key in c_res:
                    c_res[key]={}
                c_res[q_lst[i+1]]={}
                i+=1
            else:
                id1=find_id(c_res)
                id2=find_id(s_next)
                d_id=find_delete_id(id1,id2)
                delete_id(c_res,d_id)
                delete_id(s_next,d_id)
                c_res[q_lst[i+1]]=s_next[q_lst[i+1]]
                i+=1
        if q_lst[i]=='or':
            s_then=search(inverted_new,q_lst[i+1])
            c_res[q_lst[i+1]]=s_then[q_lst[i+1]]
            i+=1
        if i==0:
            c_res=search(inverted,q_lst[i])
        i+=1
    print (c_res)
    return c_res

def main():
    q_str = str(input("Please a query or a boolean query:   \n"))
    q_str=''.join([i for i in q_str if not i.isdigit()])
    boolean_search(inverted,q_str)

main()


import torch.nn as nn

from common import classifications

class DenseMutationNet(nn.Module):
	def __init__(self):
		super().__init__()
		self.fc01 = nn.Linear(5750, 512)
		self.fc02 = nn.Linear(512, 512)
		self.fc03 = nn.Linear(512, len(classifications))
		self.drop = nn.Dropout(0.5)

	def forward(self, x):
		x = self.fc01(x)
		x = self.drop(x)
		x = self.fc02(x)
		x = self.drop(x)
		x = self.fc03(x)
		return x


import matplotlib.pyplot as plt
import temperature_level_histogram as tmp
def fetch_temp_data():
    tmp_df=tmp.fetchtempdata()
    tmp_df=tmp_df.groupby('City')['AverageTemperature'].first().reset_index()
    tmp_df=tmp_df.nlargest(10, 'AverageTemperature') ## Fetching 10 records based on AverageTemperature
    return tmp_df

def generate_temp_scatterplot(df):
    yr_data=df['City']
    tot_data=df['AverageTemperature']

    # Create scatter plot
    plt.scatter(yr_data,tot_data)

    # Add labels and title
    plt.xlabel('City')
    plt.ylabel('AverageTemperature')
    plt.title('Scatter Plot for Temperature Level')

    # Display the plot
    plt.show()

def main():
    tmp_df=fetch_temp_data()
    generate_temp_scatterplot(tmp_df)

if __name__ == "__main__":
    main()


import re
from os import remove, mkdir, geteuid, getenv
from os.path import isdir, isfile, realpath, dirname, join
from time import strftime, sleep
from pwd import getpwnam
from spwd import getspall

from gi.repository import Gtk
from gi.repository import GObject

import gettext
from gettext import gettext as _
from gettext import ngettext
import sys

#If DEVACTIVE is true, it uses files from local directory
DEVACTIVE = False

if DEVACTIVE:
    from sys import path
    path.append('.')

from common.timekprpam import *
from common.timekprcommon import *

#timekpr.conf variables (dictionary variable)
VAR = getvariables(DEVACTIVE)
VERSION = getversion()

#translation stuff
def init_locale():
    locale_domain = "timekpr" # must match locale domain set in *.ui files
    locale_path = '/usr/share/locale'

    # init python gettext
    gettext.bindtextdomain(locale_domain, locale_path)
    gettext.textdomain(locale_domain)

#Check if admin/root
def check_if_admin():
    if geteuid() != 0:
        dlg = Gtk.MessageDialog(None, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, _("You need to have administrative privileges to run timekpr-gui"))
        dlg.set_default_response(Gtk.ResponseType.CLOSE)
        dlg.run()
        dlg.destroy()
        exit("Error: You need to have administrative privileges to run timekpr")

#Create configuration folder if not existing
def create_dirs():
    if not isdir(VAR['TIMEKPRDIR']):
        mkdir(VAR['TIMEKPRDIR'])
    if not isdir(VAR['TIMEKPRWORK']):
        mkdir(VAR['TIMEKPRWORK'])
    if not isdir(VAR['TIMEKPRSHARED']):
        exit('Error: Could not find the shared directory %s' % VAR['TIMEKPRSHARED'])

#Check if it is a regular user, with userid within UID_MIN and UID_MAX.
def is_regular_user(user_name):
    #FIXME: Hide active user - bug #286529
    if getenv('SUDO_USER') and user_name == getenv('SUDO_USER'):
        return False

    try:
        password_database_entry = getpwnam(user_name)
        user_id = int(password_database_entry[2])
        logindefs = open('/etc/login.defs')
        uid_limits = [int(x) for x in re.compile('^UID_(?:MIN|MAX)\s+(\d+)', re.M).findall(logindefs.read())]
    except (KeyError, ValueError):
        return False

    return min(uid_limits) <= user_id <= max(uid_limits)

def rm(filename):
    try:
        remove(filename)
    except OSError:
        pass

class timekprGUI(object):

    def __init__(self):
        ui_file = join(VAR['TIMEKPRSHARED'], 'main_window.ui')

        self.builder = Gtk.Builder()
        self.builder.add_from_file(ui_file)

        #connect signals to python methods
        self.builder.connect_signals(self)

        #connect gtk objects to python variables
        for obj in self.builder.get_objects():
            if issubclass(type(obj), Gtk.Buildable):
                name = Gtk.Buildable.get_name(obj)
                setattr(self, name, obj)

        self.mainwindow.set_title(_('Timekpr Control Panel'))

        #create lists of limit and boundary gtk objects
        self.limitSpins = [self.builder.get_object("limitSpin" + str(x)) for x in range(7)]
        self.fromSpins = [self.builder.get_object("fromSpin" + str(x)) for x in range(7)]
        self.toSpins = [self.builder.get_object("toSpin" + str(x)) for x in range(7)]
        self.boundariesLabels = [self.builder.get_object("boundariesLabel" + str(x)) for x in range(7)]
        self.limitLabels = [self.builder.get_object("limitLabel" + str(x)) for x in range(7)]

        self.statusbarCID = self.statusbar.get_context_id("timekprstatus")

        self.limits = []

        #Using /etc/shadow spwd module
        for userinfo in getspall():
            if is_regular_user(userinfo[0]):
                self.userSelectCombo.append_text(userinfo[0])
                self.userSelectCombo.set_active(0)

        #Ensure we have at least one available normal user
        if self.userSelectCombo.get_active_text() is None:
            dlg = Gtk.MessageDialog(None, 0, Gtk.MessageType.ERROR, Gtk.ButtonsType.CLOSE, _("You need to have at least one normal user available to configure timekpr"))
            dlg.set_default_response(Gtk.ResponseType.CLOSE)
            dlg.run()
            dlg.destroy()
            exit("Error: You need to have at least one normal user available to configure timekpr")

        self.on_userSelectCombo_toggled(self)

        return

    def remove_status_message(self, msgid):
        self.statusbar.remove(self.statusbarCID, msgid)

    def set_status_message(self, message):
        msgid = self.statusbar.push(self.statusbarCID, strftime("%Y-%m-%d %H:%M:%S ") + message)
        GObject.timeout_add(6000, self.remove_status_message, msgid)

    def on_window_destroy(self, *args):
        Gtk.main_quit(*args)

    def on_aboutMenuItem_selected(self, widget):
        ui_file = join(VAR['TIMEKPRSHARED'], 'about_dialog.ui')

        builder = Gtk.Builder()
        builder.add_from_file(ui_file)

        dialog = builder.get_object('aboutdialog')
        dialog.set_version(VERSION)
        dialog.set_translator_credits(_("translator-credits"))
        dialog.set_comments(_('Keep control of computer usage'))
        dialog.show_all()
        dialog.run()
        dialog.destroy()

    def on_lockUnlockButton_clicked(self, widget):
        if self.lockUnlockLabel.get_label() == _('Lock account'):
            #lock account
            lockuser(self.user)
            statusmsg = _("Locked account %s") % (self.user)
            self.set_status_message(statusmsg)
            self.read_settings_nolimits()
        else:
            #unlock account
            unlockuser(self.user)
            #remove .lock file
            lockf = join(VAR['TIMEKPRDIR'], self.user + '.lock')
            rm(lockf)
            logoutf = join(VAR['TIMEKPRWORK'], self.user + '.logout')
            rm(logoutf)
            latef = join(VAR['TIMEKPRWORK'], self.user + '.late')
            rm(latef)
            statusmsg = _("Unlocked account %s") % self.user
            self.set_status_message(statusmsg)
            self.read_settings_nolimits()

    def on_clearAllRestrictionsButton_clicked(self, widget):
        #clears all limits and their files
        #FIXME: A yes/no confirmation would be handy here
        timef = join(VAR['TIMEKPRWORK'], self.user + '.time')
        logoutf = join(VAR['TIMEKPRWORK'], self.user + '.logout')
        latef = join(VAR['TIMEKPRWORK'], self.user + '.late')
        allowf = join(VAR['TIMEKPRWORK'], self.user + '.allow')
        #Should remove .allow file? It's not a restriction
        rm(timef)
        rm(logoutf)
        rm(latef)
        rm(allowf)
        #Remove boundaries
        removeuserlimits(self.user)
        #Remove limits
        configf = join(VAR['TIMEKPRDIR'], self.user)
        rm(configf)
        #Unlock user
        unlockuser(self.user)

        statusmsg = _("Removed all restrictions for account %s") % self.user
        self.set_status_message(statusmsg)
        self.on_userSelectCombo_toggled(self)

    def on_resetTimeButton_clicked(self, widget):
        #clear the .time file
        timefile = join(VAR['TIMEKPRWORK'], self.user + '.time')
        rm(timefile)
        statusmsg = _("Cleared used up time for account %s") % self.user
        self.set_status_message(statusmsg)
        self.read_settings_nolimits()

    def on_rewardButton_clicked(self, widget):
        arg = self.rewardSpin.get_value_as_int()
        timefile = join(VAR['TIMEKPRWORK'], self.user + '.time')
        if isfile(timefile):
            f = open(timefile)
            tlast = int(f.read())
            f.close()
        else:
            tlast = 0
        tnew = tlast - arg * 60
        f = open(timefile, 'w')
        f.write(str(tnew))
        f.close()
        statusmsg = _("Applied reward of %(num)s minute(s) to account %(user)s") % {'num': arg, 'user': self.user}
        self.set_status_message(statusmsg)
        self.read_settings_nolimits()

    def on_extendLimitsButton_clicked(self, widget):
        #UPDATE: extend limits button is now "Bypass for today"
        #It now is the same as changing boundaries from 0 to 24 for today's day of the week.
        #.allow can still be useful - active (logged in user accounts) won't be killed
        index = int(strftime("%w"))
        wfrom = self.fromtolimits[0]
        wto = self.fromtolimits[1]
        wfrom[index] = '0'
        wto[index] = '24'
        removeuserlimits(self.user)
        adduserlimits(self.user, wfrom, wto)
        allowfile = join(VAR['TIMEKPRWORK'], self.user + '.allow')
        f = open(allowfile, 'w').close()
        statusmsg = _("Set access hours to 00-24 on %(day)s for account %(user)s") % {'day': strftime("%A"), 'user': self.user}
        self.set_status_message(statusmsg)
        self.on_userSelectCombo_toggled(self)

    def on_refreshButton_clicked(self, widget):
        statusmsg = _("Refreshed setting values from account %s") % self.user
        self.set_status_message(statusmsg)
        self.on_userSelectCombo_toggled(self)

    def on_cancelButton_clicked(self, widget):
        Gtk.main_quit()

    def read_boundaries(self):
        #from-to time limitation (aka boundaries) - time.conf
        if isuserlimited(self.user):
            #Get user time limits (boundaries) as lists from-to
            bfrom = self.fromtolimits[0]
            bto = self.fromtolimits[1]

            for i in range(7):
                self.fromSpins[i].set_value(float(bfrom[i]))
                self.toSpins[i].set_value(float(bto[i]))
            # Use boundaries?
            ub = True
            # Single boundaries? (set per day)
            sb = False
            #Are all boundaries the same?
            #If they're not same, activate single (per day) boundaries
            if [bfrom[0]] * 7 != bfrom or [bto[0]] * 7 != bto:
                sb = True
            #Even if boundaries are Al0000-2400, return False
            if not sb and bfrom[0] == '0' and bto[0] == '24':
                ub = False
            self.boundariesCheck.set_active(ub)
            self.singleBoundariesCheck.set_active(sb)
        else:
            for i in range(7):
                self.fromSpins[i].set_value(7)
                self.toSpins[i].set_value(22)
            self.boundariesCheck.set_active(False)
            self.singleBoundariesCheck.set_active(False)

    def read_limits(self):
        #time length limitation
        configFile = join(VAR['TIMEKPRDIR'], self.user)
        del self.limits[:]
        if isfile(configFile):
            fileHandle = open(configFile)
            self.limits = fileHandle.readline()
            self.limits = self.limits.replace("limit=( ", "")
            self.limits = self.limits.replace(")", "")
            self.limits = self.limits.split(" ")

            for i in range(7):
                self.limitSpins[i].set_value(float(self.limits[i]) / 60)

            # Single limits? (set per day)
            sl = False
            # Use limits?
            ul = True

            for i in range(1, 7):
                if self.limits[i] != self.limits[i-1]:
                    sl = True

            if self.limits[0] == '86400' and not sl:
                ul = False
            self.limitCheck.set_active(ul)
            self.singleLimitsCheck.set_active(sl)
        else:
            for i in range(7):
                self.limitSpins[i].set_value(120)
            self.limitCheck.set_active(False)
            self.singleLimitsCheck.set_active(False)

    def update_status_icons(self, uislocked):
        #Set icons in status gtk-yes or gtk-no
        lockgreen = join(VAR['TIMEKPRSHARED'], 'padlock-green.png')
        lockred = join(VAR['TIMEKPRSHARED'], 'padlock-red.png')
        iconyes = Gtk.STOCK_YES
        iconno = Gtk.STOCK_NO
        iconsize = Gtk.IconSize.BUTTON
        #limitSpins status is already set, so we can use it
        #self.spinlimitvalue = self.builder.get_object("limitSpins" + strftime('%w')).get_value()
        if not isuserlimitedtoday(self.user) and not uislocked:
            self.allDayLoginImage.set_from_stock(iconyes, iconsize)
        else:
            self.allDayLoginImage.set_from_stock(iconno, iconsize)

        if self.limitCheck.get_active():
            self.limitsEnabledImage.set_from_file(lockred)
        else:
            self.limitsEnabledImage.set_from_file(lockgreen)

        if self.boundariesCheck.get_active():
            self.boundariesEnabledImage.set_from_file(lockred)
        else:
            self.boundariesEnabledImage.set_from_file(lockgreen)

        if uislocked:
            self.accountLockedImage.set_from_file(lockred)
        else:
            self.accountLockedImage.set_from_file(lockgreen)

        index = int(strftime("%w"))
        try:
            limit = int(self.limits[index])
        except IndexError:
            limit = 86400 # =60*60*24 (seconds in one day)

        timefile = join(VAR['TIMEKPRWORK'], self.user + '.time')
        used = 0
        if isfile(timefile) and fromtoday(timefile):
            t = open(timefile)
            used = int(t.readline())
            t.close()
        left = limit - used
        m, s = divmod(left, 60)
        self.timeLeftLabel.set_label(ngettext('%(min)s minute', '%(min)s minutes', abs(m)) % {'min': m})

    def set_button_states(self, user_is_locked):
        if user_is_locked:
            self.lockUnlockLabel.set_label(_('Unlock account'))
        else:
            self.lockUnlockLabel.set_label(_('Lock account'))

        if self.limitCheck.get_active():
            timefile = join(VAR['TIMEKPRWORK'], self.user + '.time')
            if isfile(timefile):
                self.resetTimeButton.set_sensitive(True)
            else:
                self.resetTimeButton.set_sensitive(False)
            #Reward button should add time even if .time is not there?
            self.rewardButton.set_sensitive(True)
            self.rewardSpin.set_sensitive(True)
            self.rewardLabel.set_sensitive(True)
        else:
            self.resetTimeButton.set_sensitive(False)
            self.rewardButton.set_sensitive(False)
            self.rewardSpin.set_sensitive(False)
            self.rewardLabel.set_sensitive(False)

        if self.boundariesCheck.get_active():
            index = int(strftime("%w"))
            wfrom = self.fromtolimits[0]
            wto = self.fromtolimits[1]
            if wfrom[index] != '0' or wto[index] != '24':
                self.extendLimitsButton.set_sensitive(True)
            else:
                self.extendLimitsButton.set_sensitive(False)
        else:
            self.extendLimitsButton.set_sensitive(False)

    def on_userSelectCombo_toggled(self, widget):
        self.user = self.userSelectCombo.get_active_text()
        user_is_locked = isuserlocked(self.user)
        self.fromtolimits = getuserlimits(self.user)
        self.read_boundaries()
        self.read_limits()
        self.userStatusLabel.set_label(_('Status for') + ' ' + self.user + '')
        self.update_status_icons(user_is_locked)
        self.set_button_states(user_is_locked)

    def read_settings_nolimits(self):
        user_is_locked = isuserlocked(self.user)
        self.update_status_icons(user_is_locked)
        self.set_button_states(user_is_locked)

    def on_boundariesCheck_toggled(self, widget):
        if self.boundariesCheck.get_active():
            self.fromSpins[0].set_sensitive(True)
            self.toSpins[0].set_sensitive(True)
            self.singleBoundariesCheck.set_sensitive(True)
            self.toLabel.set_sensitive(True)
            self.fromLabel.set_sensitive(True)
            self.boundariesLabels[0].set_sensitive(True)
        else:
            self.fromSpins[0].set_sensitive(False)
            self.toSpins[0].set_sensitive(False)
            self.singleBoundariesCheck.set_sensitive(False)
            self.toLabel.set_sensitive(False)
            self.fromLabel.set_sensitive(False)
            self.boundariesLabels[0].set_sensitive(False)
        self.on_singleBoundariesCheck_toggled(self)

    def on_singleBoundariesCheck_toggled(self, widget):
        if self.singleBoundariesCheck.get_active() and self.boundariesCheck.get_active():
            for i in range(1, 7):
                self.fromSpins[i].set_sensitive(True)
                self.toSpins[i].set_sensitive(True)
                self.boundariesLabels[i].set_sensitive(True)
            self.boundariesLabels[0].set_text(" " + _("Sun") + " ")
        else:
            for i in range(1, 7):
                self.fromSpins[i].set_sensitive(False)
                self.toSpins[i].set_sensitive(False)
                self.boundariesLabels[i].set_sensitive(False)
            self.boundariesLabels[0].set_text(_("Every day"))

    def on_limitCheck_toggled(self, widget):
        if self.limitCheck.get_active():
            self.limitSpins[0].set_sensitive(True)
            self.singleLimitsCheck.set_sensitive(True)
            self.minutesLabel.set_sensitive(True)
            self.limitLabels[0].set_sensitive(True)
        else:
            self.limitSpins[0].set_sensitive(False)
            self.singleLimitsCheck.set_sensitive(False)
            self.minutesLabel.set_sensitive(False)
            self.limitLabels[0].set_sensitive(False)
        self.on_singleLimitsCheck_toggled(self)

    def on_singleLimitsCheck_toggled(self, widget):
        if self.singleLimitsCheck.get_active() and self.limitCheck.get_active():
            for i in range(1, 7):
                self.limitLabels[i].set_sensitive(True)
                self.limitSpins[i].set_sensitive(True)
            self.limitLabels[0].set_text(" " + _("Sun") + " ")
        else:
            for i in range(1, 7):
                self.limitLabels[i].set_sensitive(False)
                self.limitSpins[i].set_sensitive(False)
            self.limitLabels[0].set_text(_("Every day"))

    def on_applyButton_clicked(self, widget):
        space = " "
        limit = "limit=( 86400 86400 86400 86400 86400 86400 86400 )"
        #timekprpam.py adduserlimits() uses lists with numbers as strings
        bFrom = ['0'] * 7
        bTo = ['24'] * 7

        if self.limitCheck.get_active():
            if self.singleLimitsCheck.get_active():
                limit = "limit=("
                for i in range(7):
                    limit = limit + space + str(self.limitSpins[i].get_value_as_int() * 60)
                limit = limit + space + ")"
            else:
                limit = "limit=("
                for i in range(7):
                    limit = limit + space + str(self.limitSpins[0].get_value_as_int() * 60)
                limit = limit + space + ")"
        if self.boundariesCheck.get_active():
            if self.singleBoundariesCheck.get_active():
                bFrom = []
                bTo = []
                for i in range(7):
                    bFrom.append(str(self.fromSpins[i].get_value_as_int()))
                    bTo.append(str(self.toSpins[i].get_value_as_int()))
            else:
                bFrom = []
                bTo = []
                for i in range(7):
                    bFrom.append(str(self.fromSpins[0].get_value_as_int()))
                    bTo.append(str(self.toSpins[0].get_value_as_int()))
        configFile = join(VAR['TIMEKPRDIR'], self.user)
        if self.limitCheck.get_active():
            fH = open(configFile, 'w')
            fH.write(limit + "\n")
            fH.close()
        else:
            rm(configFile)

        #No need to check if boundaries are active or not, apply the default or custom limits
        #Remove old user limits (boundaries)
        rb = removeuserlimits(self.user)
        #Add new limits (boundaries)
        ab = adduserlimits(self.user, bFrom, bTo)

        statusmsg = _("Applied limit changes for account %s") % self.user
        self.set_status_message(statusmsg)
        self.on_userSelectCombo_toggled(self)

if __name__ == "__main__":
    init_locale()
    check_if_admin()
    create_dirs()
    timekprGUI()
    Gtk.main()


from django.db import models

class Artist(models.Model):
    name = models.CharField(max_length=80, unique=True)

class Album(models.Model):
    name = models.CharField(max_length=100)
    artist = models.ForeignKey(
        Artist, related_name='albums', on_delete=models.PROTECT)

class Song(models.Model):
    order = models.IntegerField()
    name = models.CharField(max_length=100)
    duration = models.IntegerField()
    album = models.ForeignKey(
        Album, related_name='songs', on_delete=models.PROTECT)

    class Meta:
        ordering = ['order']

    @property
    def artist(self):
        return self.album.artist


import mmap
import os.path
import sys

import ugee_fw_tools.key as key
import ugee_fw_tools.sm4 as sm4

__all__ = ('main',)

def get_key(directory='.'):
    with open(os.path.join(directory, 'UgeeBootLoader.exe'), 'rb') as exefile, \
            mmap.mmap(exefile.fileno(), 0, access=mmap.ACCESS_READ) as mapping:
        return key.extract_key(mapping)

def transcrypt_file(file_path, output_path, sm4_key, decrypt=False):
    with open(file_path, 'rb') as infile, open(output_path, 'wb') as outfile:
        sm4.sm4_transcrypt(infile, sm4_key, decrypt, output_file=outfile)

def decode(directory='.', info=False, firmware=False):
    if not firmware and not info:
        return

    sm4_key = get_key(directory)
    if not sm4_key:
        raise RuntimeError('Failed extracting key from updater')

    if info:
        transcrypt_file(
            os.path.join(directory, 'Bootloader-tool.enc'),
            os.path.join(directory, 'Bootloader-tool.bin'),
            sm4_key,
            True
        )

    if firmware:
        with open(os.path.join(directory, 'Bootloader-tool.bin'), 'rb') as \
                infofile:
            infofile.seek(10)
            filename = infofile.read()
        filename = filename[:filename.find(b'\0')]
        filename = filename.decode()
        transcrypt_file(
            os.path.join(directory, 'bin', filename),
            os.path.join(directory, 'bin', filename.replace('enc', '')),
            sm4_key,
            True
        )

def encode(directory='.', info=False, firmware=False):
    if not firmware and not info:
        return

    sm4_key = get_key(directory)
    if not sm4_key:
        raise RuntimeError('Failed extracting key from updater')

    if info:
        transcrypt_file(
            os.path.join(directory, 'Bootloader-tool.bin'),
            os.path.join(directory, 'Bootloader-tool.enc'),
            sm4_key
        )

    if firmware:
        with open(os.path.join(directory, 'Bootloader-tool.bin'), 'rb') as \
                infofile:
            infofile.seek(10)
            filename = infofile.read()
        filename = filename[:filename.find(b'\0')]
        filename = filename.decode()
        transcrypt_file(
            os.path.join(directory, 'bin', filename.replace('enc', '')),
            os.path.join(directory, 'bin', filename),
            sm4_key
        )

def main(argv):
    if len(argv) != 2:
        print('Need encode or decode as the only parameter')
        return 1
    if argv[1] == 'decode':
        decode(info=True, firmware=True)
    elif argv[1] == 'encode':
        encode(info=True, firmware=True)
    else:
        print('Invalid verb: ' + argv[1], file=sys.stderr)
        return 1
    return 0

if __name__ == '__main__':
    raise SystemExit(main(sys.argv) or 0)


from cmath import exp
from textattack.loggers.attack_log_manager import *
from textattack.loggers.weights_and_biases_logger import *
from textattack.shared.utils import LazyLoader, html_table_from_rows

'''
import wandb
def wandb_log_summary_rows(self, rows, title, window_id):
    table = wandb.Table(columns=["Attack Results", "score"])
    for row in rows:
        if isinstance(row[1], str):
            try:
                row[1] = row[1].replace("%", "")
                row[1] = float(row[1])
            except ValueError:
                raise ValueError(
                    f'Unable to convert row value "{row[1]}" for Attack Result "{row[0]}" into float'
                )
        print('row', row)
        print('*row', *row)
        table.add_data(*row)
        metric_name, metric_score = row
        wandb.run.summary[metric_name] = metric_score
    wandb.log({"attack_params": table})
'''
def get_log_summary(self):
    total_attacks = len(self.results)
    if total_attacks == 0:
        return

    # Default metrics - calculated on every attack
    attack_success_stats = AttackSuccessRate().calculate(self.results)
    words_perturbed_stats = WordsPerturbed().calculate(self.results)
    attack_query_stats = AttackQueries().calculate(self.results)

    # @TODO generate this table based on user input - each column in specific class
    # Example to demonstrate:
    # summary_table_rows = attack_success_stats.display_row() + words_perturbed_stats.display_row() + ...
    summary_table_rows = [
        [
            "Number of successful attacks:",
            attack_success_stats["successful_attacks"],
        ],
        ["Number of failed attacks:", attack_success_stats["failed_attacks"]],
        ["Number of skipped attacks:", attack_success_stats["skipped_attacks"]],
        [
            "Original accuracy:",
            str(attack_success_stats["original_accuracy"]) + "%",
        ],
        [
            "Accuracy under attack:",
            str(attack_success_stats["attack_accuracy_perc"]) + "%",
        ],
        [
            "Attack success rate:",
            str(attack_success_stats["attack_success_rate"]) + "%",
        ],
        [
            "Average perturbed word %:",
            str(words_perturbed_stats["avg_word_perturbed_perc"]) + "%",
        ],
        [
            "Average num. words per input:",
            words_perturbed_stats["avg_word_perturbed"],
        ],
    ]

    summary_table_rows.append(
        ["Avg num queries:", attack_query_stats["avg_num_queries"]]
    )

    if self.enable_advance_metrics:
        perplexity_stats = Perplexity().calculate(self.results)
        use_stats = USEMetric().calculate(self.results)

        summary_table_rows.append(
            [
                "Average Original Perplexity:",
                perplexity_stats["avg_original_perplexity"],
            ]
        )

        summary_table_rows.append(
            [
                "Average Attack Perplexity:",
                perplexity_stats["avg_attack_perplexity"],
            ]
        )
        summary_table_rows.append(
            ["Average Attack USE Score:", use_stats["avg_attack_use_score"]]
        )

    self.log_summary_rows(
        summary_table_rows, "Attack Results", "attack_results_summary"
    )
    # Show histogram of words changed.
    numbins = max(words_perturbed_stats["max_words_changed"], 10)
    for logger in self.loggers:
        logger.log_hist(
            words_perturbed_stats["num_words_changed_until_success"][:numbins],
            numbins=numbins,
            title="Num Words Perturbed",
            window_id="num_words_perturbed",
        )
    process_result = []
    for items in summary_table_rows:
        title = items[0].replace(':','')
        score = 0
        if isinstance(items[1], str):
            if '%' in items[1]:
                score_str = items[1].replace('%','')
                try:
                    score = float(score_str)/100
                except:
                    score = 0
                    print('nan error', score_str)
        else:
            score = float(items[1])
        process_result.append([title, score])

    return summary_table_rows, process_result


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

class MyLinkedList:

    def __init__(self):
        self._head = Node(0)
        self._count = 0

    def get(self, index: int) -> int:
        if 0 <= index < self._count:
            cur = self._head
            for _ in range(index+1):
                cur = cur.next
            return cur.val
        else:
            return -1

    def addAtHead(self, val: int) -> None:
        self.addAtIndex(0, val)

    def addAtTail(self, val: int) -> None:
        self.addAtIndex(self._count, val)

    def addAtIndex(self, index: int, val: int) -> None:
        if index < 0:
            index = 0
        elif index > self._count:
            return
        self._count += 1
        prev, curr = None, self._head
        for _ in range(index+1):
            prev, curr = curr, curr.next
        add = Node(val)
        prev.next, add.next = add, curr

    def deleteAtIndex(self, index: int) -> None:
        if 0 <= index < self._count:
            self._count -= 1
            prev, curr = None, self._head
            for _ in range(index+1):
                prev, curr = curr, curr.next
            prev.next = curr.next

# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)


from keras.models import Sequential
from keras.layers import LSTM, Dense, Embedding, SpatialDropout1D

class LSTMConfig:

    def __init__(self,
                 batch_size=32,
                 embedding_size=50,
                 num_words=2000,
                 lstm_units=64,
                 num_classes=3,
                 num_epochs=10):

        self.batch_size = batch_size
        self.embedding_size = embedding_size
        self.num_words = num_words
        self.lstm_units=lstm_units
        self.num_classes = num_classes
        self.num_epochs = num_epochs

    def __str__(self):
        status = ''
        status += 'batch size: {}\n'.format(self.batch_size)
        status += 'embedding size: {}\n'.format(self.embedding_size)
        status += 'num words: {}\n'.format(self.num_words)
        status += 'lstm units: {}\n'.format(self.lstm_units)
        status += 'num classes: {}\n'.format(self.num_classes)
        status += 'num epochs: {}\n'.format(self.num_epochs)

        return status

class Model:

    def __init__(self, lstm_config):
        self.lstm_config = lstm_config

    def build_model(self):
        raise NotImplementedError

    def fit(self, train_data, val_data=None):
        train_x = train_data[0]
        train_y = train_data[1]

        validation_split = 0 if val_data else 0.2

        return self.model.fit(
             x=train_x,
             y=train_y,
             epochs=self.lstm_config.epochs,
             verbose=2,
             validation_split=validation_split,
             validation_data=val_data)

    def evaluate(self, data):
        data_x = data[0]
        data_y = data[1]

        loss, acc = self.model.evaluate(
            x=data_x,
            y=data_y,
            verbose=2,
            batch_size=self.lstm_config.batch_size)

        return loss, acc

    def predict(self, data):
        return self.model.predict(data, batch_size=self.lstm_config.batch_size, verbose=2)


# 给定一个二叉树的 根节点 root，请找出该二叉树的 最底层 最左边 节点的值。
#
#  假设二叉树中至少有一个节点。
#
#
#
#  示例 1:
#
#
#
#
# 输入: root = [2,1,3]
# 输出: 1
#
#
#  示例 2:
#
#
#
#
# 输入: [1,2,3,4,null,5,6,null,null,7]
# 输出: 7
#
#
#
#
#  提示:
#
#
#  二叉树的节点个数的范围是 [1,104]
#  -231 <= Node.val <= 231 - 1
#
#  Related Topics 树 深度优先搜索 广度优先搜索 二叉树
#  👍 197 👎 0

# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
import collections

class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution(object):
    def findBottomLeftValue(self, root):
        """
        :type root: TreeNode
        :rtype: int
        """
        if not root:
            return
        res = 0
        max_deep = -1

        def dfs(root, deep):
            nonlocal res, max_deep

            if not root:
                return
            if not root.left and not root.right:
                #用第一次deep的更新判断是不是一层的最左元素
                if deep > max_deep:
                    max_deep = deep
                    res = root.val
            dfs(root.left, deep + 1)
            dfs(root.right, deep + 1)

        dfs(root, 0)

        return res

# leetcode submit region end(Prohibit modification and deletion)
if __name__ == '__main__':
    a = TreeNode(1)
    b = TreeNode(2)
    c = TreeNode(3)
    a.left=b
    a.right=c
    res = Solution().findBottomLeftValue(a)
    print(res)


from collections import deque

def bfs(maze, visited):
    di = [-1, 0, 1, 0]
    dj = [0, 1, 0, -1]
    q = deque()

    start = (0, 0, 1)
    q.append(start)
    visited[0][0] = True

    while(q):
        ti = q[0][0]
        tj = q[0][1]
        tdepth = q[0][2]
        if(ti == n-1 and tj == m-1):
            print(tdepth)
            break
        q.popleft()

        for k in range(4):
            ki = ti + di[k]
            kj = tj + dj[k]
            kdepth = tdepth + 1
            if(ki < 0 or ki >= n or kj < 0 or kj >= m or maze[ki][kj] == 0 or visited[ki][kj]):
                continue

            tmplist = []
            tmplist.append(ki)
            tmplist.append(kj)
            tmplist.append(kdepth)
            q.append(tuple(tmplist))
            visited[ki][kj] = True

n, m = map(int, input().split())
maze = [list(map(int, input())) for _ in range(n)]
visited = [[False]*m for _ in range(n)]
bfs(maze, visited)


"""
ws2812.py - easy to use library for PYBStick-RP2040.

* Author(s): Meurisse D. from MCHobby (shop.mchobby.be).

See project source @ https://github.com/mchobby/pyboard-driver/tree/master/PYBStick-RP2040

"""
import array
from machine import Pin
import rp2
import time

# WS2812 default configuration.
NUM_LEDS = 8 # Nombre de LEDs
PIN_NUM = 11 # Broche de sortie
BRIGHTNESS = 0.2 # Luminosité (0 à 1, 0.2 est déjà très lumineux)

######################## NEOPIXEL UTILITY ######################################
@rp2.asm_pio(sideset_init=rp2.PIO.OUT_LOW, out_shiftdir=rp2.PIO.SHIFT_LEFT, autopull=True, pull_thresh=24)
def _ws2812():
	T1 = 2
	T2 = 5
	T3 = 3
	wrap_target()
	label("bitloop")
	out(x, 1)               .side(0)    [T3 - 1]
	jmp(not_x, "do_zero")   .side(1)    [T1 - 1]
	jmp("bitloop")          .side(1)    [T2 - 1]
	label("do_zero")
	nop()                   .side(0)    [T2 - 1]
	wrap()

BLACK = (0, 0, 0)
RED = (255, 0, 0)
YELLOW = (255, 150, 0)
GREEN = (0, 255, 0)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
WHITE = (255, 255, 255)
COLORS = (BLACK, RED, YELLOW, GREEN, CYAN, BLUE, PURPLE, WHITE)

class WS2812():

	def __init__( self, pin_num = PIN_NUM, num_leds=NUM_LEDS, brightness=BRIGHTNESS ):
		self.pin_num = pin_num
		self.num_leds = num_leds
		self.brightness = brightness
		# Create the StateMachine with the ws2812 program, outputting on pin
		self.sm = rp2.StateMachine(0, _ws2812, freq=8_000_000, sideset_base=Pin(self.pin_num))
		# Start the StateMachine, it will wait for data on its FIFO.
		self.sm.active(1)
		# Display a pattern on the LEDs via an array of LED RGB values.
		self.ar = array.array("I", [0 for _ in range(self.num_leds)])

	def show( self ):
		""" Should also receive a data parameter (list of color tuples) to be fully compatible with esp8266-upy/neopixel/ """
		dimmer_ar = array.array("I", [0 for _ in range(self.num_leds)])
		for i,c in enumerate(self.ar):
			r = int(((c >> 8) & 0xFF) * self.brightness)
			g = int(((c >> 16) & 0xFF) * self.brightness)
			b = int((c & 0xFF) * self.brightness)
			dimmer_ar[i] = (g<<16) + (r<<8) + b
		self.sm.put(dimmer_ar, 8)
		time.sleep_ms(10)

	write = show

	def set(self, index, color):
		""" Assigne une couleur (r,g,b) à un pixel numéroté de 0 à N-1 """
		self.ar[index] = (color[1]<<16) + (color[0]<<8) + color[2]

	def __setitem__( self, index, color ):
		self.set( index, color )

	def fill( self, color):
		""" Remplit le ruban avec une couleur donnée """
		for i in range(self.num_leds):
			self.set(i, color)

	def clear( self ):
		self.fill( BLACK )
		self.show()

	@property
	def pixels( self ):
		return self.ar

	@property
	def count( self ):
		return self.num_leds

	n = count

##########################################################################


from localsocial.service.picture import filesystem_storage_service

class UserSearchEntry(object):
	def __init__(self, user_id, name, portrait, is_following, friend_status):
		self.user_id = user_id
		self.name = name
		self.portrait = portrait
		self.is_following = is_following
		self.friend_status = friend_status

	def to_json_dict(self):
		json_dict = {
			"user_id" : self.user_id,
			"name" : self.name,
			"portrait_src" : filesystem_storage_service.get_cropped_src(self.portrait, self.user_id),
			"is_following" : self.is_following,
			"friend_status" : self.friend_status
		}
		return json_dict


from context import src
import numpy as np
from scipy import spatial, optimize
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from src.polyhedra import AffForm, Polyhedron, Region
from src.system import Piece
from src.learner import Learner

# vars: (x, y, t)

vmax = 5
vmin = -5
T = vmax - vmin

A0 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 0]])
A1 = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
xgy = [AffForm(np.array([-1, +1, 0]), 1)]
ygx = [AffForm(np.array([+1, -1, 0]), 1)]
xey = [
    AffForm(np.array([+1, -1, 0]), 0),
    AffForm(np.array([-1, +1, 0]), 0),
]
tlT = [
    AffForm(np.array([0, 0, -1]), 0),
    AffForm(np.array([0, 0, +1]), -(T - 1)),
]
teT = [
    AffForm(np.array([0, 0, -1]), +T),
    AffForm(np.array([0, 0, +1]), -T),
]
pieces = []

# x > y, t < T
b = np.array([-1, 0, 1])
piece = Piece(A1, b, Region([Polyhedron(xgy + tlT)]))
pieces.append(piece)

# y > x, t < T
b = np.array([0, -1, 1])
piece = Piece(A1, b, Region([Polyhedron(ygx + tlT)]))
pieces.append(piece)

# x = y, t < T
b = np.array([0, 0, 1])
piece = Piece(A1, b, Region([Polyhedron(xey + tlT)]))
pieces.append(piece)

# x > y, t = T
b = np.array([-1, 0, 0])
piece = Piece(A1, b, Region([Polyhedron(xgy + teT)]))
pieces.append(piece)

# y > x, t = T
b = np.array([0, -1, 0])
piece = Piece(A1, b, Region([Polyhedron(ygx + teT)]))
pieces.append(piece)

# x = y, t = T
b = np.array([0, 0, 0])
piece = Piece(A1, b, Region([Polyhedron(xey + teT)]))
pieces.append(piece)

tmax = 2*T
dv = vmax - vmin
fig = plt.figure()
ax = plt.axes(xlim=(-1, tmax + 2), ylim=(vmin - 0.01*dv, vmax + 0.01*dv))
x = np.array([vmax - 1, vmin + 1, 0])

for t in range(tmax):
    s = '.' if x[2] == T else 'x'
    ax.plot(t, x[0], ls=None, marker=s, ms=10, c='red')
    ax.plot(t, x[1], ls=None, marker=s, ms=10, c='blue')
    flag = False
    for piece in pieces:
        if piece.rdom.eval(x) <= 0:
            flag = True
            x = piece.A @ x + piece.b
            break
    assert flag

# init
rinit = Region([
    Polyhedron([
        AffForm(np.array([-1, 0, 0]), +vmin),
        AffForm(np.array([+1, 0, 0]), -vmax),
        AffForm(np.array([0, -1, 0]), +vmin),
        AffForm(np.array([0, +1, 0]), -vmax),
        AffForm(np.array([0, 0, -1]), +0),
        AffForm(np.array([0, 0, +1]), -0),
    ])
])
# safe
runsafe = Region([
    Polyhedron([AffForm(np.array([+1, 0, 0]), -vmin)]),
    Polyhedron([AffForm(np.array([-1, 0, 0]), +vmax)]),
    Polyhedron([AffForm(np.array([0, +1, 0]), -vmin)]),
    Polyhedron([AffForm(np.array([0, -1, 0]), +vmax)]),
    Polyhedron([AffForm(np.array([0, 0, +1]), 0)]),
    Polyhedron([AffForm(np.array([0, 0, -1]), T)]),
    Polyhedron([
        AffForm(np.array([0, 0, -1]), T - 1),
        AffForm(np.array([+1, -1, 0]), 0),
    ]),
    Polyhedron([
        AffForm(np.array([0, 0, -1]), T - 1),
        AffForm(np.array([-1, +1, 0]), 0),
    ])
])

xmax = 2*max(abs(vmin), abs(vmax), abs(T)) + 2
lear = Learner(3, 7, True, None, 3, 200, True, xmax,
               pieces, rinit, runsafe)

pinv = lear.find_invariant(1000)
print(pinv)

fig = plt.figure()
ax = plt.axes(projection='3d',
              xlim=(vmin - 1, vmax + 1),
              ylim=(vmin - 1, vmax + 1),
              zlim=(-1, T + 1))

q = 0
afs = [af for af in pinv.afs if np.linalg.norm(af.a) > 0.1]
A = np.array([list(af.a) + [1.0] for af in afs])
b = np.array([-af.beta for af in afs])
c = np.array([0, 0, 0, -1])
res = optimize.linprog(c, A_ub=A, b_ub=b, bounds=(None, None))
assert res['success'] and res['status'] == 0 and res['fun'] < 0
A[:, -1] = -b
hs = spatial.HalfspaceIntersection(A, res['x'][0:3])
points = list(hs.intersections)
ch = spatial.ConvexHull(points)
verts_list = [[ch.points[i, :] for i in simplex] for simplex in ch.simplices]
polylist = Poly3DCollection(verts_list, facecolor='red', alpha=0.7,
                            ec='black', lw=1)
ax.add_collection3d(polylist)

plt.show()


from Steuern import Steuern
from Kontenerstellung import Konto

class Wechsel(Konto):

    def Forderung(self, Gesamtbrutto, Verzugszinsertrag, Diskontzinsaufwand, SpesendesGeldverkehrs):
        # Warenverkauf an den Kunden Müller
        Gesnet = Steuern.getbefore20(Gesamtbrutto)
        Ustges = Gesamtbrutto - Gesnet
        print("2 KFD ", Gesamtbrutto, "    4 Erloese ", Gesnet)
        print("                             3 Ust", Ustges, '\n')

        Erloese.einzahlen(Gesnet)
        Ust.einzahlen(Ustges)
        Erloese.buchen(KDF, Gesnet)
        Ust.buchen(KDF, Ustges)

        # Zahlung der AR mit Wechsel
        print("2 Wechselforderung", Gesamtbrutto + Verzugszinsertrag, "2 KDF", Gesamtbrutto)
        print("                                             8 Verzugszinsertrag", Verzugszinsertrag, '\n')

        Ve.einzahlen(Verzugszinsertrag)
        KDF.buchen(Wf, Gesamtbrutto)
        Ve.buchen(Wf, Verzugszinsertrag)

        # Einreichung des Wechsels bei der Bank
        print("2 schwebende Geldbewegung", Gesamtbrutto, "2 Wechselforderung", Gesamtbrutto + Verzugszinsertrag, '\n')
        Wf.buchen(schwebendeGeld, Gesamtbrutto + Verzugszinsertrag)

        # Der Wechsels wird auf dem Konto gutgeschrieben
        print("2 Bank", Gesamtbrutto + Verzugszinsertrag - Diskontzinsaufwand - SpesendesGeldverkehrs, "2 schwebende Geldbewegung", Gesamtbrutto + Verzugszinsertrag)
        print("8 Diskontzinsaufwand", Diskontzinsaufwand)
        print("7 SpesendesGeldverkehrs", SpesendesGeldverkehrs, '\n')

        schwebendeGeld.buchen(Bank, Gesamtbrutto + Verzugszinsertrag - Diskontzinsaufwand - SpesendesGeldverkehrs)
        schwebendeGeld.buchen(Daufwand, Diskontzinsaufwand)
        schwebendeGeld.buchen(SpesenGeldverkehrs, SpesendesGeldverkehrs)

        Ustspe = Steuern.getafter20(SpesendesGeldverkehrs)
        Dif = Ustspe - SpesendesGeldverkehrs

        print("2 KDF ", Diskontzinsaufwand + SpesendesGeldverkehrs + Dif, "    8 Diskontzinsaufwand", Diskontzinsaufwand)
        print("                            4 weiterverrechneteSpesen", SpesendesGeldverkehrs)
        print("                            3 Ust", Dif, '\n')

        wSpesen.einzahlen(SpesendesGeldverkehrs)
        Ust.einzahlen(Dif)

        Daufwand.buchen(KDF, Diskontzinsaufwand)
        wSpesen.buchen(KDF, SpesendesGeldverkehrs)
        Ust.buchen(KDF, Dif)

        # Verrechnung der Diskontspesen
        print("2 Bank", Gesamtbrutto + Verzugszinsertrag, "2 KDF", Gesamtbrutto, '\n')
        KDF.buchen(Bank, Diskontzinsaufwand + SpesendesGeldverkehrs + Dif)

        # Beispiel: Scheck.gegeben(3600)

    def Schuld(self, Gesamtbrutto):
        # Wareneinkauf
        Gesnet = Steuern.getbefore20(Gesamtbrutto)
        Vstges = Gesamtbrutto - Gesnet
        print("5 HW-Verbrauch", Gesnet, "3 LVB ", Gesamtbrutto)
        print("2 Vst", Vstges, '\n')

        # Zahlung der ER mit Wechsel
        print("3 LVB", Gesamtbrutto, "3 Schuldwechsel ", Gesamtbrutto, '\n')

        # Einreichung des Wechsels bei der Bank
        print("3 Schuldwechsel ", Gesamtbrutto, "2 Bank", Gesamtbrutto, '\n')

        Bank.einzahlen(Gesamtbrutto)
        Bank.buchen(Sw, Gesamtbrutto)

        Sw.buchen(LVB, Gesamtbrutto)

        LVB.buchen(HWVerbrauch, Gesnet)
        LVB.buchen(Vst, Vstges)

        # Beispiel: Scheck.erhalten(7200)

Wf = Konto("2444 Wechselforderung")
Sw = Konto("3444 Schuldwechsel")
wSpesen = Konto("4444 weiterverrechneteSpesen")
Ve = Konto("8444 Verzugszinsertrag")
Daufwand = Konto("8333 Diskontzinsaufwand")
SpesenGeldverkehrs = Konto("7444 SpesendesGeldverkehrs")
schwebendeGeld = Konto("2230 schwebendeGeldbewegung")

Maschinen = Konto("0100 Maschinen")
Bank = Konto("2000 Bank")
Ust = Konto("3500 Ust")
Vst = Konto("2500 Vst")
KDF = Konto("210 KDF")
LVB = Konto("310 LVB")
HWVerbrauch = Konto("5700 HWVerbrauch")
Erloese = Konto("4000 Erloese")

wech = Wechsel.Forderung(KDF, 36000, 1400, 620, 100)

# Forderung

print(Bank.alles())
print(Vst.alles())
print(LVB.alles())
print(HWVerbrauch.alles())
print(Daufwand.alles())
print(Wf.alles())
print(Erloese.alles())
print(schwebendeGeld.alles())
print(SpesenGeldverkehrs.alles())
print(Ve.alles())
print(Ust.alles())
print(KDF.alles())
# Schuld

# print(Bank.alles())
# print(Vst.alles())
# print(LVB.alles())
# print(HWVerbrauch.alles())

# wech = Wechsel.Forderung(KDF, 54000)


import os

path = "."
# we shall store all the file names in this list
filelist = []

def remove_prefix(text, prefix):
    if text.endswith(prefix):
        return text[:len(prefix) + 1]
    return text  # or whatever

for root, dirs, files in os.walk(path):
    for file in files:
        # append the file name to the list
        if file.endswith(".c"):
            filelist.append(os.path.join(root, file))

# print all the file names
for name in filelist:
    name = name[2:].replace("\\", "/")
    # print(name)
    cmd = name.replace('.c', "") + "_windows" + '.exe'.replace("\\", "/")
    # print(cmd)
    os.system(f"gcc {name} -o {cmd}")
    # print(f"gcc {name} -o {cmd}")


with open("dzialki.txt", "r") as plik:
    dzialki = [i for i in plik]
liczba_dzialek = int((len(dzialki)+1)/31)

dzialki = [wiersz.split() for wiersz in dzialki]
dzialki = [dzialki[i:i+30] for i in range(0, len(dzialki) + 1, 31)]

dzialki_trawa = 0
for i in range(liczba_dzialek):
    if sum(["".join(dzialki[i][j]).count("*") for j in range(30)]) / 900 > 0.7:
        dzialki_trawa += 1
print(dzialki_trawa)

'''4.2'''
dzialkiR = [dz[::-1] for dz in dzialki]
dzialkiR = [[[wi[0][::-1]] for wi in dz] for dz in dzialkiR]

for nrD in range(liczba_dzialek):
    for nrDR in range(nrD+1, liczba_dzialek):
        if dzialki[nrD] == dzialkiR[nrDR]:
            print(nrD+1, nrDR+1)


import bpy

class Terreno():
    '''

        Autor: <nicolaspauer20@gmail.com>
        Fecha: 13/09/2023

        Crea terrenos de una ciudad sobre un plano
        en blender haciendo uso del modulo bpy.
    '''

    def __init__(self, name, x_axis, y_axis):

        self.nombre = name

        self.x = x_axis

        self.y = y_axis

    def crear(self):
        '''
            Crea un terreno sobre el piso
        '''
        # Creo objeto
        bpy.ops.mesh.primitive_cube_add()
        terreno = bpy.data.objects['Cube']
        terreno.name = self.nombre
        # lo pongo sobre el piso
        terreno.location = (self.x, self.y, 1)
        # le doy una altura moderada
        terreno.scale[2] = 0.15

if __name__ == '__main__':
  # Agrego piso
    bpy.ops.mesh.primitive_plane_add()
    piso = bpy.data.objects['Plane']
    piso.name = 'piso_de_ciudad'
  # Establezco posicion en la que ubicar el piso
    piso.location = (0, 0, 0)
  # Redimensiono ancho
    piso.scale[0] = 8
  # Redimensiono largo
    piso.scale[1] = 8
  # Creo cuadras y otros terrenos
    terreno_1 = Terreno('Plaza', 0, 0)

    terreno_2 = Terreno('Casa.001', 0, 3)

    terreno_3 = Terreno('Edificio.001', 3, 3)

    terreno_4 = Terreno('Cuadra_plaza', 0, 0)

    terreno_5 = Terreno('Cuadra_residencial', 0, 3)

    terreno_6 = Terreno('Cuadra_comercial', -3, 0)

    terrenos = [terreno_1, terreno_2, terreno_3, terreno_4, terreno_5, terreno_6]

    for terreno in terrenos:
      # Creo terrenos
      terreno.crear()


# coding: utf-8
import json
import logging
import boto3
import uuid
import os

# ログの設定
logger = logging.getLogger()
logger.setLevel(logging.INFO)

# DynamoDB
logger.info('DYNAMO_URL:' + str(os.environ.get('DYNAMO_URL')))
dynamodb = (lambda url:
    boto3.resource('dynamodb') if url is None
    else boto3.resource('dynamodb', endpoint_url=url)
)(os.environ.get('DYNAMO_URL'))

#dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:8000')
#dynamodb = boto3.resource('dynamodb')
persons_tbl = dynamodb.Table('persons')

def create_person(event, context):
    logger.info('context:' + str(context))
    logger.info('headers:' + str(event['headers']))
    logger.info('body:' + event['body'])

    body = json.loads(event['body'])

    id = str(uuid.uuid4())
    persons_tbl.put_item(
        Item = {
            'id': id,
            'name': body['name'],
            'age': body['age']
        }
    )

    response = {
        "statusCode": 200,
        "body": json.dumps({
            'id': id
        })
    }

    return response

def get_person(event, context):
    logger.info('event' + str(event['pathParameters']))

    id = event['pathParameters']['id']
    res = persons_tbl.get_item(Key={'id': id})
    logger.info(f'dynamodbres = {res}')
    person = res.get('Item')

    if person is None:
        return {
            "statusCode": 404,
            "body": json.dumps({
                'message': 'Not Found'
            })
        }
    else:
        return {
            "statusCode": 200,
            "body": json.dumps(person)
        }


import csv
import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
import forex_python
import numpy as np
from forex_python.converter import get_rate
from forex_python.bitcoin import BtcConverter

print("stocks")
style.use('ggplot')
start = dt.datetime(2000, 1, 1)
end = dt.datetime(2017, 12, 1)

df = web.DataReader('GOOGL', 'yahoo', start, end)
print(df.head(3))
print("\n")
print("forex")
t = dt.datetime(2001, 10, 18)
get_rate("USD", "EUR", t)
print("USD to EUR")
print(get_rate("USD", "EUR", t))
print("\n")

b = BtcConverter()
print("bitcoin")
print(b.get_latest_price('USD'))
print("USD\n")

#code starts now
print("code starts now\n")
with open("AllStocks1.csv", "r") as StocksFile:
	StocksFileReader = csv.reader(StocksFile)
	StocksList = []
	for row in StocksFileReader:
		if len (row) != 0:
			StocksList = StocksList + row
			#print(web.DataReader(row[0], 'yahoo', start, end))
			try:
				ddd = web.DataReader(row[0], 'yahoo', start, end)
				#print(ddd)
				thepath = 'C:\\Users\\Ryan\\Desktop\\rawstocks\\'
				ddd.to_csv(thepath + row[0] + '.csv', sep=',')
			except:
				print("error @ " + row[0])

print("end of python")


#
# @lc app=leetcode id=215 lang=python3
#
# [215] Kth Largest Element in an Array
#

from typing import List

# @lc code=start
class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        l, r, target = 0, len(nums)-1, len(nums)-k

        while l < r:
            mid = self.quickSelect(nums, l, r)
            if mid == target:
                return nums[mid]
            elif mid < target:
                l = mid + 1
            else:
                r = mid - 1

        return nums[l]

    def quickSelect(self, nums, l, r):
        i, j = l+1, r

        while True:
            while i < r and nums[i] <= nums[l]:
                i += 1
            while l < j and nums[j] >= nums[l]:
                j -= 1

            if i >= j:
                break

            nums[i], nums[j] = nums[j], nums[i]

        nums[l], nums[j] = nums[j], nums[l]

        return j

# @lc code=end


"""
AlexNet convolutional neural network example.

Original paper "ImageNet Classification with Deep Convolutional Neural Networks"
by A. Krizhevsky, I. Sutskever and G. Hinton, can be found here:
https://papers.nips.cc/paper/2012/file/c399862d3b9d6b76c8436e924a68c45b-Paper.pdf

The original network contained 8 layers, 5 convolutional and
3 fully connected.  The input is 150,528 dimensional, with
[253,440-186,624-64,896-64,896-43,264-4096-4096-1000] neurons in each
consecutive layer respectively.

In the original 2012 paper, the authors used two GTX 580s, which only
had 3Gb of memory each, hence the reason for using two.  This resulted in
having to construct two convolutional networks which made things
more complicated, but here we have no reason to do this, so we will
implement the same model on a single GPU.
"""
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms import ToTensor, Lambda
from torchvision import datasets
from configs import *

# use the gpu if it's available
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# some information
print(f"Torch version: {torch.__version__}")
print(f"Cuda available: {torch.cuda.is_available()}")
print("Device: {}".format(device))

class AlexNet(torch.nn.Module):
    """

        (a) The input tensor shape is 224x224x3
        (b) The first convolution layer consts of 96 kernels with
            a size of 11x11x3 and a stride of 4.
        (ba)    There is then a response-normalized and pooled
                transformation which occurs here
        (bb)    The pooling uses a 3x3 size with a stride of 2
                (see section 3.4 of the paper)
        (c) The second convolution layer is constructed from 256
            kernels with a size of 5x5x48
        (d) The third layer has 384 kernels of size 3x3x256.
        (e) The fourth layer also has 384 kernels with a size of 3x3x192.
        (f) The fifth convolution layer has 256 kernels with a size of
            3x3x192.
        (g) There are then 3 fully connected layers with sizes 4096,4096
            and 1000.

    """
    def __init__(self,
        configuration,
    ):
        super().__init__()
        # define the architecture
        self.input_channels = configuration.get('input_channels', 3)
        self.conv1_out      = configuration.get('conv1_out', 96)
        self.conv1_kernel   = configuration.get('conv1_kernel', 11)
        self.conv1_pooling  = configuration.get('conv1_pooling', True)

        self.conv2_out      = configuration.get('conv2_out', 256)
        self.conv2_kernel   = configuration.get('conv2_kernel', 5)
        self.conv2_pooling  = configuration.get('conv2_pooling', True)

        self.conv3_out      = configuration.get('conv3_out', 384)
        self.conv3_kernel   = configuration.get('conv3_kernel', 3)
        self.conv4_out      = configuration.get('conv4_out', 384)
        self.conv4_kernel   = configuration.get('conv4_kernel', 3)

        self.conv5_out      = configuration.get('conv5_out', 256)
        self.conv5_kernel   = configuration.get('conv5_kernel', 3)
        self.conv5_pooling  = configuration.get('conv5_pooling', True)

        self.full1_out      = configuration.get('full1_out', 4096)
        self.full2_out      = configuration.get('full2_out', 4096)
        self.out_channels   = configuration.get('out_channels', 1000)

        self.loc_resp_norm  = configuration.get('loc_resp_norm', True)
        self.pooling_kernel = configuration.get('pooling_kernel', 3)
        self.pooling_stride = configuration.get('pooling_stride', 2)

        # some necessary layers
        self.relu = nn.ReLU()
        self.max_pooling = nn.MaxPool2d(
            self.pooling_kernel,
            self.pooling_stride
        )
        self.softmax = nn.Softmax()
        self.flatten = nn.Flatten()

        # define the eight layers
        self.conv1_layer = nn.Conv2d(
            in_channels =   self.input_channels,
            out_channels=   self.conv1_out,
            kernel_size =   self.conv1_kernel,
            stride      =   4,
            padding     =   1
        )
        self.conv2_layer = nn.Conv2d(
            in_channels =   self.conv1_out,
            out_channels=   self.conv2_out,
            kernel_size =   self.conv2_kernel,
            stride      =   4,
            padding     =   1
        )
        self.conv3_layer = nn.Conv2d(
            in_channels =   self.conv2_out,
            out_channels=   self.conv3_out,
            kernel_size =   self.conv3_kernel,
            stride      =   4,
            padding     =   1
        )
        self.conv4_layer = nn.Conv2d(
            in_channels =   self.conv3_out,
            out_channels=   self.conv4_out,
            kernel_size =   self.conv4_kernel,
            stride      =   4,
            padding     =   1
        )
        self.conv5_layer = nn.Conv2d(
            in_channels =   self.conv4_out,
            out_channels=   self.conv5_out,
            kernel_size =   self.conv5_kernel,
            stride      =   4,
            padding     =   1
        )
        self.full1_layer = nn.Linear(
            in_features =   self.conv5_out,
            out_features=   self.full1_out
        )
        self.full2_layer = nn.Linear(
            in_features =   self.full1_out,
            out_features=   self.full2_out,
        )
        self.output_layer = nn.Linear(
            in_features =   self.full2_out,
            out_features=   self.out_channels,
        )

    def forward(self, x):
        x = x.to(device)
        # first convolution
        x = self.conv1_layer(x)
        x = self.relu(x)
        if self.conv1_pooling:
            x = self.max_pooling(x)
        # second convolution
        x = self.conv2_layer(x)
        x = self.relu(x)
        if self.conv2_pooling:
            x = self.max_pooling(x)
        # third convolution
        x = self.conv3_layer(x)
        x = self.relu(x)
        # fourth convolution
        x = self.conv4_layer(x)
        x = self.relu(x)
        # fifth convolution
        x = self.conv5_layer(x)
        if self.conv5_pooling:
            x = self.max_pooling(x)
        x = self.relu(x)
        # fully connected layers
        x = self.flatten(x)
        x = self.full1_layer(x)
        x = self.relu(x)
        x = self.full2_layer(x)
        x = self.relu(x)
        x = self.output_layer(x)
        x = self.softmax(x)
        return x

class Model:
    """
    """
    def __init__(self,
        configuration
    ):
        self.dataset = configuration.get("dataset", "cifar10")
        self.learning_rate = configuration.get("learning_rate", 1e-3)
        self.batch_size = configuration.get("batch_size", 128)
        self.alex_net = AlexNet(configuration).cuda()
        if(next(self.alex_net.parameters()).is_cuda):
            print("AlexNet is loaded on the GPU!")
        else:
            print("AlexNet is not loaded on the GPU.")
        self.loss_function = nn.CrossEntropyLoss()
        self.optimizer = optim.Adam(
            self.alex_net.parameters(),
            lr=self.learning_rate
        )
        if self.dataset == "cifar10":
            # create datasets
            self.training_data = datasets.CIFAR10(
                root="data",
                train=True,
                download=True,
                transform=ToTensor()
            )
            self.test_data = datasets.CIFAR10(
                root="data",
                train=False,
                download=True,
                transform=ToTensor()
            )
        else:
            # create datasets
            self.training_data = datasets.ImageNet(
                root="data",
                train=True,
                download=True,
                transform=ToTensor()
            )
            self.test_data = datasets.ImageNet(
                root="data",
                train=False,
                download=True,
                transform=ToTensor()
            )
        # create dataloaders
        self.train_dataloader = DataLoader(
            self.training_data,
            batch_size=self.batch_size
        )
        self.test_dataloader = DataLoader(
            self.test_data,
            batch_size=self.batch_size
        )

    def train(self,
        epochs: int
    ) -> None:
        size = len(self.train_dataloader.dataset)
        for epoch in range(epochs):
            for batch, (x,y) in enumerate(self.train_dataloader):
                prediction = self.alex_net(x.to(device))
                loss = self.loss_function(prediction, y.to(device))
                # backpropagation
                self.optimizer.zero_grad()
                loss.backward()
                self.optimizer.step()

                if batch % 100 == 0:
                    loss, current = loss.item(), batch * len(x)
                    print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

    def test(self):
        size = len(self.test_dataloader.dataset)
        num_batches = len(self.test_dataloader)
        test_loss, correct = 0, 0
        with torch.no_grad():
            for x, y in self.test_dataloader:
                prediction = self.alex_net(x.to(device))
                test_loss += self.loss_function(prediction, y.to(device)).item()
                correct += (prediction.argmax(1) == y.to(device)).type(torch.float).sum().item()
        test_loss /= num_batches
        correct /= size
        print(f"Test Error: \n Accuracy: {(100*correct):>0.1f}%, Avg loss: {test_loss:>8f} \n")

    def save(self,
        title:  str=''
    ) -> None:
        torch.save(
            self.alex_net.state_dict(),
            "models/{}.pth".format(title)
        )

    def load(self,
        title:  str=''
    ) -> None:
        self.alex_net.load_state_dict(torch.load("models/{}.pth".format(title)))

if __name__ == "__main__":

    alex_net = Model(cifar10_config)
    alex_net.train(100)
    alex_net.test()
    alex_net.save("my_alexnet")


import inspect
from typing import Dict, Union

import fiddle as fdl

def extract_hparams_from_config(config: fdl.Config) -> Dict[str, Union[str, Dict]]:
    """Extracts a dict with the configurations from a Fiddle config

    Parameters
    ----------
    config : fdl.Config
        A Fiddle config object

    Returns
    -------
    Dict[str, Union[str, Dict]]
        Dict hierarchy with the config defined args and also the default args
        from the configured callable (function or class constructor)
    """
    output_args = {}
    config_args = config.__arguments__
    for k, v in config_args.items():
        if isinstance(v, fdl.Config):
            output_args[k] = extract_hparams_from_config(v)

        else:
            output_args[k] = v

    callable_params = inspect.signature(config.__fn_or_cls__).parameters
    for k, v in callable_params.items():
        if k not in output_args and callable_params[k].default is not callable_params[k].empty:
            output_args[k] = callable_params[k].default
    return output_args


def caixinha_magica3(numero1, numero2):
    if numero2 <= numero1:
        return numero1 - numero2
    return 0

assert caixinha_magica3(20, 15) == 5
assert caixinha_magica3(20, 10) == 10
assert caixinha_magica3(10, 10) == 0
assert caixinha_magica3(10, 15) == 0
assert caixinha_magica3(30, 45) == 0

#### Aula 01/03/2023
# Conjuntos (set)

conjunto1 = set(range(1,15))
conjunto2 = set(range(10,20))
conjunto3 = set(range(14,25))

conjunto1.difference(conjunto2)
conjunto1.intersection(conjunto2)

# Remover elemento repetidos de uma lista
lista_repetida = list(range(1,10))
lista_repetida += list(range(1,10))
lista_repetida += list(range(1,15))

lista = list(set(lista_repetida))

# Dicionários
agenda = {}
type(agenda)
agenda['orlando'] = ['Eng. Sof1', 'Des. Web 2', 'Des. Web 3']
agenda['nilton'] = ['Algoritmo']
agenda['jose'] = '199999-9999'
agenda['maria'] = '1988888888'
agenda['joaquim'] = ('1988888888','Rua 10, 1')

# Fazer uso do dicionário
agenda['orlando'] # Retorna uma lista
agenda['Orlando'] # Retorna KeyError

try:
    agenda['Orlando']
except KeyError:
    print('Não Encontrado')

agenda.get('orlando','Não Encontrado')
agenda.get('Orlando','Não Encontrado')

for chave in agenda.keys():
    print('Chave =>' + chave)
    print(agenda[chave])


import os
from urllib.parse import urlparse

from click import echo
from ebooklib import epub
from requests import get
from click import echo

from .manifest import Manifest
from .const import DC_KEYS

class Binder:
    def __init__(self, config):
        self.config = config
        self.manifest = Manifest(config.files.manifest_file)

    def bind_book(self):
        book = epub.EpubBook()

        for (m, v) in self.config.metadata.items():
            m = m.lower()
            if m in DC_KEYS:
                if m == "identifier":
                    book.set_identifier(v)
                elif m == "title":
                    book.set_title(v)
                elif m == "language":
                    book.set_language(v)
                elif m == "author" or m == "creator":
                    book.add_author(v)
                else:
                    book.add_metadata("DC", m, str(v))
            else:
                book.add_metadata(None, "meta", "", {"name": m, "content": str(v)})

        cover_file = self.config.files.cover_file
        if cover_file:
            url = urlparse(cover_file)
            if all([url.scheme, url.netloc]):
                file_name = os.path.basename(url.path)
                file_path = os.path.join(self.config.files.working_folder, file_name)
                if not os.path.isfile(file_path):
                    echo("Downloading cover image...")
                    r = get(cover_file, stream=True)
                    if r.status_code == 200:
                        with open(file_path, "wb") as file:
                            for chunk in r:
                                file.write(chunk)
                cover_file = file_path

            if os.path.isfile(cover_file):
                with open(cover_file, "rb") as file:
                    book.set_cover(os.path.basename(cover_file), file.read())

        style = "@namespace epub \"http://www.idpf.org/2007/ops\";\n"
        if self.config.style:
            style += self.config.style

        stylesheet = epub.EpubItem(uid="style", file_name="style.css", media_type="text_css", content=style)
        book.add_item(stylesheet)

        chapters = []
        base_folder = self.config.files.book_folder
        for (i, c) in enumerate(filter(lambda x: x.get("converted"), self.manifest)):
            file_name = os.path.basename(c.get("file"))
            chapter = epub.EpubHtml(
                title=c.get("title"),
                file_name=file_name,
                lang=self.config.metadata.language,
            )

            with open(os.path.join(base_folder, file_name), "rb") as file:
                chapter.set_content(file.read())

            chapter.add_item(stylesheet)
            chapters.append(chapter)
            book.add_item(chapter)

        book.toc = tuple(chapters)
        book.spine = chapters

        book.add_item(epub.EpubNcx())
        book.add_item(epub.EpubNav())

        epub.write_epub(self.config.files.epub_file, book, {})

        echo("Created EPUB!")


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

# In[1]:

import os
import cv2
import numpy as np
from PIL import Image

# In[2]:

img = Image.open("/Users/mohamedabrar/Downloads/hw3_part2_data/Koala.jpg")

# In[3]:

img=np.asarray(img)

# In[4]:

original_size=os.path.getsize("/Users/mohamedabrar/Downloads/hw3_part2_data/Koala.jpg")

# In[5]:

img=np.reshape(img,(768*1024,3))

# In[6]:

comp_ratio=[]
temp_i=np.zeros((768*1024,3))

# In[7]:

for p in range(10):
    classes = [-1] * img.shape[0]
    classes=np.array(classes)
    k=2
    rows=np.array([])
    initial_cluster_rows=np.random.randint(0,img.shape[0],size=k)
    rows=(img[initial_cluster_rows])
    prev_rows=np.empty_like(rows)

    while (prev_rows!=rows).any():
        min_dist=[]
        prev_rows=rows
        for i in range(len(rows)):
            x1=rows[i][0]
            y1=rows[i][1]
            z1=rows[i][2]
            cluster=np.array((x1,y1,z1))
            dist=np.linalg.norm(cluster - img,axis=1)
            min_dist.append(dist)
        classes=np.argmin(min_dist,0)
        rows=[]
        for i in range(k):
            index=np.where(classes==i)
            if np.size(index)==0:
                rows.append(prev_rows[i])
            else:
                rows.append(np.mean(img[index],axis=0))
        rows=np.array(rows)
    temp_i=np.zeros((768*1024,3))
    for i in range(k):
        index=np.where(classes==i)
        temp_i[index]=rows[i]
    temp_i=temp_i.astype(np.uint8)
    img1=np.reshape(temp_i,(768,1024,3))
    image_compressed = Image.fromarray(img1)
    image_compressed.show()
    image_compressed.save('/Users/mohamedabrar/Downloads/hw3_part2_data/image.jpg')
    compressed_size=os.path.getsize('/Users/mohamedabrar/Downloads/hw3_part2_data/image.jpg')
    compression_ratio=(compressed_size/original_size)
    comp_ratio.append(compression_ratio)

# In[8]:

comp_ratio

# In[9]:

print(np.mean(comp_ratio))
print(np.var(comp_ratio))


a=int(input())
print("Units Consumed:",a)
if a<=199:
    u=1.20
elif a>=200 and a<400:
    u=1.40
elif a>=400 and a<600:
    u=1.60
elif a>=600 and a<800:
    u=1.80
else:
    u=2.00
print("Cost per Unit:",'%.2f'%u)
bill=a*u
print("Bill:",'%.2f'%bill)
if bill>400:
    s=0.15*bill
else:
    s=0
print("Surcharge:",'%.2f'%s)
print("Total Amount:",'%.2f'%(bill+s))


import numpy as np
from cil.framework import ImageData
from cil.optimisation.operators import LinearOperator

from cil.framework import ImageGeometry, AcquisitionGeometry, BlockGeometry

class ChannelwiseOperator(LinearOperator):

    r'''ChannelwiseOperator:  takes in a single-channel operator op and the
    number of channels to be used, and creates a new multi-channel
    ChannelwiseOperator, which will apply the operator op independently on
    each channel for the number of channels specified.

    ChannelwiseOperator supports simple operators as input but not
    BlockOperators. Typically if such behaviour is desired, it can be achieved
    by creating instead a BlockOperator of ChannelwiseOperators.

        :param op: Single-channel operator
        :param channels: Number of channels
        :param dimension: 'prepend' (default) or 'append' channel dimension onto existing dimensions

     '''

    def __init__(self, op, channels, dimension='prepend'):

        dom_op = op.domain_geometry()
        ran_op = op.range_geometry()

        geom_mc = []

        # Create multi-channel domain and range geometries: Clones of the
        # input single-channel geometries but with the specified number of
        # channels and additional dimension_label 'channel'.
        for geom in [dom_op,ran_op]:
            if dimension == 'prepend':
                new_dimension_labels = ['channel']+list(geom.dimension_labels)
            elif dimension == 'append':
                new_dimension_labels = list(geom.dimension_labels)+['channel']
            else:
                raise Exception("dimension must be either 'prepend' or 'append'")
            if isinstance(geom, ImageGeometry):

                geom_channels = geom.copy()
                geom_channels.channels = channels
                geom_channels.dimension_labels = new_dimension_labels

                geom_mc.append(geom_channels)
            elif isinstance(geom, AcquisitionGeometry):
                geom_channels = geom.copy()
                geom_channels.config.channels.num_channels = channels
                geom_channels.dimension_labels = new_dimension_labels

                geom_mc.append(geom_channels)

            elif isinstance(geom,BlockGeometry):
                raise Exception("ChannelwiseOperator does not support BlockOperator as input. Consider making a BlockOperator of ChannelwiseOperators instead.")
            else:
                pass

        super(ChannelwiseOperator, self).__init__(domain_geometry=geom_mc[0],
                                           range_geometry=geom_mc[1])

        self.op = op
        self.channels = channels

    def direct(self,x,out=None):

        '''Returns D(x)'''

        # Loop over channels, extract single-channel data, apply single-channel
        # operator's direct method and fill into multi-channel output data set.
        if out is None:
            output = self.range_geometry().allocate()
            cury = self.op.range_geometry().allocate()
            for k in range(self.channels):
                self.op.direct(x.get_slice(channel=k),cury)
                output.fill(cury.as_array(),channel=k)
            return output
        else:
            cury = self.op.range_geometry().allocate()
            for k in range(self.channels):
                self.op.direct(x.get_slice(channel=k),cury)
                out.fill(cury.as_array(),channel=k)

    def adjoint(self,x, out=None):

        '''Returns D^{*}(y)'''

        # Loop over channels, extract single-channel data, apply single-channel
        # operator's adjoint method and fill into multi-channel output data set.
        if out is None:
            output = self.domain_geometry().allocate()
            cury = self.op.domain_geometry().allocate()
            for k in range(self.channels):
                self.op.adjoint(x.get_slice(channel=k),cury)
                output.fill(cury.as_array(),channel=k)
            return output
        else:
            cury = self.op.domain_geometry().allocate()
            for k in range(self.channels):
                self.op.adjoint(x.get_slice(channel=k),cury)
                out.fill(cury.as_array(),channel=k)

    def calculate_norm(self, **kwargs):

        '''Evaluates operator norm of DiagonalOperator'''

        return self.op.norm()