import importlib
import random,time
from Controller import ConnectionToNeo4j,QuestionCreator,NestedQuestionCreator,vari,AudioRecorder,AyeshSilenceDetection
from Controller import SpeachToText
from gingerit.gingerit import GingerIt
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)

importlib.reload(vari)
# technology_list = []
userid = vari.userId

#gnerates non technical questions
def generate_cv_questions():
    global grammer_corrected_pr0ject_question
    db = "CV"
    db2= "project"
    db3 ="project_d"
    # node_Count = ConnectionToNeo4j.getNodeCount(db)
    lang = 'en'
    q_list = []
    pro_list = []
    count = 1
    session = 0
    typo = "nonested"
    typo2 = "nontechnical"
    answer_validity = 0

    global question_number
    question_number = 0

#generates questions from the three sections
    while count<=3:
        session = session + 1
        print("session")
        print(session)
        session_no_string = str(session)
        session_node_count = ConnectionToNeo4j.session_Node_Count(db,session_no_string)
        print("this is ")
        print(session_node_count)
        node_id = ConnectionToNeo4j.get_node_id(db,session_no_string)

        for id in range(node_id,session_node_count+node_id):
            q_list.append(str(id))
        print(q_list)

        print("node_count")
        print(session_node_count)

        for question_no in range(session_node_count):

            print("question number")
            print(question_no)
            random_que = random.choice(q_list)
            print("random que")
            print(random_que)
            #new pars

            non_technical_question = ConnectionToNeo4j.cvQuestionGen(db,random_que)
            q_list.remove(random_que)
            print(q_list)
            print("jokes"+non_technical_question)

            question_number = question_number + 1

            actual_question = QuestionCreator.gen_Question(non_technical_question,question_number)
            AyeshSilenceDetection.silence_detect1(question_number)

            # print(actual_question)
            # parser = GingerIt()
            # grammer_corrected_question_list = parser.parse(actual_question)
            # grammer_corrected_question = grammer_corrected_question_list.get("result")
            # TextToSpeechConverter.text_to_speech(grammer_corrected_question, lang)

            # print(question_number)
            # print("hiiiiiiiiiiiiiiiiii printing count")
            if random_que == "6":
                global technology_list
                tech = SpeachToText.validation("", typo2,typo,"question"+str(question_number))[1]

                tech = NestedQuestionCreator.keywordSelector("",tech.lstrip(),"1","")

                print(tech)
                print("tech printed")
                technology_list = NestedQuestionCreator.nonTechnicalKeywordSeelector(tech)
                print("hello tech")
                print(technology_list)

            #gets an input to ask questions
            if random_que=="5":
                # voice_record = AudioRecorder.audio_recorder(question_number)
                # answer_validity = SpeachToText.validation("", typo2, typo, "question" + str(question_number))[0]
                project_question = ""
                random_proj_que = ""
                print(vari.userId)
                pro = ConnectionToNeo4j.getProjects(vari.userId)
                print("pro")
                print(pro)
                print("pro")
                if not  pro:
                    random_proj_que = "final year project"
                    print(random_proj_que)
                else:
                    random_proj_que = random.choice(pro)
                    print(random_proj_que)
                print(random_proj_que)

                project_question = ConnectionToNeo4j.cvQuestionProjectGen(db2, db3, random_proj_que, userid)
                question_number = question_number + 1

                print("project question")
                print(project_question)
                print("project question")

                print(" pro length")

                print(len(pro_list))
                print(" pro length")

                actual_project_question = QuestionCreator.gen_Question(project_question,question_number)
                AyeshSilenceDetection.silence_detect1(question_number)

            print("after a while")

        q_list = []
        count = count+1


import numpy as np

def compute_ap(recall, precision):
    mrec = np.concatenate(([0.0], recall, [1.0]))
    mpre = np.concatenate(([0.0], precision, [0.0]))
    for i in range(mpre.size - 1, 0, -1):
        mpre[i-1] = np.maximum(mpre[i], mpre[i-1])

    i = np.where(mrec[1:] != mrec[:-1])[0] # 错开一位看计算存在变化的位置

    ap = np.sum((mrec[i+1] - mrec[i]) * mpre[i+1]) # 计算面积
    return ap

def voc_ap(rec, rec, pre, use_07_metric=True):
    if use_07_metric:
        # 11 point metric
        ap = 0.
        for t in np.arange(0., 1.1, 0.1):
            if np.sum(rec >= t) == 0:
                p = 0
            else:
                p = np.max(pre[rec >= t])
            ap += p / 11.
    else:
        mpre = np.concatenate(([0.0], pre, [0.0]))
        mrec = np.concatenate(([0.0], rec, [1.0]))

        #保证precision从前往后非减
        for i in range(mpre.size - 1, 0, -1):
            mpre[i-1] = np.maximum(mpre[i], mpre[i-1])

        i = np.where(mrec[1:] != mrec[:-1])[0]

        ap = np.sum((mrec[i+1] - mrec[i]) * mpre[i+1])
    return ap


import asyncio
from threading import Thread
from queue import Queue

from bbr_simulator.server import start_server
from bbr_simulator.game import Game

req_queue = Queue()
res_queue = Queue(1)

async def game_interval(game):
  while True:
    while not req_queue.empty():
      action = req_queue.get()
      if action[0] == "state":
        res_queue.put(game.get_state(action[1]))
      elif action[0] == "action":
        game.send_action(action[1], action[2])
      req_queue.task_done()

    game.update()
    await asyncio.sleep(1.0/60)

def start_background_loop(loop, game):
  asyncio.set_event_loop(loop)

  game_task = loop.create_task(game_interval(game))

  loop.run_until_complete(start_server(game))
  loop.run_until_complete(game_task)

  loop.run_forever()

class Simulation:
  def __init__(self, **kwargs):
    self.game = Game(**kwargs)

  def run(self):
    loop = asyncio.new_event_loop()
    thread = Thread(target=start_background_loop, args=(loop, self.game), daemon=True)
    thread.start()

  def get_state(self, robot_index=0):
    req_queue.put(["state", robot_index])
    state = res_queue.get()
    res_queue.task_done()

    return state

  def send(self, action, robot_index=0):
    req_queue.put(["action", robot_index, action])


# Implement merge sort algorithm using python.

def mergesort(li):
    if len(li) > 1:
        mid = len(li)//2    #Finding the mid of the array
        left = li[:mid]     #Dividing the array elements
        right = li[mid:]    #into 2 halves

        mergesort(left)     # Sorting the first half
        mergesort(right)    # Sorting the second half

        i = 0
        j = 0
        k = 0

         # Copy data to temp arrays L[] and R[]
        while i < len(left) and j < len (right):
            if left[i] <= right[j]:
                li[k] = left[i]
                i = i+1
                k = k+1
            else:
                li[k] = right[j]
                j = j+1
                k = k+1

        # Checking if any element was left
        while i < len(left):
            li[k] = left[i]
            i = i+1
            k = k+1

        while j < len(right):
            li[k] = right[j]
            j = j+1
            k = k+1

x = [90, 50, 60, 30, 40,  80,  70, 10, 20, 100]
mergesort(x)
print(x)


#!/usr/bin/env python3

import fn
import pytest

@pytest.fixture
def data():
    return [3, 2, 1, 5, -3, 2, 0, -2, 11, 9]

def test_sel_sort(data):
    sorted_vals = fn.sel_sort(data)
    assert sorted_vals == sorted(data)

def test_min():
    values = (2, 3, 1, 4, 6)
    val = fn.min(values)
    assert val == 1

def test_max():
    values = (2, 3, 1, 4, 6)

    val = fn.max(values)
    assert val == 6

@pytest.mark.parametrize(
    "word, expected", [
    ('kayak', True),
    ('civic', True),
    ('forest', False)
])
def test_palindrome(word, expected):

    val = fn.is_palindrome(word)
    assert val == expected


#!/usr/bin/env python
"""
Cache for whois server lists.
"""

import sys
import os
import time
import logging
import random

import errno
import socket
import select

import ConfigParser

from seine.address import IPv4Address, IPv6Address
from seine.dns.tld import TLDCache, DNSCacheError
from seine.whois import WhoisError

CACHE_FILES = (
    '/var/cache/whois/servers.cache',
    '/tmp/whois-%s/servers.cache' % os.geteuid(),
)
SEARCH_DOMAIN = 'whois-servers.net'

WHOIS_PORT = 43
WHOIS_SERVER_TIMEOUT = 15
WHOIS_BUFFER_SIZE = 1024

TLD_REQUIRES_EQUALS = ['com']

logger = logging.getLogger(__file__)

class WhoisServer(object):
    def __init__(self, tld, address, timeout=WHOIS_SERVER_TIMEOUT):
        self.tld = tld
        self.address = address
        self.timeout = float(timeout)
        self.socket = None

    def __del__(self):
        self.close()

    def close(self):
        if self.socket is not None:
            self.socket.close()
        self.socket = None

    def connect(self):
        raise NotImplementedError('Must be implemented in child class')

    def send_query(self, domain):
        raise NotImplementedError('Must be implemented in child class')

    def get_response(self, buffer_size=WHOIS_BUFFER_SIZE):
        raise NotImplementedError('Must be implemented in child class')

class IPv4WhoisServer(WhoisServer):
    def connect(self):
        if self.socket is not None:
            raise WhoisError('Connection already open to %s' % self.address)

        self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        while True:
            try:
                self.socket.connect((self.address, WHOIS_PORT))
            except socket.error as e:
                if ecode in [e[0].EINPROGRESS, e[0].EALREADY]:
                    continue
                else:
                    raise WhoisError('Error connecting to %s: %s' % (self.address, e[1]) )
            break

        ret = select.select([self.socket], [self.socket], [], 5)
        if len(ret[1]) == 0 and len(ret[0]) == 0:
            self.close()
            raise WhoisError('Timeout waiting for data from %s' % self.address)

    def send_query(self, domain):
        if self.socket is None:
            raise WhoisError('Connection not open to %s' % self.address)

        self.socket.setblocking(1)
        self.socket.settimeout(self.timeout)

        if self.tld in TLD_REQUIRES_EQUALS:
            data = '=%s\r\n' % domain
        else:
            data = '%s\r\n' % domain

        self.socket.send(data)

    def get_response(self, buffer_size=WHOIS_BUFFER_SIZE):
        if self.socket is None:
            raise WhoisError('Connection not open to %s' % self.address)

        out = ''
        while True:
            try:
                data = self.socket.recv(WHOIS_BUFFER_SIZE)
            except socket.timeout:
                self.close()
                raise WhoisError('Request timeout to %s' % self.address)
            except socket.error as e:
                if ecode in [e[0].EINPROGRESS, e[0].EALREADY]:
                    continue
                else:
                    self.close()
                    raise WhoisError('Error reading data from %s: %s' % (self.address, emsg))

            # End of data
            if not data:
                break

            out += data

        self.close()

        return out

class IPv6WhoisServer(WhoisServer):
    def connect(self):
        raise NotImplementedError('IPv6 whois queries not yet implemented')

    def send(self, s, data):
        raise NotImplementedError('IPv6 whois queries not yet implemented')

    def get_response(self, s, buffer_size=WHOIS_BUFFER_SIZE):
        raise NotImplementedError('IPv6 whois queries not yet implemented')

class TLDWhoisServerList(object):
    def __init__(self, tld, ipv4_addresses=[], ipv6_addresses=[]):
        self.tld = tld
        self.ipv4_addresses = [IPv4Address(address) for address in ipv4_addresses]
        self.ipv6_addresses = [IPv6Address(address) for address in ipv6_addresses]

    def __repr__(self):
        return 'TLD .%s whois servers: %s %s' % (
            self.tld,
            ','.join(x.ipaddress for x in self.ipv4_addresses),
            ','.join(x.address for x in self.ipv6_addresses),
        )

    def query(self, name, ipv4=True, ipv6=False):
        if ipv4:
            if not self.ipv4_addresses:
                raise WhoisError('No IPv4 addresses for %s whois servers' % self.tld)
            server = IPv4WhoisServer(self.tld, random.choice(self.ipv4_addresses).ipaddress)

        elif ipv6:
            if not self.ipv6_addresses:
                raise WhoisError('No IPv6 addresses for %s whois servers' % self.tld)
            server = IPv6WhoisServer(random.choice(self.ipv6_addresses).address)

        tld = name.rstrip('.').split('.')[-1]
        if tld != self.tld:
            raise WhoisError('TLD %s does not match server: %s' % (tld, self.tld))

        server.connect()
        server.send_query(name)
        return server.get_response()

class WhoisServerCache(dict):
    def __init__(self, cache_path=None, tld_cache_path=None):
        self.cache_path = None

        if cache_path is not None:
            self.cache_path = os.path.expandvars(os.path.expanduser(cache_path))

        else:
            for f in CACHE_FILES:
                if os.path.isfile(f) and os.access(f, os.W_OK):
                    self.cache_path = f
                    break

                fdir = os.path.dirname(f)
                if not os.path.isdir(fdir):
                    try:
                        os.makedirs(os.path.dirname(f))
                    except IOError:
                        continue
                    except OSError:
                        continue

                if not os.path.isfile(f):
                    try:
                        open(f, 'w').write('\n')
                        os.unlink(f)
                        self.cache_path = f
                        break
                    except IOError:
                        continue
                    except OSError:
                        continue

        if self.cache_path is None:
            raise WhoisError('ERROR: No whois cache path defined')

        try:
            self.tlds = TLDCache(tld_cache_path)
            if not self.tlds.is_downloaded:
                self.tlds.download()
        except DNSCacheError as e:
            raise WhoisEror(e)

        if os.path.isfile(self.cache_path):
            self.load()

    def load(self):
        if not os.path.isfile(self.cache_path):
            raise WhoisError('No such file: %s' % self.cache_path)

        try:
            cache = ConfigParser.ConfigParser()
            cache.read(self.cache_path)
        except OSError as e:
            raise WhoisError(e)
        except IOError as e:
            raise WhoisError(e)

        for tld in cache.sections():
            try:
                ipv4_addresses = []
                ipv6_addresses = []
                if cache.has_option(tld, 'ipv4_addresses') and cache.get(tld, 'ipv4_addresses'):
                    ipv4_addresses.extend(cache.get(tld, 'ipv4_addresses').split(','))
                if cache.has_option(tld, 'ipv6_addresses') and cache.get(tld, 'ipv6_addresses'):
                    ipv6_addresses.extend(cache.get(tld, 'ipv6_addresses').split(','))
                entry = TLDWhoisServerList(tld, ipv4_addresses, ipv6_addresses)
                self[tld] = entry
            except ConfigParser.NoOptionError:
                logger.debug('Invalid cache entry for %s' % tld)

    def save(self):
        if len(self) == 0:
            return

        cache_dir = os.path.dirname(self.cache_path)

        if not os.path.isdir(cache_dir):
            try:
                os.makedirs(cache_dir)
            except IOError as e:
                raise WhoisError('Error creating cache directory %s: %s' % (cache_dir, e))
            except OSError as e:
                raise WhoisError('Error creating cache directory %s: %s' % (cache_dir, e))

        try:
            cache = ConfigParser.ConfigParser()
            for entry in self.values():
                section = cache.add_section(entry.tld)
                cache.set(entry.tld, 'ipv4_addresses', ','.join(x.ipaddress for x in entry.ipv4_addresses))
                cache.set(entry.tld, 'ipv6_addresses', ','.join(x.address for x in entry.ipv6_addresses))
            cache.write(open(self.cache_path, 'w'))

        except OSError as e:
            raise WhoisError('Error updating cache %s: %s' % (self.cache_path, e))
        except IOError as e:
            raise WhoisError('Error updating cache %s: %s' % (self.cache_path, e))

    def get(self, tld, timeout=WHOIS_SERVER_TIMEOUT):
        try:
            timeout = int(timeout)
        except ValueError:
            raise WhoisError('Invalid timeout value: %s' % timeout)

        if tld not in self.tlds:
            raise WhoisError('Invalid TLD name: %s' % tld)

        if tld not in self:
            details = {}
            name = '.'.join([tld, SEARCH_DOMAIN])
            try:
                socket.setdefaulttimeout(timeout)
                name, aliases, addresses = socket.gethostbyname_ex(name)
                entry = TLDWhoisServerList(tld, addresses)
                self[tld] = entry

            except socket.timeout:
                raise WhoisError('Timeout resolving whois server %s' % name)
            except socket.gaierror as e:
                raise WhoisError(e)
            except ValueError as e:
                raise WhoisError(e)

        return self[tld]

    def query(self, name):
        try:
            tld = name.rstrip('.').split('.')[-1]
        except ValueError:
            raise WhoisError('Error parsing TLD from %s' % name)

        tldservers = self.get(tld)
        return tldservers.query(name)


class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def addTwoNumbers(self, l1, l2):
        dummy = curr = ListNode(0)
        carry = 0
        while l1 or l2 or carry:
            v1 = v2 = 0
            if l1:
                v1 = l1.val
                l1 = l1.next
            if l2:
                v2 = l2.val
                l2 = l2.next
            carry, val = divmod(v1+v2+carry, 10)
            curr.next = ListNode(val)
            curr = curr.next
        return dummy.next

专题训练/链表/中等题/计算两个链表的和.py


import os

from lxml import etree

attribute_type = 0
attribute_value = 1
pc_pcf = '/config/web/pcf/line'
apd_class = 'gw.web.rules.APDRulesHelper'
pmp_class = 'gw.pmp.apd.web.rules.APDRulesHelper_PMP'
file_ends = ['PanelSet.pcf', 'Popup.pcf', 'ListDetail.pcf', 'Screen.pcf']
no_process = ['MenuItemSet', 'WizardStepSet']
input_tags = ['TextInput', 'RangeInput', 'PickerInput', 'TextAreaInput', 'TypeKeyInput', 'BooleanRadioInput',
              'DateInput', 'MonetaryAmountInput', 'TextCell']
name_change = dict()

def check_no_process(in_file_name: str) -> bool:
    """ There are some instances where the file should no be processed at the moment, by not processing these files
        defined in the no_process variable there may be some small manual changes needed to get the new PCF files to
        be used"""
    for nop in no_process:
        if in_file_name.count(nop) > 0:
            return True
    return False

class ProcessPCF:

    def process_pcf(self):
        for x in os.listdir(self.pc_policy_dir):
            print(f'processing : {x}')
            if not check_no_process(x):
                self.process_root(self.pc_policy_dir, x)
        for x in os.listdir(self.pc_policy_file_dir):
            print(f'processing : {x}')
            if not check_no_process(x):
                self.process_root(self.pc_policy_file_dir, x)
        for x in os.listdir(self.pc_job_dir):
            print(f'processing : {x}')
            if not check_no_process(x):
                self.process_root(self.pc_job_dir, x)

    def process_root(self, in_dir: str, in_pcf_file: str):
        """ The PCF file is opened and each of the elements in the PCF file, depending on the element there may be
            special processing that needs to take place. When a target element is identified the
            function to process the element is called. """
        tree = etree.parse(in_dir + '/' + in_pcf_file)
        self.root = tree.getroot()
        for element in self.root.iter():
            if element.tag == 'InputSet':
                self.process_input_set(element)
            if element.tag == 'WizardStepSet':
                self.process_id(element, in_pcf_file)
            if element.tag == 'Page':
                self.process_id(element, in_pcf_file)
                self.process_ref(element, 'ScreenRef')
            if element.tag == 'PanelSet':
                self.process_id(element, in_pcf_file)
                self.process_ref(element, 'PanelRef')
            if element.tag == 'Popup':
                self.process_id(element, in_pcf_file)
            if element.tag == 'LocationGroup':
                self.process_id(element, in_pcf_file)
                self.process_ref(element, 'LocationRef')
            if element.tag == 'Screen':
                self.process_id(element, in_pcf_file)
                self.process_ref(element, 'PanelRef')
            if element.tag == 'Variable':
                self.process_apd_variable(element)
            if element.tag in input_tags:
                self.process_tag(element)
            if element.tag == 'LocationEntryPoint':
                self.process_location_entry_point(element, in_pcf_file)

        content = etree.tostring(self.root, pretty_print=True)
        new_pcf_file = self.new_file_name(in_pcf_file)
        print(f'writing : {new_pcf_file}')
        file = open(in_dir + "/" + new_pcf_file, 'w')
        file.write(content.decode('utf-8'))
        file.close()

    def process_apd_variable(self, element):
        """ APD sets the variables isEditable and isVisible to use in the PCF, the use of these variables gets
            around the current processing that worked in previous versions of PolicyCenter. To ensure that PMP works
            correctly the other variables isRequired and isAvailable are added. While these are not added by
            APD at the moment they may well feature in a future version."""
        required_str = None
        attributes = element.attrib
        if 'name' in attributes:
            _name = attributes.get('name')
            if _name == 'isEditable':
                self.update_apd_tag(attributes)
            if _name == 'isVisible':
                self.update_apd_tag(attributes)
            if _name == 'isRequired':
                self.update_apd_tag(attributes)
            if _name == 'isAvailable':
                self.update_apd_tag(attributes)

    def process_location_entry_point(self, element, in_pfc_file: str):
        attributes = element.attrib
        if 'signature' in attributes:
            _sig_name = in_pfc_file.replace('.pcf', '')
            _new_name = self.new_file_name(in_pfc_file).replace('.pcf', '')
            _location = attributes.get('signature')
            attributes['signature'] = _location.replace(_sig_name, _new_name)

    def process_ref(self, element, in_ref: str):
        _ref_type = ['ref', 'location', 'def']
        for sub_element in element.iter():
            if sub_element.tag == in_ref:
                attributes = sub_element.attrib
                for ref in _ref_type:
                    if ref in attributes:
                        _location_name = f"{attributes.get(ref).split('(')[0]}.pcf"
                        if _location_name.startswith('OOSEPanelSet'):
                            pass
                        else:
                            _new_name = self.new_file_name(_location_name)
                            _location = attributes.get(ref)
                            attributes[ref] = _location.replace(_location_name.replace('.pcf', ''),
                                                                _new_name.replace('.pcf', ''))

    def process_id(self, element, in_pfc_file: str):
        """ Updates the id associated with the widget from the original to the modified name
            making use of the _Ext"""
        attributes = element.attrib
        if 'id' in attributes:
            attributes['id'] = self.new_file_name(in_pfc_file).replace('.pcf', '')

    def process_tag(self, element):
        attributes = element.attrib
        if attributes.get('required') is None or (
                not attributes.get('required').startswith(pmp_class) and not attributes.get(
            'required') == 'isRequired'):
            self.process_required(attributes)
        if attributes.get('valueVisible') is not None and (
                not attributes.get('valueVisible').startswith(pmp_class) and not attributes.get(
            'valueVisible') == 'isVisible'):
            self.process_value_visible(attributes, attributes.get('valueVisible'), self.get_field(attributes))
        if attributes.get('available') is None or (
                not attributes.get('available').startswith(pmp_class) and not attributes.get(
            'available') == 'isAvailable'):
            self.process_available(attributes)
        for sub_element in element.iter():
            if sub_element.tag == 'PostOnChange':
                self.process_post_on_change(sub_element)

    def process_post_on_change(self, element):
        """Changes the APD functions used for the post on change to call the PMP equivalent functions. The PMP
           version of the functions act as a wrapper incorporating the original APD functions"""
        attributes = element.attrib
        if attributes.get('disablePostOnEnter') is None or (
                not attributes.get('disablePostOnEnter').startswith(pmp_class)):
            _pmp_code = attributes.get('disablePostOnEnter').replace(apd_class, pmp_class)
            attributes['disablePostOnEnter'] = _pmp_code
        if attributes.get('onChange') is None or (
                not attributes.get('onChange').startswith(pmp_class)):
            _pmp_code = attributes.get('onChange').replace(apd_class, pmp_class)
            attributes['onChange'] = _pmp_code
        return self

    def update_apd_tag(self, attributes):
        if 'initialValue' in attributes:
            _initialValue = attributes.get('initialValue').replace(apd_class, pmp_class)
            attributes['initialValue'] = _initialValue
        return self

    def get_field(self, attributes):
        field_str_array = attributes.get('value').split('.')
        field_str = ''
        for field in range(len(field_str_array)):
            if field < len(field_str_array) - 1:
                if field == 0:
                    field_str = field_str + field_str_array[field]
                else:
                    field_str = field_str + '.' + field_str_array[field]
            else:
                field_str = field_str + '#' + field_str_array[field]
        if self:
            return [field_str_array[0], field_str]

    def process_available(self, attributes):
        attributes['available'] = 'isAvailable'
        return self

    def process_available_variable(self, available_str, value_str):
        if value_str[1].startswith('#'):
            return

        available_str = pmp_class + '.isAvailable(' \
                        + value_str[0] + '.PolicyLine, ' \
                        + value_str[0] + ', ' \
                        + value_str[1] + '.PropertyInfo' \
                        + ')'
        if self:
            return available_str

    def process_required(self, attributes):
        attributes['required'] = 'isRequired'
        return self

    def process_required_variable(self, required_str, value_str):
        """ Function to return the PMP function for the isRequired variable"""
        if value_str[1].startswith('#'):
            return
        default_str = 'false'
        if required_str is not None:
            default_str = '(' + required_str + ')'
        required_str = pmp_class + '.isRequired(' \
                       + value_str[0] + '.PolicyLine, ' \
                       + value_str[0] + ', ' \
                       + value_str[1] + '.PropertyInfo, ' \
                       + default_str \
                       + ')'
        if self:
            return required_str

    def process_value_visible(self, attributes, visible_str, value_str):
        if value_str[1].startswith('#'):
            return
        default_str = 'false'
        if visible_str is not None:
            default_str = '(' + visible_str + ')'
        visible_str = visible_str.replace(apd_class, pmp_class)
        attributes['valueVisible'] = visible_str
        return self

    def process_input_set(self, original_element):
        """ To get round the issue of the PCF on change functionality we need to test for the existence of the
            isRequired variable. If the isEditable and isVisible defined then we are looking in the right place and if
            there is no isRequired variable it will be added. To add the variable, information from the input needs
            to be extracted first."""
        apd_variables = {'isEditable': False, 'isVisible': False, 'isRequired': False, 'isAvailable': False}
        input_attributes = None
        for sub_element in original_element.iter():
            #
            # If there is an input widget in the input set the attributes are stored for later processing
            #
            if sub_element.tag in input_tags:
                input_attributes = sub_element.attrib
            #
            # When a variable is found in the input set and it is in the apa_variables dictionary the
            # item in the dictionary is updated from False to True
            #
            if sub_element.tag == 'Variable':
                attributes = sub_element.attrib
                if 'name' in attributes:
                    _name = attributes['name']
                    apd_variables[_name] = True
                    element = sub_element
        #
        # if there exists only the isEditable and the isVisible variables and the input widget attributes
        # have been saved it is assumed the isRequired and isAvailable variables need to be created
        #
        if apd_variables['isEditable'] and apd_variables['isVisible'] and input_attributes is not None:
            if not apd_variables['isRequired']:
                pmp_function = self.process_required_variable(input_attributes.get('required'),
                                                              self.get_field(input_attributes))
                variable_element = etree.Element('Variable')
                variable_element.set('initialValue', pmp_function)
                variable_element.set('name', 'isRequired')
                variable_element.set('recalculateOnRefresh', 'true')
                variable_element.set('type', 'Boolean')
                original_element.insert(0, variable_element)
            if not apd_variables['isAvailable']:
                pmp_function = self.process_available_variable(input_attributes.get('required'),
                                                               self.get_field(input_attributes))
                variable_element = etree.Element('Variable')
                variable_element.set('initialValue', pmp_function)
                variable_element.set('name', 'isAvailable')
                variable_element.set('recalculateOnRefresh', 'true')
                variable_element.set('type', 'Boolean')
                original_element.insert(0, variable_element)
        return self

    def new_file_name(self, in_pfc_file: str) -> str:
        """Modifications to the originally generated APD PCF files should not be done, to this end this function
           defines the name of the new PCF file to be created. """
        if name_change.get(in_pfc_file) is not None:
            return name_change.get(in_pfc_file)
        if in_pfc_file.count('_Ext') > 0:
            return in_pfc_file
        new_pcf_file: str = ''
        for file_ending in file_ends:
            if in_pfc_file.endswith(file_ending):
                new_pcf_file = in_pfc_file.replace(file_ending, '_Ext' + file_ending)
        if new_pcf_file == '':
            new_pcf_file = in_pfc_file.replace('.pcf', '_Ext.pcf')
        if in_pfc_file != new_pcf_file:
            name_change[in_pfc_file] = new_pcf_file
        if self:
            return new_pcf_file

    def __init__(self, in_config_json):
        self.config_json = in_config_json
        self.root = None
        self.pc_path = in_config_json['pc_path']
        self.pc_product_abbreviation = in_config_json['pc_product_abbreviation']
        self.pc_policy_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/policy'
        self.pc_policy_file_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/policyfile'
        self.pc_job_dir = self.pc_path + pc_pcf + '/' + self.pc_product_abbreviation + '/job'


class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        vowels = "aeiouAEIOU"
        words = sentence.split()
        goat = []

        for index, word in enumerate(words):
            if word[0] not in vowels:
                word = word[1:] + word[0]
            word += "ma" + "a" * (index + 1)
            goat.append(word)

        return " ".join(goat)

def main():
    sol = Solution()
    print(sol.toGoatLatin("I speak Goat Latin"))

if __name__ == '__main__':
    main()


# Importando bibliotecas
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# import seaborn as sns
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix, accuracy_score, precision_score, precision_recall_curve, recall_score, f1_score
import streamlit as st
from imblearn.over_sampling import SMOTE
# import pickle
from utils.Global import *

import warnings
warnings.filterwarnings('ignore')

def titulo_app():
    # st.write("*TCC - Trabalho de Conclusão de Curso*")
    # st.write("*Deploy de Modelo Preditivo de Machine Learning*")
    # st.write("*Previsão do Risco de Crédito*")
    # st.write("*Autor: Matheus Fabião da Costa Pereira*")
    # st.write("*Autor: Matheus Davi de Serrano Araújo Meireles*")
    # st.write("*Autor: Leandro Santana de Melo*")
    st.title("Random Forest Classifier Model")

@st.cache_data
def carrega_dataset():
    # Carregando os dados
    try:
        caminho_dados = './data/risco_credito.csv'
        dados = pd.read_csv(caminho_dados)
        return dados
    except Exception as e:
        st.error(f'Erro ao carregar dados: {str(e)}')
        return None

def pre_processar_dados(dados):
    dados.drop(columns=['Unnamed: 0'], axis=1, inplace=True)
    dados["Saving accounts"] = dados["Saving accounts"].fillna("none")
    dados["Checking account"] = dados["Checking account"].fillna("none")
    return dados

def exibe_dataset(dados):
    # Exibir os últimos 5 dados do Dataset
    pre_processar_dados(dados)
    st.subheader('Dataset: Risco de Crédito')
    st.dataframe(dados)

def info_dataset():
    # Exibe um expander ao clicar no botão de ajuda
    with st.expander("ℹ **Informações do Dataset**"):
        st.write('''**Age:** Idade do cliente.
             **Sex:** Gênero do cliente (Masculino ou Feminino).
             **Job:** Tipo de ocupação do cliente.
             **Housing:** Tipo de moradia do cliente (Própria, Gratuita ou Alugada).
             **Saving accounts:** Estado da conta de poupança do cliente.
             **Checking account:** Estado da conta corrente do cliente.
             **Credit amount:** Valor do crédito solicitado/concedido.
             **Duration:** Duração do empréstimo em meses.
             **Purpose:** Finalidade do empréstimo.
             **Risk:** Risco de crédito associado à solicitação (Bom ou Ruim).''')

def codifica_dados(dados):
    # Separe as colunas categóricas
    colunas_categoricas = dados.select_dtypes(exclude=['int64', 'float64'])

    le = LabelEncoder()
    for coluna in colunas_categoricas:
        dados[coluna]=le.fit_transform(dados[coluna])

    return dados

def separa_dados(dados, split):
    # Separando as características (x) e as classes alvo (y) dos dados
    x = dados.drop(['Risk'], axis=1)
    y = dados['Risk']

    smote = SMOTE(random_state=42)
    x_reamostrado, y_reamostrado = smote.fit_resample(x, y)

    x_treino, x_teste, y_treino, y_teste = train_test_split(x_reamostrado, y_reamostrado, train_size=split, random_state=42)

    return x_treino, x_teste, y_treino, y_teste

def declara_normalizador():
    Normalizador = StandardScaler()
    return Normalizador

def normaliza_dados(x, y, Normalizador):
    # Normalização dos dados
    x_treino = Normalizador.fit_transform(x)
    x_teste = Normalizador.transform(y)

    return x_treino, x_teste

def cria_modelo(Hiperparametros):
    # Cria o modelo de RFC
    modelo = RandomForestClassifier(n_estimators= Hiperparametros['N_estimators'],
                                             max_depth= Hiperparametros['Max_depth'],
                                             min_samples_split= Hiperparametros['Min_samples_split'],
                                             class_weight= Hiperparametros['Class_weight'])
    return modelo

def treina_modelo(modelo, Xtreino, Ytreino):
    modelo.fit(Xtreino, Ytreino)

def faz_previsao(modelo, Xteste):
    previsao = modelo.predict(Xteste)
    return previsao

# Função para calcular métricas de desempenho
def calcula_metricas(Yteste, Previsao):
    # Avaliando o modelo usando as principais métricas
    precisao = precision_score(Yteste, Previsao)
    recall = recall_score(Yteste, Previsao)
    f1 = f1_score(Yteste, Previsao)
    acuracia = accuracy_score(Yteste, Previsao)
    matriz_confusao = confusion_matrix(Yteste, Previsao)
    return precisao, recall, f1, acuracia, matriz_confusao

# Função para exibir métricas de desempenho
def exibe_metricas(Precisao, Recall, F1, Acuracia, Matriz_confusao):
        # Avaliando o modelo usando as principais métricas
        col1, col2 = st.columns(2)
        col1.write(f'Precisão: {Precisao:.2f}')
        col1.write(f'Recall: {Recall:.2f}')
        col1.write(f'F1-Score: {F1:.2f}')
        col1.write(f'Acurácia: {Acuracia:.2f}')
        col2.subheader('Matriz de Confusão:')
        col2.write(Matriz_confusao)

def ajuda_config():
    # Adiciona um botão na sidebar
    if st.sidebar.button('Ajuda com os Hiperparâmetros'):
        # Exibe um expander ao clicar no botão de ajuda
        with st.expander("ℹ **Informações de Ajuda**"):
            st.write('''
                    **Divisão dos Dados:** dividir o total de dados em x% para treino da IA. Recomendado entre 0.7 e 0.8

                    **n_estimators:** Número de árvores na floresta no algoritmo de Random Forest.

                    **max_depth:** Profundidade máxima de cada árvore na floresta.

                    **min_samples_split:** Número mínimo de amostras necessárias para dividir um nó interno.

                    **Peso das Classes:** Peso atribuído às classes no treinamento para lidar com desequilíbrios, usado principalmente em problemas de classificação.
                    ''')

def normaliza_novos_dados(Novos_dados, Normalizador, Nome):
    # Criando o DataFrame
    df = pd.DataFrame(Novos_dados)

    # Exibindo o DataFrame
    st.info(f'Exibindo dados de {Nome}')
    st.dataframe(df)

    # Separe as colunas categóricas
    colunas_categoricas = df.select_dtypes(exclude=['int64', 'float64'])

    le = LabelEncoder()
    for coluna in colunas_categoricas:
        df[coluna]=le.fit_transform(df[coluna])

    # x = np.array(Novos_dados).reshape(1, -1)
    # Transforma o array 1D em 2D
    x = Normalizador.transform(df)
    return x

def previsao_novos_dados(modelo, X):
    good = 'Baixo Risco'
    bad = 'Alto Risco'
    previsao = modelo.predict(X)
    if previsao[0] == 1:
        st.write('O resultado da previsão foi:', bad)
    else:
        st.write('O resultado da previsão foi:', good)
    return previsao


# Eric K.
# Meta Global Hackathon 2022

from fractions import Fraction
from decimal import *
getcontext().prec = 128

# Input
lines = []
file_name = "ti.txt"
#file_name = "promotions_hard_input.txt"
with open(file_name, "r") as f:
    for line in f:
        lines.append(line.rstrip())

# Auxiliarry functions
lvl1 = Fraction(10**6)
lvl2 = Fraction(2*10**6)

def get_level(wage):
    if wage < lvl1:
        return 0
    elif wage < lvl2:
        return 1
    else:
        return 2

def to_decimal_string(frac):
    numerator = frac.numerator
    denominator = Decimal(frac.denominator)
    return str(Decimal(numerator/denominator).quantize(Decimal('0.000001')))

# Processing
ans_lines = []
t = int(lines[0])
lines = lines[1:]
for _ in range(t):
    n, q = [int(x) for x in lines[0].split()]
    wages = [Fraction(x) for x in lines[1].split()]
    lines = lines[2:]

    for _ in range(q):
        query = lines[0].split()
        print(wages)
        print(query)
        lines = lines[1:]
        if query[0] == "1": # Modify
            percentages = [Fraction(100 + int(x), 100) for x in query[1:4]]
            e, r = [int(x) for x in query[4:6]]
            e -= 1
            #levels = [get_level(wages[x]) for x in range(n)]
            for _ in range(r):
                for i in range(n):
                    wages[i] *= percentages[get_level(wages[i])]
                    #wages[i] *= percentages[levels[i]]
                print(to_decimal_string(wages[e]))
                print(wages[e])
                ans_lines.append(to_decimal_string(wages[e]))
        elif query[0] == "2": # Query
            e1, e2 = [int(x) - 1 for x in query[1:]]
            total = Fraction(0)
            for i in range(e1, e2+1):
                total += wages[i]
            print(to_decimal_string(total))
            ans_lines.append(to_decimal_string(total))
        print("========")
    print("x=x=x=x=x=x=x=x=x=x")

# Output
with open("out.txt", "w") as f:
    for line in ans_lines:
        f.write(line + "\n")

2022-2 - Meta Global Hackathon/Challenge 5 (precision issues)/challenge5b.py


import pandas as pd
import sqlite3, os

os.chdir(os.path.dirname(__file__))

df = pd.read_csv('seattle-weather.csv')

# Fact table
datetime_col = pd.to_datetime(df['date'])
df['year'] = datetime_col.dt.year
df['quarter'] = 'Q' + datetime_col.dt.quarter.astype(str)
df['month_order'] = datetime_col.dt.month
df['month_name'] = datetime_col.dt.month_name()
df['day_of_year'] = datetime_col.dt.day_of_year

df['start_of_year'] = datetime_col.apply(lambda x: pd.Timestamp(year=x.year, month=1, day=1)).dt.strftime('%Y-%m-%d')
df['start_of_quarter'] = datetime_col.apply(lambda x: pd.Timestamp(year=x.year, month=(x.month-1)//3*3+1, day=1)).dt.strftime('%Y-%m-%d')
df['start_of_month'] = datetime_col.apply(lambda x: pd.Timestamp(year=x.year, month=x.month, day=1)).dt.strftime('%Y-%m-%d')
df['start_of_week'] = datetime_col.apply(lambda x: x - pd.Timedelta(days=(x.dayofweek+1)%7)).dt.strftime('%Y-%m-%d')

# Dim table
start_of_year = df['start_of_year'].unique()
start_of_quarter = df['start_of_quarter'].unique()
start_of_month = df['start_of_month'].unique()
lookup_df = pd.DataFrame({
    'start_of_time': list(start_of_year) + list(start_of_quarter) + list(start_of_month),
    'time_type_id': ([0] * len(start_of_year)) +
                      ([1] * len(start_of_quarter)) +
                      ([2] * len(start_of_month)),
})

time_type_df = pd.DataFrame({
    'index': [0, 1, 2],
    'value': ['Year', 'Quarter', 'Month'],
    'column': ['start_of_year', 'start_of_quarter', 'start_of_month']
})

# Connect to SQLite database
conn = sqlite3.connect('seattle_weather.db')
try:
    df.to_sql('weather', conn, index=False, if_exists='replace')
    lookup_df.to_sql('time_lookup', conn, if_exists='replace')
    time_type_df.to_sql('time_type', conn, index=False, if_exists='replace')
finally:
    conn.close()


import csv

#manipulating Zillow data to create a new schema

files = [open('data/Zip_MedianRentalPrice_with_header/Zip_MedianRentalPrice_1Bedroom.csv','r')
		,open('data/Zip_MedianRentalPrice_with_header/Zip_MedianRentalPrice_2Bedroom.csv','r')
		,open('data/Zip_MedianRentalPrice_with_header/Zip_MedianRentalPrice_3Bedroom.csv','r')
		,open('data/Zip_MedianRentalPrice_with_header/Zip_MedianRentalPrice_4Bedroom.csv','r')
		,open('data/Zip_MedianRentalPrice_with_header/Zip_MedianRentalPrice_5BedroomOrMore.csv','r') ]

locations_csv = open('data/output/locations.csv','wb')
rentalPrice_csv = open('data/output/rental_price.csv','wb')

readers = [csv.reader(files[0]),csv.reader(files[1]),csv.reader(files[2]),csv.reader(files[3]),csv.reader(files[4])]
writers = [csv.writer(locations_csv),csv.writer(rentalPrice_csv)]
locations =  set()
rentalPrice = set()
dates_first_index = []
dates = []

#write headers
writers[0].writerow(('zip_code','city','state','metro','country_name'))
writers[1].writerow(('zip_code','bedrooms','size_rank','date','available','price'))

#find date starting indexes in all 5 csv files
for reader in readers:
	first_row = next(reader)
	i = 0
	while(first_row[i] != '2016-01'):
		i= i+1
	dates_first_index.append(i)

#find the dates from the file
foo = i
for i in range(25):
	dates.append(first_row[foo+i]+"-01")

zip_codes = []
bedrooms = 1
for reader in readers:
	for row in reader:
		locations.add(((row[0]).lstrip("0"),row[1],row[2],row[3],row[4]))
		zip_codes.append(row[0])
		for i in range(len(dates)):
			available = 'false'
			if(row[dates_first_index[bedrooms-1]+i]==''): available = 'true'
			rentalPrice.add((row[0],bedrooms,row[5],dates[i],available,row[dates_first_index[bedrooms-1]+i]))
	bedrooms = bedrooms +1

writers[0].writerows(locations)
writers[1].writerows(rentalPrice)

Databases - PostgreSQL/Project - Views , CSV file manipulation in Python/zillow.py


for _ in range(int(input())):
    N = int(input())
    bin_str = input()
    count_one = 0
    count_zero = 0
    for char in bin_str:
        if char == "0":
            count_zero += 1
        else:
            count_one += 1
    if N % 2 != 0:
        odd_ele = "0" if count_zero % 2 != 0 else "1"
        if odd_ele == "1":
            count_one -= 1
        else:
            count_zero -= 1
    if count_one % 2 == 0 and count_zero % 2 == 0:
        print("YES")
    elif count_zero == count_one:
        print("YES")
    else:
        print("NO")

"""
can be palindrome when
1. count of 1 and coutn of 0 is same
or
2. count of 0 and count of 1 is even
"""


#  BlackJack Project -> CapStone Project

import random;

def calculate_score(cards):
    if sum(cards) == 21 and len(cards) == 2:
        return 0;

    if 11 in cards and sum(cards) > 21:
        cards.remove(11)
        cards.append(1)

    return sum(cards);

def deal_cards():
    cards = [11,2,3,4,5,6,7,8,9,10,10,10,10];
    card = random.choice(cards)
    return card;

def compare_scores(user_score, comp_score):
    if user_score == comp_score:
        return "Draw"
    elif comp_score == 0:
        return "Lose! Opponent has BlackJack."
    elif user_score == 0:
        return "Wins! with a BlackJack"
    elif user_score > 21:
        return "You went Over. You Lose."
    elif comp_score > 21:
        return "Opponent went Over. You Win."
    elif user_score > comp_score:
        return "You Win"
    else:
        return "you Lose"

def play_game():
    user_cards = [];
    computer_cards = [];
    is_game_over = False

    for _ in range(2):
        new_card = deal_cards()
        user_cards.append(new_card)
        computer_cards.append(new_card)

    while not is_game_over:
        user_score = calculate_score(user_cards)
        computer_score = calculate_score(computer_cards)

        print(f"Your cards are {user_cards} and your score is {user_score}")
        print(f"computer first card is {computer_cards[0]}");
        if user_score == 0 or computer_score == 0 or user_score > 21:
            is_game_over = True;
        else:
            user_should_deal = input("Type 'y' for another card or 'n' for pass: ")
            if user_should_deal == 'y':
                user_cards.append(deal_cards())
            else:
                is_game_over = True;

    while computer_score != 0 and computer_score < 17:
        computer_cards.append(deal_cards())
        computer_score = calculate_score(computer_cards)

    print(f"Your cards are {user_cards} and Final score is {user_score}")
    print(f"Computer cards are {computer_cards} and Final score is {computer_score}")
    print(compare_scores(user_score, computer_score))

while input("Do you want to Playa game of BlackJack. Type 'y' to play: ") == 'y':
    play_game();


#!/usr/bin/env python

import os
import logging
from time import sleep
import miio
import paho.mqtt.client as mqtt

TOPICS = {}

def on_connect(client, userdata, flags, rc):
    if rc==0:
        client.is_connected=True
        logging.info('Connected')
    else:
        logging.error(f'Connection error, code={rc}')

def on_disconnect(client, userdata, rc):
    client.is_connected=False
    if rc==0:
        logging.info('Disconnected')
    else:
        logging.error(f'Disconected due to an error, code={rc}')

def main():
    logging.basicConfig(level=logging.INFO)

    ip = os.environ.get('MIROBO_IP')
    token = os.environ.get('MIROBO_TOKEN')

    vac = miio.Vacuum(ip, token)
    info = vac.info()
    device_identifier = info.mac_address.replace(':', '').lower()

    TOPICS['firmware_version'] = f'mirobo/status/{device_identifier}/firmware_version'
    TOPICS['battery'] = f'mirobo/status/{device_identifier}/battery'
    TOPICS['fanspeed'] = f'mirobo/status/{device_identifier}/fanspeed'
    TOPICS['is_on'] = f'mirobo/status/{device_identifier}/is_on'
    TOPICS['sensor_dirt_hours'] = f'mirobo/status/{device_identifier}/sensor_dirt_hours'
    TOPICS['filter_hours'] = f'mirobo/status/{device_identifier}/filter_hours'
    TOPICS['main_brush_hours'] = f'mirobo/status/{device_identifier}/main_brush_hours'
    TOPICS['side_brush_hours'] = f'mirobo/status/{device_identifier}/side_brush_hours'
    TOPICS['cleaning_summary_count'] = f'mirobo/status/{device_identifier}/cleaning_summary_count'
    TOPICS['cleaning_summary_total_area'] = f'mirobo/status/{device_identifier}/cleaning_summary_total_area'
    TOPICS['cleaning_summary_total_hours'] = f'mirobo/status/{device_identifier}/cleaning_summary_total_hours'

    mqtt.Client.is_connected=False
    client = mqtt.Client('mirobo')
    client.on_connect=on_connect
    client.on_disconnect=on_disconnect
    client.loop_start()
    client.connect('mosquitto', 1883, 60)
    while True:
        try:
            # device info
            publish(client, TOPICS['firmware_version'], info.firmware_version)

            # status
            status = vac.status()
            publish(client, TOPICS['battery'], float(status.battery))
            publish(client, TOPICS['fanspeed'], status.fanspeed)
            publish(client, TOPICS['is_on'], status.is_on)

            # consumables
            consumable_status = vac.consumable_status()
            publish(client, TOPICS['sensor_dirt_hours'], float(consumable_status.sensor_dirty.total_seconds() / 3600))
            publish(client, TOPICS['filter_hours'], float(consumable_status.filter.total_seconds() / 3600))
            publish(client, TOPICS['main_brush_hours'], float(consumable_status.main_brush.total_seconds() / 3600))
            publish(client, TOPICS['side_brush_hours'], float(consumable_status.side_brush.total_seconds() / 3600))

            # cleaning stats
            clean_history = vac.clean_history()
            publish(client, TOPICS['cleaning_summary_count'], float(clean_history.count))
            publish(client, TOPICS['cleaning_summary_total_area'], float(clean_history.total_area))
            publish(client, TOPICS['cleaning_summary_total_hours'], float(clean_history.total_duration.total_seconds() / 3600))
        except:
            logging.error("Error getting device status")
        sleep(5*60)

def publish(client, topic, payload):
    while not client.is_connected:
        logging.info('Waiting for connection')
        sleep(1)
    logging.info(f'Publishing {topic} {payload}')
    client.publish(topic, str(payload))

if __name__ == '__main__':
    main()


import requests
from bs4 import BeautifulSoup
import pandas as pd

# Send a GET request to the webpage
url = 'https://rivet.hepforge.org/analyses.html'
response = requests.get(url)

# Parse the HTML content using Beautiful Soup
soup = BeautifulSoup(response.text, 'html.parser')

# Find all links on the page
links = soup.find_all('a')

# Filter out only the links that lead to analysis pages
analysis_links = []
for link in links:
    href = link.get('href')
    if href and 'analyses/' in href:
        analysis_links.append(href)

# Print the list of analysis links
#print(analysis_links)

df = pd.DataFrame(data=[], columns=['Rivet ID', 'Analysis Name', 'Experiment Name', 'Inspire HEP Link', 'Inspire HEP ID'])

counter = 0
for link in analysis_links:
        # Send a GET request to the webpage
        url = 'https://rivet.hepforge.org/' + link
        response = requests.get(url)

        # Parse the HTML content using Beautiful Soup
        soup = BeautifulSoup(response.text, 'html.parser')

        # print(soup.prettify())

        # Find the div tag containing the Rivet Analysis link and extract its href attribute
        # rivet_analysis_div = soup.findAll(href=re.compile("rivet.hepforge.org/analyses"))

        try:
                rivet_id = soup.find("h3").text
        except:
                rivet_id = 'N/A'

        lst = soup.findAll('b')
        try:
                analysis_name = lst[0].text
        except:
                analysis_name = 'N/A'
        try:
                experiment_name = lst[1].next_sibling.strip()
        except:
                experiment_name = 'N/A'
        try:
                inspire_hep_link = lst[2].next_sibling.next_sibling['href']
        except:
                inspire_hep_link = 'N/A'
        try:
                inspire_hep_id = lst[2].next_sibling.next_sibling.text
        except:
                inspire_hep_id = 'N/A'

        # Create a dictionary with the attributes
        data = pd.DataFrame({'Rivet ID': rivet_id,
                'Analysis Name': analysis_name,
                'Experiment Name': experiment_name,
                'Inspire HEP Link': inspire_hep_link,
                'Inspire HEP ID': inspire_hep_id}, index=[0])

        # Create a DataFrame from the dictionary
        df = pd.concat([df, data], ignore_index=True)

        counter += 1
        print(counter)

df.to_csv('output.csv', index=False)


import threading
import time
a = 1
counter = 1
def factorial(start, end):
    """Возводит число в факториал"""
    global counter
    global a
    for i in range(start, end + 1):
        counter *= i
    print(str(a)," поток =",counter)       # Для проверки работы функций, использовать с маленькими
    a += 1                                 # числами желательно до 50

def threading_factorial(n,number_of_threads):
    """функция делит число на количество потоков и возводит в факториал"""
    threads = []
    f = n // number_of_threads
    a = f
    w = 1
    v = 0
    for i in range(1,n + 1):
        if n % number_of_threads == 0:
            if i == f:
                t = threading.Thread(target = factorial,args = (w, f))
                threads.append(t)
                t.start()
                w = f +1
                f += a
            else:
                continue
        else:
            if  n % number_of_threads != 0:
                if  i == f:
                    if v != number_of_threads - 2 :
                        t = threading.Thread(target = factorial,args = (w, f))
                        threads.append(t)
                        t.start()
                        w = f +1
                        f += a + 1
                        v += 1
                    else:
                        t = threading.Thread(target = factorial,args = (w, f))
                        threads.append(t)
                        t.start()
                        w = f +1
                        f = n
                        v += 1

                else:
                    continue
    for i in threads:
        i.join

def func_time(a,b):
    """а - с потоком, b без потоков"""
    if a < b:
        print("Функция с потоками выполняется быстрей на: " f'{b-a:.10f} "сек."')
    else:
        print("Функция без потоков выполняется быстрей на: " f'{a - b:.10f} "сек."')

start_t = time.time()
threading_factorial(1000,3)
counter = 1
a = 0
thread_time = time.time() -  start_t
print("Функция с потоками выполняется:"f'{thread_time:.4f} "сек."')

factorial_t = time.time()
factorial(1,1000) # jn 1 до числа вычесления
factorial_time = time.time() - factorial_t
print("Функция без потоков выполняется:"f'{factorial_time:.4f} "сек."\n')

func_time(thread_time,factorial_time)


class Attendee:
    def __init__(self, name, tickets):
        self.name = name
        self.tickets = tickets

    def displayAttendee(self):
        print(f"Name: {self.name}, Tickets:{self.tickets}")

    def addTicket(self):
        self.tickets += 1
        print(f"{self.name} tickets increased to {self.tickets}")

att1 = Attendee("Asmodeus", 666)
att2 = Attendee("Bahamat", 7)

att1.displayAttendee()
att2.displayAttendee()

att1.addTicket()
att1.displayAttendee()

att1.addTicket()
att1.displayAttendee()


"""
톱니바퀴 문제
Author : Donghak Park
"""

def move_gear(Nth, direct):
    global gear

    now_left = gear[Nth][6]
    now_right = gear[Nth][2]

    if direct == 1:
        temp = gear[Nth].pop()
        gear[Nth].insert(0, temp)
    else:
        temp = gear[Nth].pop(0)
        gear[Nth].append(temp)

    move_left(Nth - 1, direct * -1, now_left)
    move_right(Nth + 1, direct * -1, now_right)

def move_left(Nth, direct, now_left):
    global gear

    if Nth <= 0:
        return

    if now_left == gear[Nth][2]:
        return
    else:
        now_left = gear[Nth][6]

        if direct == 1:
            temp = gear[Nth].pop()
            gear[Nth].insert(0, temp)
        else:
            temp = gear[Nth].pop(0)
            gear[Nth].append(temp)

        move_left(Nth - 1, direct * -1, now_left)

def move_right(Nth, direct, now_right):
    global gear

    if Nth >= 5:
        return

    if now_right == gear[Nth][6]:
        return
    else:

        now_right = gear[Nth][2]
        if direct == 1:
            temp = gear[Nth].pop()
            gear[Nth].insert(0, temp)
        else:
            temp = gear[Nth].pop(0)
            gear[Nth].append(temp)

        move_right(Nth + 1, direct * -1, now_right)

# 2번이 오른쪽 6번이 왼쪽 N극이 0
gear = {}
answer = 0

for i in range(1, 5):
    gear[i] = list(map(int, list(input())))

K = int(input())

for _ in range(K):
    Nth, direct = map(int, input().split())
    move_gear(Nth, direct)

for key in gear.keys():
    if gear[key][0] == 1:
        answer += (2 ** (key - 1))

print(answer)


# prepared invocations and structures -----------------------------------------
import pycuda.driver as cuda
import pycuda.autoinit
import numpy
import struct
from pycuda.compiler import SourceModule

class DoubleOpStruct:
    mem_size = 8 + numpy.uintp(0).nbytes
    def __init__(self, array, struct_arr_ptr):
        self.data = cuda.to_device(array)
        self.shape, self.dtype = array.shape, array.dtype

        packed_args = struct.pack("ixP", array.size, numpy.uintp(self.data))
        cuda.memcpy_htod(struct_arr_ptr, packed_args)

    def __str__(self):
        return str(cuda.from_device(self.data, self.shape, self.dtype))

struct_arr = cuda.mem_alloc(2 * DoubleOpStruct.mem_size)
do2_ptr = int(struct_arr) + DoubleOpStruct.mem_size

array1 = DoubleOpStruct(numpy.array([1, 2, 3], dtype=numpy.float32), struct_arr)
array2 = DoubleOpStruct(numpy.array([0, 4], dtype=numpy.float32), do2_ptr)

print("original arrays")
print(array1)
print(array2)

mod = SourceModule("""
    struct DoubleOperation {
        int datalen, __padding; // so 64-bit ptrs can be aligned
        float *ptr;
    };

    __global__ void double_array(DoubleOperation *a)
    {
        a = a + blockIdx.x;
        for (int idx = threadIdx.x; idx < a->datalen; idx += blockDim.x)
        {
            float *a_ptr = a->ptr;
            a_ptr[idx] *= 2;
        }
    }
    """)
func = mod.get_function("double_array")
func(struct_arr, block=(32, 1, 1), grid=(2, 1))

print("doubled arrays")
print(array1)
print(array2)

func(numpy.uintp(do2_ptr), block=(32, 1, 1), grid=(1, 1))
print("doubled second only")
print(array1)
print(array2)

if cuda.get_version() < (4, ):
    func.prepare("P", block=(32, 1, 1))
    func.prepared_call((2, 1), struct_arr)
else:
    func.prepare("P")
    block = (32, 1, 1)
    func.prepared_call((2, 1), block, struct_arr)

print("doubled again")
print(array1)
print(array2)

if cuda.get_version() < (4, ):
    func.prepared_call((1, 1), do2_ptr)
else:
    func.prepared_call((1, 1), block, do2_ptr)

print("doubled second only again")
print(array1)
print(array2)


# multiAgents.py
# --------------
# Licensing Information:  You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.edu.
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).

from util import manhattanDistance
from game import Directions
import random
import util
import sys

from game import Agent

class ReflexAgent(Agent):
    """
    A reflex agent chooses an action at each choice point by examining
    its alternatives via a state evaluation function.

    The code below is provided as a guide.  You are welcome to change
    it in any way you see fit, so long as you don't touch our method
    headers.
    """

    def getAction(self, gameState):
        """
        You do not need to change this method, but you're welcome to.

        getAction chooses among the best options according to the evaluation function.

        Just like in the previous project, getAction takes a GameState and returns
        some Directions.X for some X in the set {NORTH, SOUTH, WEST, EAST, STOP}
        """
        # Collect legal moves and successor states
        legalMoves = gameState.getLegalActions()

        # Choose one of the best actions
        scores = [self.evaluationFunction(
            gameState, action) for action in legalMoves]
        bestScore = max(scores)
        bestIndices = [index for index in range(
            len(scores)) if scores[index] == bestScore]
        # Pick randomly among the best
        chosenIndex = random.choice(bestIndices)

        "Add more of your code here if you want to"

        return legalMoves[chosenIndex]

    def evaluationFunction(self, currentGameState, action):
        """
        Design a better evaluation function here.

        The evaluation function takes in the current and proposed successor
        GameStates (pacman.py) and returns a number, where higher numbers are better.

        The code below extracts some useful information from the state, like the
        remaining food (newFood) and Pacman position after moving (newPos).
        newScaredTimes holds the number of moves that each ghost will remain
        scared because of Pacman having eaten a power pellet.

        Print out these variables to see what you're getting, then combine them
        to create a masterful evaluation function.
        """
        # Useful information you can extract from a GameState (pacman.py)
        successorGameState = currentGameState.generatePacmanSuccessor(action)
        newPos = successorGameState.getPacmanPosition()
        newFood = successorGameState.getFood()
        newGhostStates = successorGameState.getGhostStates()
        newScaredTimes = [ghostState.scaredTimer for ghostState in newGhostStates]
        #print(successorGameState)
        #print(newPos)
        #print(newFood)
        #print('---------------------')
        #for ghostState in newGhostStates:
        #    print(ghostState)
        #print(newScaredTimes)

        "*** YOUR CODE HERE ***"
        #Nos interesa lograr la puntuación más elevada de cada movimiento para elegir siempre la que más aporte
        #por lo que cuanto más comamos, más alejados de los fantasmas estemos mejor

       #Variable que vamos a devolver
        resultado = 0

        #Comprobar que hemos comido comida
        listaComidaSucesor = newFood.asList() #lista de comidas para un estado sucesor
        listaComidaActual = currentGameState.getFood().asList() #lista de comida del estado actual

        if(len(listaComidaActual) > len(listaComidaSucesor)): #significa que hemos comido 1 comida en la transicion del estado actual al sucesor, añadimos 100 puntos
            resultado = resultado + 500

        #Haremos lo mismo para los puntos grandes
        listaPuntosSucesor = successorGameState.getCapsules()
        listaPuntosActual = currentGameState.getCapsules()

        if(len(listaPuntosActual) > len(listaPuntosSucesor)): #significa que hemos comido punto
            resultado = resultado + 500

        #Tambien nos interesa estar alejados de los fantasmas, por lo que una distancia cercana a un fantasma nos bajará puntos
        #conseguimos las distancias a los fantasmas
        distanciaFantasmas = []
        for ghostState in newGhostStates:
            if ghostState.scaredTimer == 0: #solo nos queremos alejar si el fantasma no está asustado
                distancia = manhattanDistance(ghostState.getPosition(), newPos)
                distanciaFantasmas.append(distancia)

        for distancia in distanciaFantasmas: #penalizaremos mucho el estar a menos de 4 (distancia manhattan) de un fantasma
            if distancia < 4:
                resultado = resultado - 1000

        #Muchas veces el pacman se queda quieto así que restaremos puntos por ello
        if action == 'Stop':
            resultado = resultado - 100

        #Como nos interesa ganar daremos muchos puntos por ello
        if successorGameState.isWin():
           resultado = resultado + sys.maxsize

         #Como no nos interesa perder quitaremos muchos puntos por ello
        if successorGameState.isLose():
           resultado = resultado - sys.maxsize

        #Probando hasta aquí me he dado cuenta que no se premia el acercarse a la comida y eso hace que el pacman no se acerce a por ella
        comidaMasCercana = sys.maxsize
        for comida in newFood.asList():
            comidaMasCercana = min(comidaMasCercana, manhattanDistance(comida, newPos))
        resultado = resultado + 1000 - comidaMasCercana

        return resultado

def scoreEvaluationFunction(currentGameState):
    """
    This default evaluation function just returns the score of the state.
    The score is the same one displayed in the Pacman GUI.

    This evaluation function is meant for use with adversarial search agents
    (not reflex agents).
    """
    return currentGameState.getScore()

class MultiAgentSearchAgent(Agent):
    """
    This class provides some common elements to all of your
    multi-agent searchers.  Any methods defined here will be available
    to the MinimaxPacmanAgent, AlphaBetaPacmanAgent & ExpectimaxPacmanAgent.

    You *do not* need to make any changes here, but you can if you want to
    add functionality to all your adversarial search agents.  Please do not
    remove anything, however.

    Note: this is an abstract class: one that should not be instantiated.  It's
    only partially specified, and designed to be extended.  Agent (game.py)
    is another abstract class.
    """

    def __init__(self, evalFn='scoreEvaluationFunction', depth='2'):
        self.index = 0  # Pacman is always agent index 0
        self.evaluationFunction = util.lookup(evalFn, globals())
        self.depth = int(depth)

class MinimaxAgent(MultiAgentSearchAgent):
    """
    Your minimax agent (question 2)
    """

    def maximizar(self, gameState, depth):
        profundidadActual = depth + 1
        index = 0 #sabemos que siempre que maximicemos será con el pacman, que tiene índice 0
        if(gameState.isLose() or gameState.isWin() or profundidadActual == self.depth): #si se cumple alguna de las condiciones se devuelve el valor
            return self.evaluationFunction(gameState)
        v = -sys.maxsize #como dice la teoria, inicializamos v a menos infinito
        accionesPosibles = gameState.getLegalActions(index) #vemos que movimientos posibles tiene el pacman
        for accion in accionesPosibles:
            sucesor = gameState.generateSuccessor(index, accion) #generamos los estados sucesores con las acciones
            v = max(v, self.minimizar(sucesor, profundidadActual, index+1))
        return v

    def minimizar(self, gameState, depth, index):
        if(gameState.isLose() or gameState.isWin()): #no comprobamos la profundidad porque ya se ha dado la maximización
            return self.evaluationFunction(gameState)
        v = sys.maxsize
        accionesPosibles = gameState.getLegalActions(index)
        for accion in accionesPosibles:
            sucesor = gameState.generateSuccessor(index, accion)
            numeroAgentes = gameState.getNumAgents()-1
            if(index == numeroAgentes): #el fantasma que está jugando es el último, y el siguiente es el pacman
                v = min(v, self.maximizar(sucesor, depth))
            else: #todavía quedan más fantasmas por jugar
                v = min(v, self.minimizar(sucesor, depth, index+1))
        return v

    def accion_raiz(self, gameState):
        index = 0 #indice del pacman, que es el que toma la accion
        accionesLegales = gameState.getLegalActions(index)
        accionQueEjecuta = None
        v = -sys.maxsize
        for accion in accionesLegales:
            sucesor = gameState.generateSuccessor(index,accion)
            puntuacion = self.minimizar(sucesor,0,1) #la siguente acción al root es un fantasma que minimiza
            if(v < puntuacion): #buscamos cual de los sucesores nos devuelve un mayor valor
                v = puntuacion
                accionQueEjecuta = accion
        return accionQueEjecuta

    def getAction(self, gameState):
        """
        Returns the minimax action from the current gameState using self.depth
        and self.evaluationFunction.

        Here are some method calls that might be useful when implementing minimax.

        gameState.getLegalActions(agentIndex):
        Returns a list of legal actions for an agent
        agentIndex=0 means Pacman, ghosts are >= 1

        gameState.generateSuccessor(agentIndex, action):
        Returns the successor game state after an agent takes an action

        gameState.getNumAgents():
        Returns the total number of agents in the game

        gameState.isWin():
        Returns whether or not the game state is a winning state

        gameState.isLose():
        Returns whether or not the game state is a losing state
        """
        "*** YOUR CODE HERE ***"

        return self.accion_raiz(gameState)

class AlphaBetaAgent(MultiAgentSearchAgent):
    """
    Your minimax agent with alpha-beta pruning (question 3)
    """

    def maximizar(self, gameState, depth, alfa, beta):
        profundidadActual = depth + 1
        index = 0 #sabemos que siempre que maximicemos será con el pacman, que tiene índice 0
        if(gameState.isLose() or gameState.isWin() or profundidadActual == self.depth): #si se cumple alguna de las condiciones se devuelve el valor
            return self.evaluationFunction(gameState)
        v = -sys.maxsize #como dice la teoria, inicializamos v a menos infinito
        accionesPosibles = gameState.getLegalActions(index) #vemos que movimientos posibles tiene el pacman
        for accion in accionesPosibles:
            sucesor = gameState.generateSuccessor(index, accion) #generamos los estados sucesores con las acciones
            v = max(v, self.minimizar(sucesor, profundidadActual, index+1, alfa, beta))
            if(v > beta): #no podemos poner 'v >= beta' porque el enunciado dice que no hay que podar en caso de igualdad
                return v
            alfa = max(alfa, v)
        return v

    def minimizar(self, gameState, depth, index, alfa, beta):
        if(gameState.isLose() or gameState.isWin()): #no comprobamos la profundidad porque ya se ha dado la maximización
            return self.evaluationFunction(gameState)
        v = sys.maxsize
        accionesPosibles = gameState.getLegalActions(index)
        for accion in accionesPosibles:
            sucesor = gameState.generateSuccessor(index, accion)
            numeroAgentes = gameState.getNumAgents()-1
            if(index == numeroAgentes): #el fantasma que está jugando es el último, y el siguiente es el pacman
                v = min(v, self.maximizar(sucesor, depth, alfa, beta))
                if(v < alfa): #no podemos poner 'v <= alfa' porque el enunciado dice que no hay que podar en caso de igualdad
                    return v
                beta = min(beta, v)
            else: #todavía quedan más fantasmas por jugar
                v = min(v, self.minimizar(sucesor, depth, index+1, alfa, beta))
                if(v < alfa): #no podemos poner 'v <= alfa' porque el enunciado dice que no hay que podar en caso de igualdad
                    return v
                beta = min(beta, v)
        return v

    def accion_raiz(self, gameState):
        index = 0 #indice del pacman, que es el que toma la accion
        accionesLegales = gameState.getLegalActions(index)
        accionQueEjecuta = None
        v = -sys.maxsize
        alfa = -sys.maxsize #como nos dice la teoria inicializamos los valore alfa
        beta = sys.maxsize # y beta que irán propagandose a sus nodos hijos
        for accion in accionesLegales:
            sucesor = gameState.generateSuccessor(index,accion)
            puntuacion = self.minimizar(sucesor, 0, 1, alfa, beta) #la siguente acción al root es un fantasma que minimiza
            if(v < puntuacion): #buscamos cual de los sucesores nos devuelve un mayor valor
                v = puntuacion
                accionQueEjecuta = accion
            if(v > beta): #no podemos poner 'v >= beta' porque el enunciado dice que no hay que podar en caso de igualdad
                return accionQueEjecuta
            alfa = max(alfa, v)
        return accionQueEjecuta

    def getAction(self, gameState):
        """
        Returns the minimax action using self.depth and self.evaluationFunction
        """
        "*** YOUR CODE HERE ***"
        return self.accion_raiz(gameState)

class ExpectimaxAgent(MultiAgentSearchAgent):
    """
      Your expectimax agent (question 4)
    """

    def maximizar(self, gameState, depth):
        profundidadActual = depth + 1
        index = 0 #sabemos que siempre que maximicemos será con el pacman, que tiene índice 0
        if(gameState.isLose() or gameState.isWin() or profundidadActual == self.depth): #si se cumple alguna de las condiciones se devuelve el valor
            return self.evaluationFunction(gameState)
        v = -sys.maxsize #como dice la teoria, inicializamos v a menos infinito
        accionesPosibles = gameState.getLegalActions(index) #vemos que movimientos posibles tiene el pacman
        for accion in accionesPosibles:
            sucesor = gameState.generateSuccessor(index, accion) #generamos los estados sucesores con las acciones
            v = max(v, self.value(sucesor, profundidadActual, index+1))
        return v

    def value(self, gameState, depth, index):
        if(gameState.isLose() or gameState.isWin()): #no comprobamos la profundidad porque ya se ha dado la maximización
            return self.evaluationFunction(gameState)
        v = 0 #para expectimax se inicializa v=0 en la parte probabilística
        accionesPosibles = gameState.getLegalActions(index)
        numeroSucesores = len(accionesPosibles)
        probabilidad = 1/numeroSucesores
        for accion in accionesPosibles:
            sucesor = gameState.generateSuccessor(index, accion)
            numeroAgentes = gameState.getNumAgents()-1
            if(index == numeroAgentes): #el fantasma que está jugando es el último, y el siguiente es el pacman
                v += self.maximizar(sucesor, depth) #si soy un fantasma voy a coger el mayor valor que dejen por debajo, porque no soy experto
            else: #todavía quedan más fantasmas por jugar
                v += self.value(sucesor, depth, index+1)
        return(v * probabilidad)

    def accion_raiz(self, gameState):
        index = 0 #indice del pacman, que es el que toma la accion
        accionesLegales = gameState.getLegalActions(index)
        accionQueEjecuta = None
        v = -sys.maxsize
        for accion in accionesLegales:
            sucesor = gameState.generateSuccessor(index,accion)
            puntuacion = self.value(sucesor, 0, 1) #la siguente acción al root es un fantasma que minimiza
            if(v < puntuacion): #buscamos cual de los sucesores nos devuelve un mayor valor
                v = puntuacion
                accionQueEjecuta = accion
        return accionQueEjecuta

    def getAction(self, gameState):
        """
        Returns the expectimax action using self.depth and self.evaluationFunction

        All ghosts should be modeled as choosing uniformly at random from their
        legal moves.
        """
        "*** YOUR CODE HERE ***"
        return self.accion_raiz(gameState)

def betterEvaluationFunction(currentGameState):
    """
    Your extreme ghost-hunting, pellet-nabbing, food-gobbling, unstoppable
    evaluation function (question 5).

    DESCRIPTION: <write something here so we know what you did>
    """
    "*** YOUR CODE HERE ***"

    #Variable que vamos a devolver
    resultado = 0

    posicionActual = currentGameState.getPacmanPosition()
    listaComidas = currentGameState.getFood().asList()
    listaPuntos = currentGameState.getCapsules()

    #Podemos añadir una lista de comidas ya comidas
    listaYaComidas = currentGameState.getFood().asList(False)

    #Calcularemos primero las distancias a los fantasmas del estado actual y el sucesor

    #Estado actual

    #Posiciones actuales de los fantasmas
    posicionesFastasmasActuales = []
    for fantasma in currentGameState.getGhostStates():
        posFantasma = fantasma.getPosition()
        posicionesFastasmasActuales.append(posFantasma)

    #Distancia a cada fantasma del estado actual desde la posición de pacman
    distanciaFantasmasActual = []
    for posFantasma in posicionesFastasmasActuales:
        distancia = manhattanDistance(posicionActual, posFantasma)
        distanciaFantasmasActual.append(distancia)

    #Calculamos también las distancias a las comidas
    distanciaComidas = []
    for comida in listaComidas:
        distancia = manhattanDistance(posicionActual, comida)
        distanciaComidas.append(distancia)

    resultado = resultado + currentGameState.getScore() + len(listaYaComidas) #añadimos al resultado el número de comidas ya tragadas

    #Ahora vamos a diferenciar dos casos, los fantasmas asustados y los fantasmas no asustados
    estadoFantasmas = currentGameState.getGhostStates()
    contadoresAsustados = [ghostState.scaredTimer for ghostState in estadoFantasmas]

    fantasmasAsustados = sum(contadoresAsustados) #si es mayor a 0 significa que hay fantasmas asustados
    distanciaTotalFanstasmas = sum(distanciaFantasmasActual)

    if(fantasmasAsustados > 0): #significa que hay fantasmas asustados
        resultado = resultado + fantasmasAsustados - distanciaTotalFanstasmas #restaremos por estar alejado de los fantasmas
    else:
        resultado = resultado + distanciaTotalFanstasmas

    #Ademas podemos añadir que en el caso de que haya fantasmas asustados se reste por cada punto grande no comido y viceversa

    if(fantasmasAsustados > 0): #significa que hay fantasmas asustados
        resultado = resultado - len(listaPuntos)
    else:
        resultado = resultado + len(listaPuntos)

    return resultado
    util.raiseNotDefined()

# Abbreviation
better = betterEvaluationFunction


###
###    This file is part of Pyffle BBS.
###
###    Pyffle BBS is free software: you can redistribute it and/or modify
###    it under the terms of the GNU General Public License as published by
###    the Free Software Foundation, either version 3 of the License, or
###    (at your option) any later version.
###
###    Pyffle BBS is distributed in the hope that it will be useful,
###    but WITHOUT ANY WARRANTY; without even the implied warranty of
###    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
###    GNU General Public License for more details.
###
###    You should have received a copy of the GNU General Public License
###    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
###
###

## Models for SqlAlchemy version 6
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relation, backref
from sqlalchemy import *
from sqlalchemy.dialects.postgresql import *
from sqlalchemy.orm import sessionmaker
from pyffle_tables import *
from pyffle_data import *
import pyffle_editor
from datetime import datetime
import sys
import getpass
import os
import tempfile

def getIdentity():
	return "pyffle_inspector v0.01"

## Returns True if the version of pyffle is compatible this version of module
def confirmVersion(version):
	return True

class PyffleModule:
	currentUser = None
	data = None

	def eventDispatched(self, event):
		pass

	def indent(self,n):
		for i in range(1,n):
			self.data.util.printn("  ")

	def printAce(self, aces,indent):
		self.data.util.printn("%s=>%s " % (aces[0], aces[1]))

	def	printJoins(self,username,indent):
		self.indent(indent)
		self.data.util.println("^JOIN^ %s" % (str(self.data.getJoinedBoardids(username=username))))

	def printAcl(self, aclid, indent):
		msgAcl = self.data.getAcl(aclid)
		self.indent(indent)
		self.data.util.println("^ACL^ %s (%s)" % (msgAcl.id,msgAcl.description))

		grants = self.data.getAces(aclid,"GRANT")
		denies = self.data.getAces(aclid,"DENY")

		self.indent(indent)
		self.data.util.printn("  ^GRANT^: ")

		for grant in grants:
			self.printAce(grant,indent+1)
		self.data.util.println(" ")

		self.indent(indent)
		self.data.util.printn("  ^DENY^: ")
		for deny in denies:
			self.printAce(deny,indent+1)
		self.data.util.println(" ")

	def printMsg(self, msgid, indent):
		msg = self.data.getMessage(msgid)
		self.indent(indent)
		board = self.data.getBoard(msg.boardid)
		self.data.util.println("^MSG^ %s %s -> %s (%s) in %s" % (msg.id,msg.fromname,msg.toname,msg.subject,board.name))
		aclid = msg.aclid
		self.printAcl(aclid,indent + 1)

	def printUser(self, username):
		self.data.util.cls()
		user = self.data.getUser(username)
		self.data.util.println("^USER^ " + username)
		self.printAcl(user.aclid, 2)
		self.printJoins(username, 2)
		msgids = self.data.getMessagesAuthoredByUser(username)
		for msgid in msgids:
			self.printMsg(msgid, 2)

	def printBoard(self, boardname):
		self.data.util.cls()
		board = self.data.getBoardByName(boardname)
		self.data.util.println("^BOARD^ " + boardname)
		self.printAcl(board.aclid, 2)
		msgids = self.data.getMessagesByBoardname(boardname)
		for msgid in msgids:
			self.printMsg(msgid, 2)

	def go(self, command, args):
		if command == "iuser":
			self.data.stateChange("inspector_iuserstart")
			username = args[1].strip()
			self.printUser(username)
			self.data.stateChange("inspector_iuserend")

		if command == "iboard":
			self.data.stateChange("inspector_iboardstart")
			name = args[1].strip()
			self.printBoard(name)
			self.data.stateChange("inspector_iboardend")


# Sequência de Fibonacci.

def fibNumero(item):
    f1 = f2 = 1
    while item>2:
        buffer = f2
        f2 = f1 + f2
        f1 = buffer
        item -=1
    return f2

def fibSequencia(item):
    f1 = f2 = 1
    print(f1,f2,end=' ')
    while item > 2 :
        buffer = f2
        f2 = f1+ f2
        f1 = buffer
        print(f2,end=' ')
        item -= 1
    print()

n = int(input("Digite um número"))

m = fibNumero(n)

print(m)

fibSequencia(n)


retangulos = []

def setup():
    size(600, 600) # área de desenho
    rectMode(CENTER)
    tamanho = 60
    for j in range(10):
        y = j * tamanho + tamanho / 2
        for i in range(10):
            x = i * tamanho + tamanho / 2
            for k in range(30):
                tam_sorteado = random(10, 60)
                cor = color(random(256), 100)
                # rect(x, y, tam_sorteado, tam_sorteado)
                retangulos.append((x, y, tam_sorteado, cor))

def draw():
    #background(200) # cor de fundo
    for x, y, tam, cor in reversed(retangulos):
        if dist(x, y, mouseX, mouseY) > tam / 2:
            fill(cor)
        else:
            fill(255, 0, 0, 100)
        rect(x, y, tam, tam)


import csv
game_scores = []

with open("2023_season.csv", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        if row["away_score"] and row["away_team"] and row["home_score"] and row["home_team"]:
            game_scores.append(row)
            game_scores[-1]["home_score"] = int(game_scores[-1]["home_score"])
            game_scores[-1]["away_score"] = int(game_scores[-1]["away_score"])
            game_scores[-1]["week"] = int(game_scores[-1]["week"])

# If you want to loop over every game, you do this:
for game in game_scores:
    # each game is a dictionary.  A dictionary maps keys to values
    # the Game dictionary contains keys such as "away_team", "home_team"
    # "home_score", "away_score", and "week"
    print(game)

# question: How many points have been scored by home teams so far this year?
# Here is how we would figure it out
home_points = 0
for game in game_scores:
    home_points += game["home_score"] # += adds the number on the left to the one on the right
print("total home points scored", home_points)

# Question: How many points have been scored by away teams?
# The code for figuring this out will look very similar to the code
# for finding the total home points
away_points = 0

# Bonus: How many games were won by home teams? How many games were
# won by away teams? You will need to use an if statement for this one.
home_wins = 0
away_wins = 0


from itertools import combinations

def isPrime(x ,y, z) :
    sum = x+y+z

    for i in range(2, sum) :
        if sum % i == 0 :
            return False

    return True

def solution(nums):
    answer = 0
    arr = list(combinations(nums, 3))
    # 갓... combinations 너무 사랑함
    for i in arr:
        if isPrime(i[0], i[1], i[2]) :
            answer+=1
    return answer


import winsound

a = {'1': 'jedan',
     '2': 'dva',
     '3': 'tri',
     '4': 'cetiri',
     '5': 'pet',
     '6': 'sest',
     '7': 'sedam',
     '8': 'osam',
     '9': 'devet',
     '10': 'deset',
     '11': 'jedanaest',
     '12': 'dvanaest',
     '13': 'trinaest',
     '14': 'cetrnaest',
     '15': 'petnaest',
     '16': 'sesnaest',
     '17': 'sedamnaest',
     '18': 'osamnaest',
     '19': 'devetnaest',
     '20': 'dvadeset',
     '30': 'trideset',
     '40': 'cetrdeset',
     '50': 'pedeset',
     '60': 'sezdeset',
     '70': 'sedamdeset',
     '80': 'osamdeset',
     '90': 'devedeset',
     '100': 'sto',
     '200': 'dvjesto',
     '300': 'tristo',
     '400': 'cetristo',
     '500': 'petsto',
     '600': 'setsto',
     '700': 'sedamsto',
     '800': 'osamsto',
     '900': 'devetsto',
     '0': ''}

wordedNumber = []
number = input()
numberLength = len(number)
number = int(number)
billion = number // 1000000000
million = (number // 1000000) % 1000
thousand = (number // 1000) % 1000
remainder = number % 1000

if billion > 0:
    if billion == 1:
        wordedNumber.extend(('jedna', 'milijarda'))
    if billion == 2 or billion == 3 or billion == 4:
        wordedNumber.extend((str(billion), 'milijarde'))
    if billion > 4:
        wordedNumber.extend((str(billion), 'milijardi'))

if million > 0:
    hundredMillion = million // 100 * 100
    if hundredMillion > 0:
        wordedNumber.append(str(hundredMillion))
    if (million // 10) % 10 == 1:
        tenMillion = str(million % 100)
        wordedNumber.extend((tenMillion, 'miliona'))
    else:
        tenMillion = (million // 10) % 10
        tenMillion = tenMillion * 10
        if tenMillion > 0:
            wordedNumber.append(str(tenMillion))
        oneMillion = million % 10
        if oneMillion > 0:
            wordedNumber.append(str(oneMillion))
            if oneMillion == 1:
                wordedNumber.append('milion')
            if oneMillion > 1 and oneMillion < 5:
                wordedNumber.append('miliona')
            if oneMillion > 4:
                wordedNumber.append('miliona')
        if oneMillion == 0:
            wordedNumber.append('miliona')

if thousand > 0:
    hundredThousand = thousand // 100 * 100
    if hundredThousand > 0:
        wordedNumber.append(str(hundredThousand))
    if (thousand // 10) % 10 == 1:
        tenThousand = str(thousand % 100)
        wordedNumber.extend((tenThousand, 'hiljada'))
    else:
        tenThousand = (thousand // 10) % 10
        tenThousand = tenThousand * 10
        if tenThousand > 0:
            wordedNumber.append(str(tenThousand))
        oneThousand = thousand % 10
        if oneThousand > 0:
            if oneThousand == 1:
                wordedNumber.extend(('jedna', 'hiljada_z'))
            if oneThousand > 1 and oneThousand < 5:
                wordedNumber.extend((str(oneThousand), 'hiljade'))
            if oneThousand > 4:
                wordedNumber.extend((str(oneThousand), 'hiljada'))
        if oneThousand == 0:
            wordedNumber.append('hiljada')

if remainder > 0:
    hundredRemainder = remainder // 100 * 100
    if hundredRemainder > 0:
        wordedNumber.append(str(hundredRemainder))
    if (remainder // 10) % 10 == 1:
        tenRemainder = str(remainder % 100)
        wordedNumber.append(tenRemainder)
    else:
        tenRemainder = (remainder // 10) % 10
        tenRemainder = tenRemainder * 10
        if tenRemainder > 0:
            wordedNumber.append(str(tenRemainder))
        oneRemainder = remainder % 10
        if oneRemainder > 0:
            wordedNumber.append(str(oneRemainder))

for i in range(len(wordedNumber)):
    if wordedNumber[i] in a:
        winsound.PlaySound(a[wordedNumber[i]] + ".wav", winsound.SND_FILENAME)
    else:
        winsound.PlaySound(wordedNumber[i] + ".wav", winsound.SND_FILENAME)


k = int(input())
p = input()

inps = []
i = 0
while i < k:
    inps.append(input())
    i += 1

c = 0
i = 0
while i < k:
    inp = inps[i]
    inp_len = len(inp)
    ch = p[i]
    index = inp.index(ch)
    if index > inp_len / 2:
        index = inp_len - index
    c += index
    i += 1
print(c)


import os, sys
from utils import showStatus, clear, output, manualMode
from branch_utils import extraOptions, stepOptions, types, getIndexedBranches, commonCmdLoop, createNewBranch

# Start the command loop
def branch_tool():
  tool_on = True
  while tool_on:
    # Process arguments
    mode = input("""
Choose a mode:

(ck)eckout mode: Checkout a branch
(n)ew branch mode: Create a new branch
(d)elete mode: Delete a branch

Extras:
Include ~ in front of your command to execute any command
(t) git status
(e)xit tool
(q)uit

:""")

    if mode == "e":
      clear()
      tool_on = False
    elif mode == "q":
      clear()
      sys.exit()
    elif mode == "t":
      clear()
      showStatus()
    elif mode == "ck":
      commonCmdLoop(
        "Choose a branch to checkout",
        "git checkout"
      )
    elif mode == "n":
      createNewBranch()
    elif mode == "d":
      commonCmdLoop(
        "Choose a branch to delete",
        "git branch -D"
      )
    else:
      manualMode(mode)


from django.db import models
from django.utils.translation import gettext_lazy as _

# Create your models here.

class BasePrescription(models.Model):
    """Абстрактная базовая модель назначения врача."""

    medicine_card = models.ForeignKey(
        "medicine_cards.medicinecard",
        on_delete=models.DO_NOTHING,
        related_name="%(class)s",
        verbose_name=_("Медицинская карта"),
    )
    pacient = models.ForeignKey(
        "pacients.pacient",
        on_delete=models.DO_NOTHING,
        verbose_name=_("Пациент"),
        related_name="%(class)s",
        null=True,
    )
    doctor = models.ForeignKey(
        "doctors.doctor",
        on_delete=models.DO_NOTHING,
        related_name="%(class)s",
        verbose_name=_("Врач"),
    )
    doctor_appointment = models.ForeignKey(
        "appointments.doctorappointment",
        on_delete=models.DO_NOTHING,
        related_name="%(class)s",
        verbose_name=_("Прием врача"),
    )

    class Meta:
        abstract = True

class Prescription(BasePrescription):
    """Абстрактная модель назначения врача."""

    duration = models.PositiveIntegerField(_("Продолжительность"))
    rate = models.PositiveIntegerField(_("Частота"))
    number = models.FloatField(_("Количество"))
    per = models.CharField(
        _("Единица измерения частоты"),
        help_text="День, неделя, месяц, час",
        max_length=20,
    )

    class Meta:
        abstract = True

class MedicinePrescription(Prescription):
    """Модель назначения медикаментов."""

    medicine = models.ForeignKey(
        "medicines.medicine",
        on_delete=models.DO_NOTHING,
        related_name="medicine_prescriptions",
        verbose_name=_("Медикамент"),
    )

    class Meta:
        verbose_name = "Назначение медикаментов"
        verbose_name_plural = "Назначения медикаментов"

    def __str__(self) -> str:
        return "{} для {}".format(self.Meta.verbose_name, self.medicine_card.pacient)

class ProcedurePrescription(Prescription):
    """Модель назначения процедур."""

    procedure = models.ForeignKey(
        "procedures.procedure",
        on_delete=models.DO_NOTHING,
        related_name="procedure_prescriptions",
        verbose_name=_("Процедура"),
    )

    class Meta:
        verbose_name = "Назначение процедуры"
        verbose_name_plural = "Назначения процедур"

    def __str__(self) -> str:
        return "{} для {}".format(self.Meta.verbose_name, self.medicine_card.pacient)

class AnalisisPrescription(BasePrescription):
    """Модель назначения анализа."""

    analisis = models.ForeignKey(
        "analisis.analysis",
        on_delete=models.DO_NOTHING,
        related_name="analisis_prescriptions",
        verbose_name=_("Анализ"),
    )

    class Meta:
        verbose_name = "Назначение анализа"
        verbose_name_plural = "Назначения анализов"

    def __str__(self) -> str:
        return "{} для {}".format(self.Meta.verbose_name, self.medicine_card.pacient)


# This file is part of Fail2Ban.
#
# Fail2Ban is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Fail2Ban is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Fail2Ban; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

# Author: Cyril Jaquier
#
# $Revision$

__author__ = "Cyril Jaquier"
__version__ = "$Revision$"
__date__ = "$Date$"
__copyright__ = "Copyright (c) 2004 Cyril Jaquier"
__license__ = "GPL"

from faildata import FailData
from ticket import FailTicket
from threading import Lock
import logging

# Gets the instance of the logger.
logSys = logging.getLogger("fail2ban.filter")

class FailManager:

	def __init__(self):
		self.__lock = Lock()
		self.__failList = dict()
		self.__maxRetry = 3
		self.__maxTime = 600
		self.__failTotal = 0

	def setFailTotal(self, value):
		try:
			self.__lock.acquire()
			self.__failTotal = value
		finally:
			self.__lock.release()

	def getFailTotal(self):
		try:
			self.__lock.acquire()
			return self.__failTotal
		finally:
			self.__lock.release()

	def setMaxRetry(self, value):
		try:
			self.__lock.acquire()
			self.__maxRetry = value
		finally:
			self.__lock.release()

	def getMaxRetry(self):
		try:
			self.__lock.acquire()
			return self.__maxRetry
		finally:
			self.__lock.release()

	def setMaxTime(self, value):
		try:
			self.__lock.acquire()
			self.__maxTime = value
		finally:
			self.__lock.release()

	def getMaxTime(self):
		try:
			self.__lock.acquire()
			return self.__maxTime
		finally:
			self.__lock.release()

	def addFailure(self, ticket):
		try:
			self.__lock.acquire()
			ip = ticket.getIP()
			unixTime = ticket.getTime()
			if self.__failList.has_key(ip):
				fData = self.__failList[ip]
				if fData.getLastReset() < unixTime - self.__maxTime:
					fData.setLastReset(unixTime)
					fData.setRetry(0)
				fData.inc()
				fData.setLastTime(unixTime)
			else:
				fData = FailData()
				fData.inc()
				fData.setLastReset(unixTime)
				fData.setLastTime(unixTime)
				self.__failList[ip] = fData
			self.__failTotal += 1
		finally:
			self.__lock.release()

	def size(self):
		try:
			self.__lock.acquire()
			return len(self.__failList)
		finally:
			self.__lock.release()

	def cleanup(self, time):
		try:
			self.__lock.acquire()
			tmp = self.__failList.copy()
			for item in tmp:
				if tmp[item].getLastTime() < time - self.__maxTime:
					self.__delFailure(item)
		finally:
			self.__lock.release()

	def __delFailure(self, ip):
		if self.__failList.has_key(ip):
			del self.__failList[ip]

	def toBan(self):
		try:
			self.__lock.acquire()
			for ip in self.__failList:
				data = self.__failList[ip]
				if data.getRetry() >= self.__maxRetry:
					self.__delFailure(ip)
					# Create a FailTicket from BanData
					failTicket = FailTicket(ip, data.getLastTime())
					failTicket.setAttempt(data.getRetry())
					return failTicket
			raise FailManagerEmpty
		finally:
			self.__lock.release()

class FailManagerEmpty(Exception):
	pass