import argparse
import gzip
import os
import requests

def parse_arguments():
  """Parses command line arguments."""
  parser = argparse.ArgumentParser()
  parser.add_argument("source_url",
                      type=str,
                      metavar="<source-url>",
                      help="Source URL to download")
  parser.add_argument("-o",
                      "--output",
                      type=str,
                      required=True,
                      metavar="<output-file>",
                      help="Output file path")
  return parser.parse_args()

def main(args):
  output_dir = os.path.dirname(args.output)

  if not os.path.isdir(output_dir):
    os.makedirs(output_dir)

  response = requests.get(args.source_url)
  if response.status_code != 200:
    raise requests.RequestException(
        f"Failed to download file with status code {response.status_code}")

  data = response.content
  if args.source_url.endswith(".gz"):
    data = gzip.decompress(data)

  with open(args.output, "wb") as f:
    f.write(data)

if __name__ == "__main__":
  main(parse_arguments())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 19 20:35:53 2019

@author: maxime
"""
from datetime import date
import pandas as pd

from .base import CyclingInitBot, PyItem, Race
from .data import calendar_list

class ChampListCreator(CyclingInitBot):
    def __init__(
            self,
            man_or_woman:str,
            start_year:int,
            actualize:bool):
        '''
        Perform queries in wikidata to find out the national champions for all years. It is saved in a csv file.
        It is a kind of cashing of this queries, as it would too long to perform it every time it is needed.

        Parameters
        ----------
        man_or_woman : str
            age category and gender of the races to be created
        start_year : int
        actualize : bool
            Do we want to actualize the list or recreated it completely
        '''
        super().__init__()
        self.man_or_woman=man_or_woman
        self.start_year=start_year
        self.end_year=date.today().year+1
        self.actualize=actualize

        self.dic =calendar_list.nationChampionshipMaster()
        self.dic_road_race_women, self.dic_clm_women,\
        self.dic_road_race_men, self.dic_clm_men=calendar_list.worldCCchampionships()

        self.champ_table=[]

        self.verbose=False

    def main(self):
        '''
        Main function of this script
        '''
        #Road
        if self.man_or_woman=="woman":
            self.filename='src/input/champ2.csv'
            self.old_filename='src/input/champ.csv'
            self.dic_worldconti=self.dic_road_race_women
            self.pattern="Course en ligne féminine aux"
        else:
            self.filename='src/input/champ_man2.csv'
            self.old_filename='src/input/champ_man.csv'
            self.dic_worldconti=self.dic_road_race_men
            self.pattern="Course en ligne masculine aux"

        self.road_or_clm='Road'
        self.sub_create_champ()

        print("road scan finished")
        #Clm
        if self.man_or_woman=="woman":
            self.dic_worldconti=self.dic_clm_women
            self.pattern="Contre-la-montre féminin aux"
        else:
            self.dic_worldconti=self.dic_clm_men
            self.pattern="Contre-la-montre masculin aux"
        self.road_or_clm='Clm'
        self.sub_create_champ()
        print("itt scan finished")

        final_df=pd.DataFrame(self.champ_table)
        if self.actualize:
            old_df = pd.read_csv(self.old_filename,index_col=0)
            old_df=old_df[old_df["WorldCC"]==False] #remove the world
            old_df=old_df[old_df["Year"]<self.start_year]
            final_df=pd.concat([old_df, final_df])

        final_df.to_csv(self.filename)
        print("csv file " + self.filename + " written")

    def sub_findwinner(
            self,
            pyItem:PyItem,
            id_race:str,
            WorldCC:bool=False,
            ):
          '''
            Look for winner in the races, it remove races that does not seem to have correct information

            Parameters
            ----------
            pyItem : PyItem
            id_race : str
                Wikidata id of the race
            WorldCC : bool, optional
                If the race is not a national championship
          '''

          date_found=False
          invalid_precision=False
          there_is_a_winner=False
          warning_written=False
          row={}
          row['Champ']=id_race

          if (u'P585' in pyItem.item.claims):
             list_of_race_date=pyItem.item.claims.get(u'P585')
             race_date=list_of_race_date[0].getTarget()
             if race_date is None:
                 invalid_precision=True
             elif ((race_date.day==1 and race_date.month==1) or
                 race_date.day==0 or
                 race_date.month==0):
                 invalid_precision=True
             else:
                 date_found=True

          if (u'P1346' in pyItem.item.claims): #winner
             winners=pyItem.item.claims.get(u'P1346')
             for winner in winners:
                 there_is_qual=False
                 id_this_qual=None

                 for qual in winner.qualifiers.get('P642', []):
                     there_is_qual=True
                 if there_is_qual:
                     id_this_qual=winner.qualifiers['P642'][0].getTarget().getID()
                 else:
                     print(pyItem.get_label('fr'))
                     print("no qualifier")

                 if id_this_qual is not None and id_this_qual=='Q20882667': #winner general classification
                     #check qualifier
                     if winner.getTarget() is not None:
                         id_temp_winner=winner.getTarget().getID()
                         there_is_a_winner=True
                     if date_found and there_is_a_winner:
                         row['Day']=race_date.day
                         row['Month']=race_date.month
                         row['Year']=race_date.year
                         row['Winner']=id_temp_winner
                         if WorldCC:
                             row['WorldCC']=True
                         else:
                             row['WorldCC']=False
                         if self.road_or_clm=="Clm":
                             row['Clm']=True
                         else:
                             row['Clm']=False
                         self.champ_table.append(row)
                     elif invalid_precision and there_is_a_winner:
                         if warning_written==False:
                             print(pyItem.get_label('fr'))
                             print('unsufficient precision')
                             warning_written=True

    def sub_champlist(self):
        '''
        Run the search of winners in each race of self.dic_worldconti
        '''
        for id_race in self.dic_worldconti:
            race=Race(id=id_race)
            if(u'P527' in race.item.claims):
                 for e in race.item.claims.get(u'P527'):
                     pyItem_this_year=PyItem(id=e.getTarget().getID())
                     self.sub_findwinner(pyItem_this_year, id_race,WorldCC=True)

    def sub_course(self,race):
        '''
        Check the nature of the race and perform the winner search in the parent if necessary
        '''
        this_label=race.get_label('fr')
        if this_label.find(self.pattern)==0: #filter with fr label
            if (u'P31' in race.item.claims):
                list_of_nature=race.item.claims.get(u'P31')
                id_master=list_of_nature[0].getTarget().getID()
            else:
                id_master=u'Q1'
            self.sub_findwinner(race, id_master)

    def sub_create_champ(self):
        '''
        Create the result table

        Note: world and continental championships are recreated all the time
        '''
        self.sub_champlist()
        self.log.concat(self.road_or_clm +" world and continental championships "+ \
                        self.man_or_woman + " completed")

        if self.verbose:
            self.log.concat(self.WorldCC_champ_table)

        #Look in the national championships
        for year in range(self.start_year,self.end_year):
            year=str(year)
            self.log.concat(self.road_or_clm + " start year " + year)

            pyItem_all_national=PyItem(id=self.dic[year])

            if(u'P527' in pyItem_all_national.item.claims):
                 for e in pyItem_all_national.item.claims.get(u'P527'):
                     race_this_national=Race(id=e.getTarget().getID())

                     if(u'P527' in race_this_national.item.claims):
                         for e2 in race_this_national.item.claims.get(u'P527'):
                             race_this_year=Race(id=e2.getTarget().getID())
                             self.sub_course(race_this_year)
                     else:
                         print(race_this_national.get_label('fr') + " has no P527")


import json
import sys
import os

TYPE_FLAG = '__persistent_type__'
MODULE_FLAG = '__persistent_module__'

def as_dict(value):
  """Recursively converts an object into a dictionary.

  Converts tuple into list and recursively process each items.
  """
  if hasattr(value, 'as_dict') and callable(value.as_dict):
    return value.as_dict()
  elif isinstance(value, (list, tuple)):
    return [as_dict(v) for v in value]
  elif isinstance(value, dict):
    return dict((as_dict(k), as_dict(v))
                for k, v in value.iteritems())
  elif isinstance(value, (float, int, basestring)) or value is None:
    return value
  else:
    raise AttributeError('Can\'t type %s into a dictionary' % type(value))

def _inner_from_dict(value):
  """Recursively regenerates an object."""
  if isinstance(value, dict):
    if TYPE_FLAG in value:
      return PersistentMixIn.from_dict(value)
    return dict((_inner_from_dict(k), _inner_from_dict(v))
                for k, v in value.iteritems())
  elif isinstance(value, list):
    return [_inner_from_dict(v) for v in value]
  elif isinstance(value, (float, int, basestring)) or value is None:
    return value
  else:
    raise AttributeError('Can\'t load type %s' % type(value))

def to_yaml(obj):
  """Converts a PersisntetMixIn into a yaml-inspired format."""
  def align(x):
    y = x.splitlines(True)
    if len(y) > 1:
      return ''.join(y[0:1] + ['  ' + z for z in y[1:]])
    return x
  def align_value(x):
    if '\n' in x:
      return '\n  ' + align(x)
    return x

  if hasattr(obj, 'as_dict') and callable(obj.as_dict):
    out = (to_yaml(obj.as_dict()),)
  elif isinstance(obj, (float, int, basestring)) or obj is None:
    out = (align(str(obj)),)
  elif isinstance(obj, dict):
    if TYPE_FLAG in obj:
      out = ['%s:' % obj[TYPE_FLAG]]
    else:
      out = []
    for k, v in obj.iteritems():
      if k.startswith('__') or v in (None, '', False, 0):
        continue
      r = align_value(to_yaml(v))
      if not r:
        continue
      out.append('- %s: %s' % (k, r))
  elif hasattr(obj, '__iter__') and callable(obj.__iter__):
    out = ['- %s' % align(to_yaml(x)) for x in obj]
  else:
    out = ('%s' % obj.__class__.__name__,)
  return '\n'.join(out)

class PersistentMixIn(object):
  """Class to be used as a base class to persistent data in a simplistic way.

  persistent class member needs to be set to a tuple containing the instance
  member variable that needs to be saved or loaded.

  TODO(maruel): Use __reduce__!
  """
  persistent = None

  def __new__(cls, *args, **kwargs):
    """Override __new__() to be able to instantiate derived classes without
    calling their __init__() function. This is useful when objects are created
    from a dict.
    """
    result = super(PersistentMixIn, cls).__new__(cls)
    if args or kwargs:
      result.__init__(*args, **kwargs)
    return result

  def as_dict(self):
    """Create a dictionary out of this object."""
    assert isinstance(self.persistent, (list, tuple))
    out = {}
    for member in self.persistent:
      assert isinstance(member, str)
      out[member] = as_dict(getattr(self, member))
    out[TYPE_FLAG] = self.__class__.__name__
    out[MODULE_FLAG] = self.__class__.__module__
    return out

  @staticmethod
  def from_dict(data):
    """Returns an instance of a class inheriting from PersistentMixIn,
    initialized with 'data' dict."""
    datatype = data[TYPE_FLAG]
    if MODULE_FLAG in data and data[MODULE_FLAG] in sys.modules:
      objtype = getattr(sys.modules[data[MODULE_FLAG]], datatype)
    else:
      # Fallback to search for the type in the loaded modules.
      for module in sys.modules.itervalues():
        objtype = getattr(module, datatype, None)
        if objtype:
          break
      else:
        raise KeyError('Couldn\'t find type %s' % datatype)
    obj = PersistentMixIn.__new__(objtype)
    assert isinstance(obj, PersistentMixIn)
    for member in obj.persistent:
      setattr(obj, member, _inner_from_dict(data.get(member, None)))
    return obj

  def __str__(self):
    return to_yaml(self)

def load_from_json_file(filename):
  """Loads one object from a JSON file."""
  try:
    f = open(filename, 'r')
    return PersistentMixIn.from_dict(json.load(f))
  finally:
    f.close()

def save_to_json_file(filename, obj):
  """Save one object in a JSON file."""
  try:
    old = filename + '.old'
    if os.path.exists(filename):
      os.rename(filename, old)
  finally:
    try:
      f = open(filename, 'w')
      json.dump(obj.as_dict(), f, sort_keys=True, indent=2)
      f.write('\n')
    finally:
      f.close()


"""
自动伸缩文字下方的多条直线，达到合适的长度
"""

from math import pi

from autocad.toapoint import my_get_selection, haircut, to_Apoint
from pyautocad import Autocad,APoint

def thisorder():
    acad = Autocad(create_if_not_exists=True)
    print(acad.doc.Name)
    slt = my_get_selection(acad=acad,text="选择文字和标志线：按enter结束")
    acad.prompt("正在执行命令...\n")
    text=None
    lines=[]
    for myobj in slt:
        if 'acdbtext' in myobj.ObjectName.lower():
            haircut(myobj)
            text=myobj
            # myobj.myrect.draw_in_cad(acad.doc)
        elif 'acdbline' in myobj.ObjectName.lower():  # 直线
            haircut(myobj)
            lines.append(myobj)

    #计算合适的直线长度
    for ln in lines:
        p1=text.leftdown.get_nearest_point_to_line(ln.myline)
        p2=text.rightup.get_nearest_point_to_line(ln.myline)
        #修改
        ln.StartPoint=to_Apoint(p1)
        ln.EndPoint = to_Apoint(p2)
    pass
    acad.prompt("命令完成\n")

if __name__ == '__main__':
    thisorder()


#! /usr/bin/env python3

import datetime
import time
import cv2
import picamera
import RPi.GPIO as GPIO
from RPLCD.i2c import CharLCD
import database

class MotionSensorClass():
    """
    """

    def __init__(self, db_queue=None, power_pin=None):
        self.db_queue = db_queue
        self.MotionInputPin = 16
        self.PowerPin = power_pin
        GPIO.setup(self.MotionInputPin, GPIO.IN)

        self.state = False
        return

    def Enable(self):
        """
        """
        self.state = True
        GPIO.setup(self.PowerPin, GPIO.OUT)
        GPIO.output(self.PowerPin, self.state)
        return

    def Disable(self):
        """
        """
        self.state = False
        GPIO.setup(self.PowerPin, GPIO.OUT)
        GPIO.output(self.PowerPin, self.state)
        return

class LCDClass():
    """
    """

    def __init__(self, db_queue=None, power_pin=None):
        self.db_queue = db_queue
        self.PowerPin = power_pin
        self.state = False
        return

    def Enable(self):
        """
        """
        self.state = True
        GPIO.setup(self.PowerPin, GPIO.OUT)
        GPIO.output(self.PowerPin, self.state)
        return

    def Disable(self):
        """
        """
        self.state = False
        GPIO.setup(self.PowerPin, GPIO.OUT)
        GPIO.output(self.PowerPin, self.state)
        return

    def WriteDisplay(self, string=None):
        if string is None:
            return
        print("LCDClass: WriteDisplay {}".format(string))
        lcd = CharLCD(0x27)
        lcd.clear()
        lcd.write_string(str(string))
        return

class LEDClass():
    """
    """
    def __init__(self, LEDPin=23):
        """
        """
        print("LEDClass Init")
        self.LEDPin = 23
        self.state = False
        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.LEDPin, GPIO.OUT)
        GPIO.output(self.LEDPin, self.state)
        return

    def toggle(self):
        """
        """
        self.state = not self.state
        print("LED Toggle {}".format(self.state))
        GPIO.output(self.LEDPin, self.state)
        return

class PushButtonClass():
    """
    """
    def __init__(self, db_queue=None, InputPin=18):
        self.db_queue = db_queue
        self.InputPin = InputPin
        GPIO.setup(self.InputPin, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        self.state = False
        return

class CameraClass():
    """
    Class for dealing with the camera on a Raspberry Pi
    """

    def __init__(self, db_queue=None, x=1024, y=768):
        """
        Constructor to make camera instance
        """
        self.db_queue = db_queue
        self.camera = picamera.PiCamera()
        self.camera.resolution = (x, y)
        return

    def FacialDetection(self, filename=None):
        if filename is None:
            return None

        dir_path = "/usr/local/share/OpenCV/haarcascades/"
        xml_filename = "haarcascade_frontalface_default.xml"
        model_path = dir_path + "/" + xml_filename
        clf = cv2.CascadeClassifier(model_path)
        image = cv2.imread(filename)
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        # Detect faces on image
        faces = clf.detectMultiScale(
            gray,
            scaleFactor=1.1,
            minNeighbors=5,
            minSize=(60, 60),
            flags=cv2.CASCADE_SCALE_IMAGE
        )

        print("FacialDetection: Found {0} faces!".format(len(faces)))

        # Draw a rectangle around the faces
        for (x, y, w, h) in faces:
            cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

        cv2.imwrite(filename, image)
        return

    def simple_picture(self, filename=None):
        """
        Take an immediate picture and save to filename
        """
        if filename is None:
            return
        time.sleep(2)
        self.camera.capture(filename)

class RasPiHardware():
    """
    """

    def __init__(self, db_queue=None):
        self.db_queue = db_queue

        MotionSensorPowerPin = 24
        LCDPowerPin = 14

        GPIO.setwarnings(False)
        GPIO.setmode(GPIO.BCM)

        self.Camera = CameraClass(db_queue)
        self.LED = LEDClass(db_queue)
        self.PushButton = PushButtonClass(db_queue)

        self.LCD = LCDClass(db_queue=db_queue, power_pin=LCDPowerPin)
        self.LCD.Disable()

        self.MotionSensor = MotionSensorClass(db_queue=db_queue,
                                              power_pin=MotionSensorPowerPin)
        self.MotionSensor.Disable()

        GPIO.add_event_detect(18, GPIO.FALLING, callback=self.ButtonCallBack,
                              bouncetime=800)
        GPIO.add_event_detect(16, GPIO.RISING,
                              callback=self.MotionSensorCallBack)
        return

    def __del__(self):
        print("RasPiHardware Destructor")
        self.LCD.Disable()
        self.MotionSensor.Disable()
        GPIO.cleanup()
        return

    def TakePicture(self, channel=None, name=None):
        """
        """
        now = datetime.datetime.now()
        now_string = now.strftime("%m-%d-%Y_%H-%M-%S")
        filename = "images/"+name+"_"+now_string+".jpg"
        print("TakePicture {}".format(filename))
        self.Camera.simple_picture(filename=filename)
        self.Camera.FacialDetection(filename=filename)
        image_message = database.DatabaseImageMessage(
            table_name="images", image_name=filename,
            date=now.strftime("%m-%d-%Y"),
            time=now.strftime("%H:%M:%S"))
        message = database.DatabaseMessage(
            command=database.DatabaseCommand.DB_INSERT_IMAGE_DATA,
            message=image_message)
        self.db_queue.put(message)
        return

    def ButtonCallBack(self, channel):
        now = datetime.datetime.now()
        print("PushButtonCallBack {} {}".format(
            channel,
            now.strftime("%m-%d-%Y %H:%M:%S")))
        # Trigger camera to take picture
        self.TakePicture(channel, "push_button")

        sensor_message = database.DatabaseSensorMessage(
            table_name="button",
            sensor_id=channel, sensor_data=True,
            date=now.strftime("%m-%d-%Y"),
            time=now.strftime("%H:%M:%S"))
        message = database.DatabaseMessage(
            command=database.DatabaseCommand.DB_INSERT_SENSOR_DATA,
            message=sensor_message)
        self.db_queue.put(message)

        return

    def MotionSensorCallBack(self, channel):
        print("MotionSensorClass: MotionSensorCallBack {}".format(channel))
        self.TakePicture(channel, "motion_sensor")

        return


from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import auth
from .models import Operador as caixa, Produtos as prod
from .form import ProductForm, CaixaForm
# from django import template
from django.http import HttpResponseRedirect
from django.urls import reverse

#COMPRAS
@login_required
def listar_produtos_disponiveis(request):
        produtos = prod.objects.all()
        return render(request, 'compras.html', {'produtos': produtos})

        def post(self, request, *args, **kwargs):
            if request.method == "POST":
                produto_id = request.POST.getlist('preco[]')
                for preco in produto_id:
                    produtos = prod.objects.get(pk=id)
                    produtos.save()

            return redirect('listar_produtos_disponiveis')

# class Preco_view(View):
#     def get(self, request):
#         produto = prod.objects.all()
#         context ={
#             'produto': produto
#         }
#         return render(request, 'compras.html', context)

#PRODUTOS
@login_required
def list_products(request):
    produtos = prod.objects.all()
    return render(request, 'produtos.html', {'produtos': produtos})

@login_required
def create_products(request):
    form = ProductForm(request.POST or None)

    if request.method == "POST" and form.is_valid():
        form.save()
        return redirect('list_products')

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

@login_required
def update_products(request, id):
    produto = prod.objects.get(id=id)
    form = ProductForm(request.POST or None, instance=produto)

    if request.method == "POST" and form.is_valid():
        form.save()
        return redirect('list_products')

    return render(request, 'produtos-form.html', {'form': form, 'produto': produto})

@login_required
def delete_products(request, id):
    produto = prod.objects.get(id=id)

    if request.method == 'POST':
        produto.delete()
        return redirect('list_products')

    return render(request, 'produtos-delete-confirm.html', {'produto': produto})

#CAIXA
@login_required
def list_caixa(request):
    operadores = caixa.objects.all()
    return render(request, 'caixa.html', {'operadores': operadores})

@login_required
def create_caixa(request):
    form = CaixaForm(request.POST or None)

    if request.method == "POST" and form.is_valid():
        form.save()
        return redirect('list_caixa')

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

@login_required
def update_caixa(request, id):
    operadores = caixa.objects.get(id=id)
    form = CaixaForm(request.POST or None, instance=operadores)

    if request.method == "POST" and form.is_valid():
        form.save()
        return redirect('list_caixa')

    return render(request, 'caixa-form.html', {'form': form, 'operadores': operadores})

@login_required
def delete_caixa(request, id):
    operadores = caixa.objects.get(id=id)

    if request.method == 'POST':
        operadores.delete()
        return redirect('list_caixa')

    return render(request, 'caixa-delete-confirm.html', {'operadores': operadores})

#LOGOUT
def logout(request):
    auth.logout(request)
    return redirect('/')


# This code can't scroll. so user should have to scroll while code is executing

from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred = credentials.Certificate('treatment-97281-firebase-adminsdk-ba112-c7823d2208.json')

firebase_admin.initialize_app(cred, {
    'databaseURL': "https://treatment-97281-default-rtdb.firebaseio.com"
})

ref = db.reference('/bus')

def my_function():
    link = "https://rongdhonustudio.com/DhakaBus.html"
    driver.get(link)
    data1 = driver.find_elements(By.XPATH, "//ul//li")
    data2 = driver.find_elements(By.XPATH, "//ul//li//div//div")

    print(f"total number of item: {len(data1)}")
    for i in range(len(data1)):
        BussName = data1[i].text
        var = data1[i]
        data1[i].click()
        time.sleep(1)
        Route = data2[i].text
        Route_name = Route.replace('Route:','')
        print(BussName, "==", Route_name)
        print(" ")

        ref.push().set({
            'bus_name': BussName,
            'bus_route': Route_name
        })

driver = webdriver.Chrome()
time.sleep(2)

my_function()

time.sleep(2)
driver.quit()


import json

import scrapy

class TestSpider(scrapy.Spider):
    name = "test"
    allowed_domains = ["fanyi.baidu.com"]

    # post请求不携带参数无法访问
    # start_urls = ["https://fanyi.baidu.com/sug"]

    # def parse(self, response):
    #     pass
    def start_requests(self):
        url = 'https://fanyi.baidu.com/sug'
        data = {
            'kw': 'movie'
        }
        yield scrapy.FormRequest(url=url, formdata=data, callback=self.test)

    def test(self, response):
        content = response.text
        obj = json.loads(content)
        print(obj)


from datetime import datetime
from uuid import uuid4, UUID
from pydantic import BaseModel, Field
from sqlalchemy import or_

from base import database, table_users_log

class User_log(BaseModel):
    p_id: UUID = Field(default_factory=uuid4)
    r_id: UUID = Field(default_factory=uuid4)
    u_id: UUID = Field(default_factory=uuid4)
    l_time : datetime
    event : str

    async def create(P_ID, R_ID, U_ID, EVENT):
        "Процедура добавления строчки лога"
        query = table_users_log.insert().values(
                p_id = P_ID,
                r_id = R_ID,
                u_id = U_ID,
                l_time = datetime.now(),
                event = EVENT
                )

        return await database.execute(query)

    async def list_events(ID):
        "Процедура чтения лога по проекту референсу или юзеру"
        query = table_users_log.select().values(or_(
            table_users_log.c.p_id == ID,
            table_users_log.c.r_id == ID,
            table_users_log.c.u_id == ID
            ))

        return await database.fetch_all(query)


class Node:

    def __init__(self, item):
        self.mItem = item
        self.mNext = None

class LinkedList:

    def __init__(self):
        self.mFirst = None

    def empty(self):
        return self.mFirst is None

    def insert(self, item):
        node = Node(item)
        node.mNext = self.mFirst
        self.mFirst = node

    def head(self):
        if self.empty():
            return None
        else:
            return self.mFirst.mItem

    def tail(self):
        if self.empty():
            raise Exception("dsf")
        self.mFirst = self.mFirst.mNext
        return self

if __name__ == "__main__":
    LL = LinkedList()
    LL.insert(55)
    LL.insert(76)
    LL.insert(5)
    print(LL.head())
    LL.tail()
    print(LL.head())


import sys
from collections import defaultdict
input = sys.stdin.readline

n = int(input())
due = defaultdict(list)
latest_due = 0 # 가장 늦은 데드라인
ans = 0

for _ in range(n):
    p, d = map(int, input().split())
    # due[d]는 각각이 리스트임
    due[d].append(p)
    latest_due = max(latest_due, d)

for i in range(latest_due + 1):
    if i in due:
        due[i].sort()

# date 부터 latest_due 까지의 idx 중에서 찾음
for date in range(latest_due, 0, -1):
    mP = None
    mIdx = None

    for i in range(date, latest_due + 1):
        if i in due and due[i] and (mP == None or due[i][-1] > mP):
            mIdx = i
            mP = due[i][-1]

    # 찾으면 그 일정을 수행, pop
    if mP:
        ans += mP
        due[mIdx].pop()

print(ans)


import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen as uReq # command to grab the page

# this program was built as part of my work with SVCI - in order to streamline my workload in data entry

# Function to scrape company information from Crunchbase
def scrape_crunchbase_company(url):
    try:
        # Send a GET request to the Crunchbase URL
        #response = requests.get(url)

        uClient = uReq(url)
        # read the html page and save it inside a var, if you don't store, the html is dumped
        response = uClient.read()
        # close the connection
        uClient.close()

        # Check if the request was successful
        if response.status_code == 200:
            # Parse the HTML content of the page using BeautifulSoup
            soup = BeautifulSoup(response.text, 'html.parser')

            # Extract company information (you can modify this as needed)
            company_name = soup.find('h1', class_='component--field-formatter field-type-identifier-multi').text.strip()
            description = soup.find('span', class_='component--field-formatter field-type-markdown field-label-hidden').text.strip()
            headquarters = soup.find('div', class_='location-icon-2').find_next('span').text.strip()
            founders = soup.find('span', class_='wrappable-label-with-info ng-star-inserted').text.strip()
            website = soup.find('a', rel_='nofollow noopener noreferrer').text.strip()

            # Print the scraped information
            print("Company Name:", company_name)
            print("Description:", description)
            print("Headquarters:", headquarters)
            print("Founders: ", founders)
            print("Website: ", website)
        else:
            print("Couldn't retrieve the page. Status code:", response.status_code)

    except Exception as e:
        print("An error occurred:", str(e))

# URL of the Crunchbase page you want to scrape
crunchbase_url = "https://www.crunchbase.com/organization/databook"

# Call the scrape function with the URL
scrape_crunchbase_company(crunchbase_url)


import base64

# Read data from stdin

def main():
    # if str == 'Start':
    #     print "OK"
    #     print "Cancel"
    with open("/home/pi/ios/ble/python/sample.png", "rb") as imageFile:
        image_str = base64.b64encode(imageFile.read())
    fh = open("/home/pi/ios/ble/data/imageToSave", "wb")
    fh.write(image_str)
    fh.close()
    fh = open("/home/pi/ios/ble/data/string", "wb")
    fh.write("Hello Raspberry Pi")
    fh.close()
    fh = open("/home/pi/ios/ble/data/status", "wb")
    fh.write("Finished " + str(len(image_str)))
    fh.close()

if __name__ == '__main__':
    main()


from turtle import  Turtle
ALIGNMENT = "left"
FONT = ('courier', 18, 'normal')

class Scoreboard(Turtle):
    def __init__(self):
        super().__init__()
        self.score = 0
        self.penup()
        self.color("white")
        self.ht()
        self.setpos(-250,270)
        self.write(f"Score = {self.score}", False, align=ALIGNMENT,  font=FONT)

    def eat(self):
        self.clear()
        self.score += 1
        self.write(f"Score = {self.score}", False, align="left", font=('Arial', 12, 'normal'))

    def game_over(self):
        self.home()
        self.write(f"GAME OVER", False, align=ALIGNMENT, font=FONT)


from __future__ import division, print_function
import numpy as np

def dec_to_bin(x, n):
	return bin(x)[2:].zfill(n)

def combine(a, b):
	ans = ''
	count = 0
	for i in xrange(len(a)):
		if(a[i] == b[i]):
			ans += a[i]
		else:
			ans += '-'
			count += 1
	if(count > 1):
		return None
	else:
		return ans

def find_prime_implicants(data):
	implicants = list(data)
	size = len(implicants)
	IM = []
	im = []
	im2 = []
	mark = [0]*size
	m = 0
	for i in xrange(size):
		for j in xrange(i+1, size):
			ans = combine( str(implicants[i]), str(implicants[j]) )
			if ans != None:
				im.append(str(ans))
				mark[i] = 1
				mark[j] = 1
			else:
				continue

	mark2 = [0]*len(im)
	for p in xrange(len(im)):
		for n in xrange(p+1, len(im)):
			if( p != n and mark2[n] == 0):
				if( im[p] == im[n]):
					mark2[n] = 1

	for r in xrange(len(im)):
		if(mark2[r] == 0):
			im2.append(im[r])

	for q in xrange(size):
		if( mark[q] == 0 ):
			IM.append( str(implicants[q]) )
			m = m+1

	if(m == size or size == 1):
		return IM
	else:
		return IM + find_prime_implicants(im2)

def transfer(data, tra):
	newlist = list(data)
	if newlist in tra:
		return
	if '-' not in newlist:
		tra.append(newlist)
		return
	#print(newlist)
	for i in xrange(len(newlist)):
		if newlist[i]=='-':
			newlist[i] = '0'
			transfer(newlist, tra)
			newlist[i] = '1'
			transfer(newlist, tra)
def PrintAns(ans):
	for i in xrange(len(ans)):
		for j in xrange(len(ans[i])):
			if ans[i][j]=='0':
				print(chr(j+ord('a'))+"'", end="")
			elif ans[i][j]=='1':
				print(chr(j+ord('a')), end="")
		if i < len(ans)-1:
			print(' + ', end="")
	print()

if __name__ == '__main__':
	while True:
		m = []
		d = []
		ALL = []
		try:
			(N_var, N_m, N_d) = map(int, raw_input().split())
		except:
			break

		if N_m>0:
			m = map(int, raw_input().split())
		if N_d>0:
			d = map(int, raw_input().split())
		ALL = sorted(m+d)
		for i in xrange(len(ALL)):
			ALL[i] = dec_to_bin(ALL[i], N_var)
		prime_implicants = find_prime_implicants(ALL)
		#print(prime_implicants)

		table = np.zeros(shape=(len(prime_implicants), 1<<N_var))
		for i in xrange(len(prime_implicants)):
			tra = []
			transfer(prime_implicants[i], tra)
			#print(tra)
			for j in tra:
				strr = ''.join(j)
				dec = int(strr, 2)
				if dec in m:
					table[i][dec] = 1
		#print(table)
		essential = []
		ans = []
		while True:
			if len(essential)==N_m:
				break
			for i in xrange(1<<N_var):
				if i not in m:
					continue
				index = -1
				for j in xrange(len(prime_implicants)):
					if table[j][i]==1:
						if index==-1:
							index = j
						else:
							index = -1
							break
				if index==-1:
					continue
				ans.append(prime_implicants[index])
				for k in xrange(1<<N_var):
					if table[index][k]==1:
						for r in xrange(len(prime_implicants)):
							table[r][k] = 0
						if k not in essential:
							essential.append(k)
				#print(table)
			if len(essential)==N_m:
				break

			MAX = 0
			MAX_ind = -1
			for i in xrange(len(prime_implicants)):
				SUM = 0
				for j in xrange(1<<N_var):
					SUM += table[i][j]
				if SUM>MAX:
					MAX = SUM
					MAX_ind = i
			ans.append(prime_implicants[MAX_ind])
			for j in xrange(1<<N_var):
				if table[MAX_ind][j]==1:
					for k in xrange(len(prime_implicants)):
						table[k][j] = 0
					if j not in essential:
						essential.append(j)
		PrintAns(ans)


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
from decimal import Decimal
from django.conf import settings

from product.models import Product, Slab, PackageList
from stock.models import Location

class Cart:
    def __init__(self, request):
        self.session = request.session
        cart = self.session.get(settings.CART_SESSION_ID)
        if not cart:
            cart = self.session[settings.CART_SESSION_ID] = {}
        self.cart = cart

    def add(self, product_id, location_id, piece=None, quantity=None, slab_id_list=None):
        product = Product.objects.get(pk=product_id)
        if product.type == 'slab':
            if not slab_id_list:
                return False
            piece = len(slab_id_list)
            quantity = sum(slab.get_quantity() for slab in Slab.objects.filter(id__in=slab_id_list))
        elif product.type == 'block':
            piece = 1
            quantity = quantity
        line = len(self.cart) + 1 if product_id not in self.cart else self.cart[product_id]['line']
        self.cart[product_id] = {'line': line, 'piece': piece, 'quantity': str(quantity),
                                 'slab_id_list': slab_id_list, 'location_id': location_id}
        self.save()

    def save(self):
        self.session.modified = True

    def get_select_slabs(self):
        lst = []
        for i in self.cart.values():
            lst.extend(i['slab_id_list'])
        return lst

    def remove(self, product_id):
        product_id = str(product_id)
        if product_id in self.cart:
            del self.cart[product_id]
            self.save()

    def clean(self):
        del self.session[settings.CART_SESSION_ID]
        self.save()

    def __iter__(self):
        product_id_list = self.cart.keys()
        products = Product.objects.filter(id__in=product_id_list)
        cart = copy.deepcopy(self.cart)
        for product in products:
            cart[str(product.id)]['product'] = product
            if product.type == 'slab':
                cart[str(product.id)]['part'] = {s.part_number for s in
                                                 Slab.objects.filter(id__in=cart[str(product.id)]['slab_id_list'])}

        for item in cart.values():
            item['quantity'] = item['quantity']
            yield item

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


#! python3
"""This module implements classes and methods for manipulating Blood Bowl 2
team names and league schedules in order to facilitate command line operation
and a Discord Bot API in the future."""
import argparse
import yaml

################################################################################
class Team:
    """Class encapsulates team data as well as multiple methods for
    constructing the object from different sources."""

    def __init__(self, name, race, coach, dtag):
        self.name = name
        self.race = race
        self.coach = coach
        self.dtag = dtag

    @classmethod
    def from_dict(cls, team_info):
        """Returns a class object filled with data from a dictionary (the
        format the YAML file will return)."""
        return cls(
            team_info["name"], team_info["race"], team_info["coach"], team_info["dtag"]
        )

    @classmethod
    def from_str(cls, team_str):
        """Returns a class object filled with data from a string (the
        format when creating a team from the command line)."""
        team_list = team_str.split(",")
        if team_list[2].lstrip() == "AI":
            return cls(
                team_list[0].lstrip(),
                team_list[1].lstrip(),
                team_list[2].lstrip(),
                "None",
            )
        return cls(
            team_list[0].lstrip(),
            team_list[1].lstrip(),
            team_list[2].lstrip(),
            team_list[3].lstrip(),
        )

    @property
    def yaml(self):
        """Returns a dictionary object to be used to create the data structure
        that is built up into the final overall YAML structure."""
        return {
            "name": self.name,
            "race": self.race,
            "coach": self.coach,
            "dtag": self.dtag,
        }

class League(list):
    """A customized list class encapsulating specific method for constructing
    the class out of a dictionary and Team objects.  May have additional
    custom methods later."""

    def __init__(self, teams_dict=None):
        # Expect to receive nothing and initialize an empty list, or a list
        # of dictionary objects that must be parsed and then we fill our
        # list with Team objects.
        super().__init__()
        teams_dict = teams_dict or []
        for team_dict in teams_dict:
            self.append(Team.from_dict(team_dict))

    @property
    def yaml(self):
        """Returns a list object to be used to create the data structure
        that is built up into the final overall YAML structure."""
        return [team.yaml for team in self]

################################################################################
class Game:
    """Class that encapsulates the data pertaining to a single game in a
    tournament structure."""

    def __init__(self, game_data):
        """Initialization of Game object.  Keeping the Team object associated
        with each position as well as the index.  The index is used for
        recreating the YAML object."""
        # Initial state variables from the instance data
        self.home_index = game_data["home"]
        self.away_index = game_data["away"]
        self.result = {}
        self.result["home"] = game_data["result"]["home"]
        self.result["away"] = game_data["result"]["away"]
        # Secondary variables
        self.home = None
        self.away = None
        self.played = False
        if self.result["home"] != -1 and self.result["away"] != -1:
            self.played = True

    def add_team_data(self, league):
        """Method contains a Team object for the purposes of reporting and
        matching an index number to a Team name.  Index of 9999 indicates
        a bye game and should always be in the away position."""
        self.home = league[self.home_index]
        if self.away_index == 9999:
            self.away = Team("Bye", "", "", "")
        else:
            self.away = league[self.away_index]

    def add_result(self, result_list):
        """Gets a list of scores [home, away] and sets the instances
        values accordingly."""
        self.result["home"] = result_list[0]
        self.result["away"] = result_list[1]

    @property
    def yaml(self):
        """Returns a dictionary object to be used to create the data structure
        that is built up into the final overall YAML structure."""
        return {"home": self.home_index, "away": self.away_index, "result": self.result}

    def __str__(self):
        if self.played:
            return f"Home: {self.home.name:25} Away: {self.away.name:25} Result: {self.result['home']}-{self.result['away']}"
        return f"Home: {self.home.name:25} Away: {self.away.name:25}"

class Week(list):
    """Class that encapsulates the data pertaining to a single week in a
    tournament structure."""

    def __init__(self, game_list=None):
        """Receives a list of dictionaries."""
        super().__init__()
        self.current = False
        game_list = game_list or []
        for game in game_list:
            self.append(Game(game))

    def add_games(self, game_list):
        """Gets a manufactured list in the same format as the one retrieved
        from the YAML file and adds games to this week object."""
        for game in game_list:
            self.append(Game(game))

    def add_result(self, result_list):
        """Gets a list of values for a game result.  [Game num, home score,
        away score] and calls the game's method to set those values."""
        self[result_list[0]].add_result(result_list[1:])

    @property
    def yaml(self):
        """Returns a list object to be used to create the data structure
        that is built up into the final overall YAML structure."""
        return [game.yaml for game in self]

    def __str__(self):
        if self.current:
            lines = [" Current " + "-" * 63]
        else:
            lines = ["-" * 72]
        for game_idx, game in enumerate(self):
            lines.append(f"Game: {game_idx} | {game}")
        return "\n".join(lines)

class Schedule(list):
    """Class that encapsulates the data holding every week (and then every
    subsequent game) in a tournament structure."""

    def __init__(self, schedule_dict=None):
        # Again we expect to get either nothing, or a dictionary with
        # keys labeling the weeks.
        super().__init__()
        schedule_dict = schedule_dict or {}
        for week in schedule_dict:
            self.append(Week(schedule_dict[week]))

    def add_week(self):
        """Adds a blank week object to the schedule."""
        self.append(Week())

    def add_games(self, game_list, week_num=-1):
        """Adds a list of games in the correct format to the last week in
        the schedule.  (or other week specified)"""
        self[week_num].add_games(game_list)

    def add_result(self, result_list, week_num=-1):
        """Receives a list representing the result of a game, as well as the
        week to apply the result to and call's the appropriate week object's
        method to set the game result."""
        self[week_num].add_result(result_list)

    @property
    def yaml(self):
        """Returns a dictionary object to be used to create the data structure
        that is built up into the final overall YAML structure."""
        # Special note here so that I don't forget the bug and why it's not
        # 100% fixed.  Most of the YAML file is lists which does come back in
        # order in YAML 1.1 (and that's what I'm using with pyyaml).  However
        # for that "YAML readability" aspect, I used a dictionary for each week
        # and then each week is labeled.  Dictionaries in 1.1 and PyYAML do
        # NOT come back ordered.  They are printed in alphabetical order of
        # keyword.  So once week numbers went to 2 digits it was printed
        # week_0, week_1, week_10.  However there's something in the way it
        # parses through the structure once the week is added in the middle
        # that breaks everything.
        #
        # The workaround is to make the game numbers padded 3 digits for a
        # maximum schedule of 1000 games (which is definitely more than we'd
        # ever do.  However the parsing weakness is still in here.  I'm not
        # sure if the bug is when the 2 digit week structure is read, or when
        # games are added, or when it's written.
        #
        # Final solution would be to rework the YAML data structure to either
        # full on YAML, or use ruamel.yaml and YAML 1.2, or go to SQLite or
        # something like that.
        return {f"week_{idx:03}": week.yaml for (idx, week) in enumerate(self)}

    @property
    def full_report(self):
        """Returns a string containing a full schedule report (every
        week)"""
        lines = [f"Number of weeks in the schedule: {len(self)}"]
        for week_idx, week in enumerate(self):
            lines.append(f"-- Week: {week_idx+1} --{week}")
        return "\n".join(lines)

    def week_report(self, week_num):
        """Returns a string containing a single week report"""
        lines = []
        for week_idx, week in enumerate(self):
            if week_idx == week_num:
                lines.append(f"-- Week: {week_idx+1} --{week}")
        return "\n".join(lines)

    def __str__(self):
        lines = [f"Number of weeks in the schedule: {len(self)}"]
        for week_idx, week in enumerate(self):
            lines.append(f"-- Week: {week_idx} --{week}")
        return "\n".join(lines)

################################################################################
class TourneyFile:
    """Class encapsulates interactions with the YAML file.  No one outside
    of this class ought to be exposed to THE BLOB."""

    def __init__(self, filename):
        self.filename = filename
        self.league = League()
        self.schedule = Schedule()
        self.current_week = 0

    def read(self):
        """Reading the YAML file and parsing the results.  Have to check
        to make sure fields are populated before creating the data structures.
        """
        with open(self.filename, "r") as f:
            blob = yaml.safe_load(f)
        # Checking the population of the blob against these keys.  The
        # list initializer does not like None as an input.
        if blob["teams"]:
            self.league = League(blob["teams"])
        if blob["current_week"]:
            self.current_week = blob["current_week"]
        if blob["schedule"]:
            self.schedule = Schedule(blob["schedule"])
            for week_idx, week in enumerate(self.schedule):
                if week_idx == self.current_week:
                    week.current = True
                for game in week:
                    game.add_team_data(self.league)
        return self.league, self.schedule, self.current_week

    def write(self, blob):
        """Encapsulated YAML writing method."""
        with open(self.filename, "w") as f:
            yaml.dump(blob, f)

    def create(self):
        """Encapsulated YAML initial file state method."""
        # blob = {"current_week": 0, "teams": None, "schedule": None}
        self.write(self.make_blob)

    def add_team(self, team_str):
        """Encapsulated team addition method."""
        self.read()
        self.league.append(Team.from_str(team_str))
        self.write(self.make_blob)

    def del_team(self, team_name):
        """Encapsulated team deletion method."""
        self.read()
        print(f"self.league is {self.league}")
        for idx, team in enumerate(self.league):
            if team.name == team_name:
                del self.league[idx]
                self.write(self.make_blob)
                break
        else:
            print(f"Team {team_name} not found!")

    def add_week(self):
        """Adds a blank week to the schedule."""
        self.read()
        self.schedule.add_week()
        self.write(self.make_blob)

    def add_games(self, game_list):
        """Receives a list of integers in strings.  Proceeds to create games
        out of this list and add it to the last week in the schedule."""
        self.read()
        # Need to create a translation from the list of strings of numbers
        # to the format the Game object wants.
        game_list = list(map(int, game_list))
        newlist = []
        for idx in range(0, len(game_list), 2):
            if idx != len(game_list) - 1:
                newlist.append(
                    {
                        "home": game_list[idx],
                        "away": game_list[idx + 1],
                        "result": {"home": -1, "away": -1},
                    }
                )
            else:
                newlist.append(
                    {
                        "home": game_list[idx],
                        "away": 9999,
                        "result": {"home": -1, "away": -1},
                    }
                )
        self.schedule.add_games(newlist)
        self.write(self.make_blob)

    def add_result(self, result_list):
        """Receives a list of integers in strings.  Calls the schedule
        object to record the result of the game."""
        self.read()
        result_list = list(map(int, result_list))
        self.schedule.add_result(result_list, self.current_week)
        self.write(self.make_blob)

    def incr_week(self):
        """Method to increment the current week."""
        self.read()
        if self.current_week < len(self.schedule) - 1:
            self.current_week += 1
        self.write(self.make_blob)

    def decr_week(self):
        """Method to increment the current week."""
        self.read()
        if self.current_week > 0:
            self.current_week -= 1
        self.write(self.make_blob)

    @property
    def make_blob(self):
        """Method that constructs the YAML data block (the "blob") from our
        internal data state."""
        teams_result = None
        if self.league is not None:
            teams_result = self.league.yaml
        schedule_result = None
        if self.schedule is not None:
            schedule_result = self.schedule.yaml
        return {
            "current_week": self.current_week,
            "teams": teams_result,
            "schedule": schedule_result,
        }

    def report_teams_long(self):
        """Method to print a report for the team data structures retrieved from the
        YAML file."""
        self.read()
        print(f"Number of teams: {len(self.league)}")
        for idx, team in enumerate(self.league):
            print(f"-- Team #{idx} ---------------------------")
            print(f"Team Name: {team.name}")
            print(f"Team Race: {team.race}")
            print(f"Coach Name: {team.coach}")
            print(f"Coach Discord Tag: {team.dtag}")

    def report_teams_short(self):
        """Produces a condensed team name only list of the current teams"""
        self.read()
        lines = []
        for idx, team in enumerate(self.league):
            lines.append(f"{idx:2}: Name: {team.name:30} Coach: {team.coach:15} Tag: {team.dtag:10}")
        text = "\n".join(lines)
        return text

    def report_full_schedule(self):
        """Method to print a report of the schedule data retrieved from the YAML
        file."""
        self.read()
        return self.schedule.full_report

    def report_current_week(self):
        """Method to print a report of the current week of schedule data
        in the YAML file."""
        self.read()
        return self.schedule.week_report(self.current_week)

################################################################################
def main():
    """Main command line entry point."""
    parser = argparse.ArgumentParser(
        prog="bb_tournament",
        description="Program to manipulate a Blood Bowl 2 tournament data file.",
    )
    parser.add_argument("filename", help="The tournament data file (YAML format).")
    parser.add_argument(
        "--create",
        action="store_true",
        help="Creates a base tournament file (YAML format).",
    )
    parser.add_argument(
        "--add_team",
        help='''Adds a team to the tournament.  Format should be a comma
        separated list inside quotes in the following order:  "Team Name, Race,
        Coach Name, Coach Discoprd Tag".  If the coach is an AI team, use "AI"
        for the Coach Name field, and leave off the Discord Tag field.
        Example #1 --add_team "Super Joes, Khemri, John Doe, JDoe#9999"
        Example #2 --add_team "Doofus Name, Human, AI"''',
    )
    parser.add_argument(
        "--del_team",
        help="""Removes a team from the list.  Team should be specified by
        team name.  If there are spaces in the name, please surround the name
        with quotes.""",
    )
    parser.add_argument(
        "--add_week",
        action="store_true",
        help="""Adds a week to the current schedule.""",
    )
    parser.add_argument(
        "--incr_week",
        action="store_true",
        help="""Increments the current schedule week.""",
    )
    parser.add_argument(
        "--decr_week",
        action="store_true",
        help="""Decrements the current schedule week.""",
    )
    parser.add_argument(
        "--add_games",
        nargs="+",
        help="""Adds any number of games to the week.  Should be followed by a
        list of numbers corresponding to team indexes (as seen by --report
        teams).  The numbers are interpreted as pairs, home team first,
        followed by the away team.  If an odd number of teams are added, the
        last team in the list is given a 'bye' game for the week.  Example #1
        --add_game 0 1 2 3 4 5 will produce 3 games in the week with Team 0
        playing at home against Team 1 playing away, and so on with pairings,
        2 vs 3, and 4 vs 5.  Example #2 --add_game 3 2 1 4 5 will produce three
        games, 3 vs 2, 1 vs 4, and Team 5 gets a bye.""",
    )
    parser.add_argument(
        "--result",
        nargs=3,
        help="""Adds a result to a game in the current week.  Requires three
        numbers following.  The first value is the number of the game as
        listed in the schedule.  The second value is the home team score, and
        the third and final value is the away team score.  Example: --result
        3 1 0 adds a 1-0 result to game 3.""",
    )
    parser.add_argument(
        "--report",
        choices=["longteams", "shortteams", "schedule", "full", "current"],
        help="Produces the selected report for the tournament.",
    )
    args = parser.parse_args()

    tfile = TourneyFile(args.filename)

    if args.create:
        tfile.create()
    if args.add_team:
        tfile.add_team(args.add_team)
    if args.del_team:
        tfile.del_team(args.del_team)
    if args.add_week:
        tfile.add_week()
    if args.incr_week:
        tfile.incr_week()
    if args.decr_week:
        tfile.decr_week()
    if args.add_games:
        tfile.add_games(args.add_games)
    if args.result:
        tfile.add_result(args.result)
    if args.report == "longteams" or args.report == "full":
        tfile.report_teams_long()
    if args.report == "shortteams":
        print(tfile.report_teams_short())
    if args.report == "schedule" or args.report == "full":
        print(tfile.report_full_schedule())
    if args.report == "current":
        print(tfile.report_current_week())

################################################################################
if __name__ == "__main__":
    main()


#!/usr/bin/python3.4
import logging
import monitor
# create logger with 'spam_application'
logger = logging.getLogger('Arduino_app')
logger.setLevel(logging.DEBUG)
# create file handler which logs even debug messages
fh = logging.FileHandler('serial_monitor.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create formatter and add it to the handlers
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter)
# add the handlers to the logger
logger.addHandler(fh)
logger.addHandler(ch)

logger.info('launching serial Monitoring')
monitoring = monitor.ArduinoSerial(port='/dev/ttyACM0')
#serialCom = monitoring(port='/dev/ttyACM0')
logger.info('launched an instance of serial Monitoring')
logger.info('starting monitoring loop')
#monitor.readFrom_Serial(monitoring)
monitor.read_dht11_serial(monitoring)
logger.info('ending monitoring loop')


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

import inspect
import os
import re
import platform
import subprocess
import curses
import sys
import errno
from six import callable

import bpython

config = bpython.running.config

EMACS_CLIENT = re.compile(r'^emacsclient')
EMACS = re.compile(r'^emacs')
NANO = re.compile(r'^nano')
PICO = re.compile(r'^pico')
GEDIT = re.compile(r'^gedit')
KATE = re.compile(r'^kate')
VIM = re.compile(r'^[gm]vim')
VI = re.compile(r'^[gm]vi')
JEDIT = re.compile(r'^jedit')
UEDIT32 = re.compile(r'^uedit32')
GEANY = re.compile(r'^geany')
TEXTMATE = re.compile(r'^mate')
SUBLIME = re.compile(r'^subl')

is_emacs_client = lambda x: EMACS_CLIENT.match(x)
is_emacs = lambda x: EMACS.match(x)
is_nano = lambda x: NANO.match(x)
is_pico = lambda x: PICO.match(x)
is_gedit = lambda x: GEDIT.match(x)
is_kate = lambda x: KATE.match(x)
is_vim = lambda x: VIM.match(x)
is_vi = lambda x: VI.match(x)
is_jedit = lambda x: JEDIT.match(x)
is_uedit32 = lambda x: UEDIT32.match(x)
is_geany = lambda x: GEANY.match(x)
is_textmate = lambda x: TEXTMATE.match(x)
is_sublime = lambda x: SUBLIME.match(x)

class CommandError(Exception): pass

def invoke_editor(file_name, line_number, reloading):
    _editor_name = editor_name()
    if _editor_name:
        if callable(_editor_name):
            argc = len(inspect.getargspec(config.editor).args)
            args = [file_name, line_number, reloading][:argc]
            editor_invocation = _editor_name(*args)
        elif isinstance(_editor_name, str):
            editor_invocation = "%s %s %s" % (
                _editor_name,
                blocking_flag_for_editor(_editor_name, reloading) or "",
                start_line_syntax_for_editor(_editor_name, file_name, line_number)
            )
        else:
            raise

        if editor_invocation:
            return editor_invocation
    else:
        raise (CommandError("Please set config.editor or export $VISUAL or $EDITOR"))

def blocking_flag_for_editor(_editor_name, block):
    """
    Some editors that run outside the terminal allow you to control whether or
    not to block the process from which they were launched (in this case, Pry).
    For those editors, return the flag that produces the desired behavior.
    """
    if is_emacs_client(_editor_name) and not block:
        flag = '--no-wait'
    elif is_vim(_editor_name) and block:
        flag = '--nofork'
    elif is_jedit(_editor_name) and block:
        flag = '--wait'
    elif is_textmate(_editor_name) and block:
        flag = '-w'
    elif is_sublime(_editor_name) and block:
        flag = '-w'
    else:
        flag = None
    return flag

def start_line_syntax_for_editor(_editor_name, file_name, line_number):
    """
    Return the syntax for a given editor for starting the editor
    and moving to a particular line within that file
    """

    if line_number <= 1:
        return file_name

    if is_vi(_editor_name) or \
            is_emacs(_editor_name) or \
            is_nano(_editor_name) or \
            is_pico(_editor_name) or \
            is_gedit(_editor_name) or \
            is_kate(_editor_name):
        result = "+%s %s" % (line_number, file_name)
    elif is_textmate(_editor_name) or is_geany(_editor_name):
        result = "-l %s %s" % (line_number, file_name)
    elif is_sublime(_editor_name):
        result = "%s:%s" % (file_name, line_number)
    elif is_uedit32(_editor_name):
        result = "%s/%s" % (file_name, line_number)
    elif is_jedit(_editor_name):
        result = "%s +line:%s" % (file_name, line_number)
    else:
        if platform.system() == "Windows":
            result = file_name
        else:
            result = "+%s %s" % (line_number, file_name)
    return result

def editor_name():
    """
    Get the name of the binary that Pry.config.editor points to.

    This is useful for deciding which flags we pass to the editor as
    we can just use the program's name and ignore any absolute paths.

    @example
      Pry.config.editor="/home/conrad/bin/textmate -w"
      editor_name
      # => textmate

    """
    _editor_name = config.editor
    if not _editor_name:
        _editor_name = os.path.basename(config.editor).split()
        if _editor_name:
            _editor_name = _editor_name[0]
    return _editor_name or os.environ.get('VISUAL') or os.environ.get('EDITOR')

def invoke_command(command):
    curses.endwin()
    try:
        subprocess.call(command)
    except OSError as e:
        raise e
    finally:
        curses.doupdate()

def invoke_command_with_input(command, inputs):
    curses.endwin()
    try:
        popen = subprocess.Popen(command, stdin=subprocess.PIPE)
        if isinstance(inputs, unicode):
            inputs = inputs.encode(sys.__stdout__.encoding, 'replace')
        popen.stdin.write(inputs)
        popen.stdin.close()
    except OSError as e:
        if e.errno == errno.ENOENT:
            # pager command not found, fall back to internal pager
            sys.stdout.write(inputs)
            return
    except IOError as e:
        if e.errno != errno.EPIPE:
            raise
    while True:
        try:
            popen.wait()
        except OSError as e:
            if e.errno != errno.EINTR:
                raise
        else:
            break
    curses.doupdate()

def is_dictproxy(obj):
    if hasattr(obj, '__class__') and hasattr(obj.__class__, '__name__'):
        return obj.__class__.__name__ == 'dictproxy'
    return False


from cgi import parse_qs, escape

def simple_app(environ, start_response):
    html = """

         POST:
        %(post)s

 GET:
        %(get)s

    """
    htmlfomet = """
 Key "%(key)s" = "%(value)s" """
    try:
        request_body_size = int(environ.get('CONTENT_LENGTH', 0))
    except (ValueError):
        request_body_size = 0
    request_body = environ['wsgi.input'].read(request_body_size)
    dataPost = parse_qs(request_body)
    keys = dataPost.keys()
    post = ""
    for k in keys:
        post = post + htmlfomet % {
                'key': escape(k),
                'value': dataPost[k]
                }
    dataGet = parse_qs(environ['QUERY_STRING'])
    keys = dataGet.keys()
    get = ""
    for k in keys:
        get = get + htmlfomet % {
                'key': escape(k),
                'value': dataGet[k]
                }

    response_body = html % {
            'post': post or 'None',
            'get': get or 'None'
            }
    status = '200 OK'
    response_headlers = [('Content-type', 'text/html'),
            ('Content-Length', str(len(response_body)))
            ]
    start_response(status, response_headlers)
    return [response_body]


MENU = {
    "espresso": {
        "ingredients": {
            "water": 50,
            "coffee": 18,
        },
        "cost": 1.5,
    },
    "latte": {
        "ingredients": {
            "water": 200,
            "milk": 150,
            "coffee": 24,
        },
        "cost": 2.5,
    },
    "cappuccino": {
        "ingredients": {
            "water": 250,
            "milk": 100,
            "coffee": 24,
        },
        "cost": 3.0,
    }
}

profit = 0
resources = {
    "water": 1000,
    "milk": 200,
    "coffee": 100,
}

# Print report of all coffee machine resources
def print_report():
    """Printing out amount of resources and profit when function is called"""
    for key, resource in resources.items():
        if key == "coffee":
            print(f"{key.title()}: {resource}g")
        else:
            print(f"{key.title()}: {resource}ml")
    print(f"Money: ${profit}")

# Check for resources sufficient before making coffee
def check_resources_sufficient(order_ingredients):
    """Return True when order can be made, False if not enough ingredients"""
    for item in order_ingredients:
        if order_ingredients[item] > resources[item]:
            print(f"Sorry there is not enough {item}.")
            return False
    return True

# Process coins. Insert different types coins and check if it's enough money
def process_coins(coffee, price):
    """Returns the total calculated from coins inserted"""
    print(f"Price for {coffee.title()}: ${price}")
    print("Please insert coins.")
    quarters = int(input("How many quarters? ")) * 0.25
    dimes = int(input("How many dimes? ")) * 0.10
    nickles = int(input("How many nickles? ")) * 0.05
    pennies = int(input("How many pennies? ")) * 0.01
    total_coins = quarters + dimes + nickles + pennies
    return total_coins

# Check if transaction is successful
def is_transaction_successful(money_received, drink_cost):
    """Return True when payment is accepted, or False if money is insufficient"""
    if money_received >= drink_cost:
        change = round(money_received - drink_cost, 2)
        print(f"Here is ${change} in change.")
        global profit
        profit += drink_cost
        return True
    else:
        print("Sorry that's not enough money. Money refunded.")
        return False

# Make coffee when sufficient resources and transaction successful
def make_coffee(drink_name, order_ingredients):
    """Deduct the required resources from the resources"""
    for item in order_ingredients:
        resources[item] -= order_ingredients[item]
    print(f"Here is your {drink_name}☕. Enjoy!")

# Ask user what they want to drink as long as the coffee machine is on
machine_is_on = True
while machine_is_on:
    choice = input("What would you like to? (espresso/latte/cappuccino): ").lower()

    if choice == "report":
        print_report()
    elif choice in ["espresso", "latte", "cappuccino"]:
        drink = MENU[choice]
        if check_resources_sufficient(drink["ingredients"]):
            payment = process_coins(choice, drink["cost"])
            if is_transaction_successful(payment, drink["cost"]):
                make_coffee(choice, drink["ingredients"])
    else:
        machine_is_on = False


import basf2 as b2
from ROOT import Belle2, TFile, TFitResultPtr, TH1F, TH2D, TH2F
from ROOT import TF1, gDirectory, gROOT
import math
from ROOT.Belle2 import SVDCoGCalibrationFunction

svd_recoDigits = "SVDRecoDigitsFromTracks"
cdc_Time0 = "EventT0"
svd_Clusters = "SVDClustersFromTracks"

gROOT.SetBatch(True)

# mode = True

class SVDCoGTimeCalibrationImporterModule(b2.Module):
    """
    Python class used for evaluating the CoG corrections, create a localDB,
    creating a localDB with the corrections and a root file to check the corrections
    """

    def notApplyCorrectForCDCLatency(self, mode):
        """
        Function that allows to set if apply the CDC latency correction

        parameters:
             mode (bool):
             - if True -> not apply correction
             - if False -> apply correction
        """
        #: parameter that allows to apply or not the CDC latency correction
        self.notApplyCDCLatencyCorrection = mode
        print("Not Correct for CDC latency: " + str(mode) + " " + str(self.notApplyCDCLatencyCorrection))

    def fillLists(self, mode_byte_object, svdClusters_rel_RecoTracks_cl):
        """
        Function that fill the lists needed for the CoG corrections

        parameters:
             mode_byte_object (modeByte): modeByte that contains the information about the TB
             svdClusters_rel_RecoTracks_cl (SVDCluster): cluster related to tracks
        """

        timeCluster = svdClusters_rel_RecoTracks_cl.getClsTime()
        snrCluster = svdClusters_rel_RecoTracks_cl.getSNR()
        layerCluster = svdClusters_rel_RecoTracks_cl.getSensorID().getLayerNumber()
        layerIndex = layerCluster - 3
        sensorCluster = svdClusters_rel_RecoTracks_cl.getSensorID().getSensorNumber()
        sensorIndex = sensorCluster - 1
        ladderCluster = svdClusters_rel_RecoTracks_cl.getSensorID().getLadderNumber()
        ladderIndex = ladderCluster - 1
        sideCluster = svdClusters_rel_RecoTracks_cl.isUCluster()
        if sideCluster:
            sideIndex = 1
        else:
            sideIndex = 0

        hasTimezero = self.cdcEventT0.hasEventT0()
        # print("Time: " + str(hasTimezero))
        if hasTimezero:
            TBClusters = mode_byte_object.getTriggerBin()
            TBIndex = ord(TBClusters)
            tZero = self.cdcEventT0.getEventT0()
            # tZero_err = self.cdcEventT0.getEventT0Uncertainty()
            # tZero_err = 5.1
            tZeroSync = tZero - 4000./509 * (3 - TBIndex)
            et0 = self.EventT0Hist
            et0.Fill(tZeroSync)
            # print(str(tZero_err))

            resHist = self.resList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex]
            resHist.Fill(timeCluster - tZeroSync)
            spHist = self.spList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex]
            # spHist.Fill(timeCluster, 1.3*timeCluster - 50 + random.gauss(0,10))
            spHist.Fill(timeCluster, tZeroSync)
            cogHist = self.cogList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex]
            cogHist.Fill(timeCluster)
            cdcHist = self.cdcList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex]
            cdcHist.Fill(tZeroSync)
            snrHist = self.snrList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex]
            snrHist.Fill(snrCluster)

            self.nList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex] += 1
            self.sumCOGList[layerIndex][ladderIndex][sensorIndex][sideIndex][TBIndex] += timeCluster

            #: counts the number of clusters
            self.NTOT = self.NTOT + 1

    def set_localdb(self, localDB):
        """
        Function that allows to set the localDB

        parameters:
             localDB (str): Name of the localDB used
        """
        #: set the name of the localDB used
        self.localdb = localDB

    def initialize(self):
        """
        Initialize object (histograms, lists, ...) used by the class
        """

        #: name of the output file
        self.outputFileName = "CoGCorrectionMonitor_" + self.localdb + ".root"

        #: lists used to create the histograms for each TB :
        #: residuals
        self.resList = []
        #: scatterplot t0 vs cog
        self.spList = []
        #: cog
        self.cogList = []
        #: t0
        self.cdcList = []
        #: Cluster SNR
        self.snrList = []
        #: number of clusters
        self.nList = []
        #: sum of CoG times
        self.sumCOGList = []

        geoCache = Belle2.VXD.GeoCache.getInstance()

        self.Evt = 0
        for layer in geoCache.getLayers(Belle2.VXD.SensorInfoBase.SVD):
            layerList0 = []
            layerList1 = []
            layerList2 = []
            layerList3 = []
            layerList4 = []
            layerList5 = []
            layerList6 = []
            layerList7 = []
            layerList8 = []
            self.resList.append(layerList0)
            self.spList.append(layerList1)
            self.cogList.append(layerList2)
            self.cdcList.append(layerList3)
            self.snrList.append(layerList4)
            self.nList.append(layerList8)
            self.sumCOGList.append(layerList7)
            # layerNumber = layer.getLayerNumber()
            for ladder in geoCache.getLadders(layer):
                ladderList0 = []
                ladderList1 = []
                ladderList2 = []
                ladderList3 = []
                ladderList4 = []
                ladderList5 = []
                ladderList6 = []
                ladderList7 = []
                ladderList8 = []
                layerList0.append(ladderList0)
                layerList1.append(ladderList1)
                layerList2.append(ladderList2)
                layerList3.append(ladderList3)
                layerList4.append(ladderList4)
                layerList5.append(ladderList5)
                layerList6.append(ladderList6)
                layerList7.append(ladderList7)
                layerList8.append(ladderList8)
                # ladderNumber = ladder.getLadderNumber()
                for sensor in geoCache.getSensors(ladder):
                    sensorList0 = []
                    sensorList1 = []
                    sensorList2 = []
                    sensorList3 = []
                    sensorList4 = []
                    sensorList5 = []
                    sensorList6 = []
                    sensorList7 = []
                    sensorList8 = []
                    ladderList0.append(sensorList0)
                    ladderList1.append(sensorList1)
                    ladderList2.append(sensorList2)
                    ladderList3.append(sensorList3)
                    ladderList4.append(sensorList4)
                    ladderList5.append(sensorList5)
                    ladderList6.append(sensorList6)
                    ladderList7.append(sensorList7)
                    ladderList8.append(sensorList8)
                    # sensorNumber = sensor.getSensorNumber()
                    for side in range(2):
                        sideList0 = []
                        sideList1 = []
                        sideList2 = []
                        sideList3 = []
                        sideList4 = []
                        sideList5 = []
                        sideList6 = []
                        sideList7 = []
                        sideList8 = []
                        sensorList0.append(sideList0)
                        sensorList1.append(sideList1)
                        sensorList2.append(sideList2)
                        sensorList3.append(sideList3)
                        sensorList4.append(sideList4)
                        sensorList5.append(sideList5)
                        sensorList6.append(sideList6)
                        sensorList7.append(sideList7)
                        sensorList8.append(sideList8)

        for i in geoCache.getLayers(Belle2.VXD.SensorInfoBase.SVD):
            layerN = i.getLayerNumber()
            li = layerN - 3
            for j in geoCache.getLadders(i):
                ladderN = j.getLadderNumber()
                ldi = ladderN - 1
                for k in geoCache.getSensors(j):
                    sensorN = k.getSensorNumber()
                    si = sensorN - 1
                    for s in range(2):
                        for t in range(4):
                            self.resList[li][ldi][si][s].append(
                                TH1F("res" + "_" + str(k) + "." + str(s) + "." + str(t), " ", 200, -100, 100))
                            self.spList[li][ldi][si][s].append(
                                TH2D("sp" + "_" + str(k) + "." + str(s) + "." + str(t), " ", 300, -150, 150, 300, -150, 150))
                            self.cogList[li][ldi][si][s].append(
                                TH1F("cog" + "_" + str(k) + "." + str(s) + "." + str(t), " ", 200, -100, 100))
                            self.cdcList[li][ldi][si][s].append(
                                TH1F("cdc" + "_" + str(k) + "." + str(s) + "." + str(t), " ", 200, -100, 100))
                            self.snrList[li][ldi][si][s].append(
                                TH1F("snr" + "_" + str(k) + "." + str(s) + "." + str(t), " ", 100, 0, 100))
                            self.nList[li][ldi][si][s].append(0)
                            self.sumCOGList[li][ldi][si][s].append(0)
        #: distribution of EventT0
        self.EventT0Hist = TH1F("EventT0", " ", 200, -100, 100)
        #: alpha parameter vs TB, for U side
        self.AlphaUTB = TH2F("alphaVsTB_U", " ", 400, 0.5, 2, 4, 0, 4)
        self.AlphaUTB.GetXaxis().SetTitle("alpha")
        self.AlphaUTB.GetYaxis().SetTitle("trigger bin")
        #: alpha parameter vs TB, for V side
        self.AlphaVTB = TH2F("alphaVsTB_V", " ", 400, 0.5, 2, 4, 0, 4)
        self.AlphaVTB.GetXaxis().SetTitle("alpha")
        self.AlphaVTB.GetYaxis().SetTitle("trigger bin")
        #: beta parameter vs TB, for U side
        self.BetaUTB = TH2F("betaVsTB_U", " ", 200, -100, 100, 4, 0, 4)
        self.BetaUTB.GetXaxis().SetTitle("beta (ns)")
        self.BetaUTB.GetYaxis().SetTitle("trigger bin")
        #: beta parameter vs TB, for V side
        self.BetaVTB = TH2F("betaVsTB_V", " ", 200, -100, 100, 4, 0, 4)
        self.BetaVTB.GetXaxis().SetTitle("beta (ns)")
        self.BetaVTB.GetYaxis().SetTitle("trigger bin")

        #: mean of the residuals distribution vs TB, for V side
        self.MeanHistVTB = TH2F("meanHistVsTB_V", " ", 100, -10, 10, 4, 0, 4)
        self.MeanHistVTB.GetXaxis().SetTitle("distribution mean (ns)")
        self.MeanHistVTB.GetYaxis().SetTitle("trigger bin")
        #: mean of the residuals distribution vs TB, for U side
        self.MeanHistUTB = TH2F("meanHistVsTB_U", " ", 100, -10, 10, 4, 0, 4)
        self.MeanHistUTB.GetXaxis().SetTitle("distribution mean (ns)")
        self.MeanHistUTB.GetYaxis().SetTitle("trigger bin")
        #: RMS of the residuals distribution vs TB, for V side
        self.RMSHistVTB = TH2F("rmsHistVsTB_V", " ", 100, 0, 10, 4, 0, 4)
        self.RMSHistVTB.GetXaxis().SetTitle("distribution RMS (ns)")
        self.RMSHistVTB.GetYaxis().SetTitle("trigger bin")
        #: RMS of the residuals distribution vs TB, for U side
        self.RMSHistUTB = TH2F("rmsHistVsTB_U", " ", 100, 0, 10, 4, 0, 4)
        self.RMSHistUTB.GetXaxis().SetTitle("distribution RMS (ns)")
        self.RMSHistUTB.GetYaxis().SetTitle("trigger bin")
        #: mean of the residuals distribution vs TB, for V side (from gaussian fit)
        self.MeanFitVTB = TH2F("meanFitVsTB_V", " ", 100, -10, 10, 4, 0, 4)
        self.MeanFitVTB.GetXaxis().SetTitle("fit mean (ns)")
        self.MeanFitVTB.GetYaxis().SetTitle("trigger bin")
        #: mean of the residuals distribution vs TB, for U side (from gaussian fit)
        self.MeanFitUTB = TH2F("meanFitVsTB_U", " ", 100, -10, 10, 4, 0, 4)
        self.MeanFitUTB.GetXaxis().SetTitle("fit mean (ns)")
        self.MeanFitUTB.GetYaxis().SetTitle("trigger bin")
        #: RMS of the residuals distribution vs TB, for U side (from gaussian fit)
        self.RMSFitUTB = TH2F("rmsFitVsTB_U", " ", 100, 0, 10, 4, 0, 4)
        self.RMSFitUTB.GetXaxis().SetTitle("fit sigma (ns)")
        self.RMSFitUTB.GetYaxis().SetTitle("trigger bin")
        #: RMS of the residuals distribution vs TB, for V side (from gaussian fit)
        self.RMSFitVTB = TH2F("rmsFitVsTB_V", " ", 100, 0, 10, 4, 0, 4)
        self.RMSFitVTB.GetXaxis().SetTitle("fit sigma (ns)")
        self.RMSFitVTB.GetYaxis().SetTitle("trigger bin")

        #: gaus function used for fitting distributions
        self.gaus = TF1("gaus", 'gaus(0)', -150, 100)

        self.NTOT = 0

    def event(self):
        """
        Function that allows to cicle on the events
        """
        svd_evt_info = Belle2.PyStoreObj('SVDEventInfo')
        mode_byte = svd_evt_info.getModeByte()
        # timeClusterU = 0
        # timeClusterV = 0
        # sideIndex = 0
        # TBIndexU = 0
        # TBIndexV = 0
        #: counts the number of events
        self.Evt = self.Evt + 1

        #: registers PyStoreObj EventT0
        self.cdcEventT0 = Belle2.PyStoreObj(cdc_Time0)
        svdCluster_list = Belle2.PyStoreArray(svd_Clusters)
        # svdRecoDigit_list = Belle2.PyStoreArray(svd_recoDigits)

        for svdCluster in svdCluster_list:
            # svdRecoDigit = svdCluster.getRelatedTo(svd_recoDigits)
            self.fillLists(mode_byte, svdCluster)

    def terminate(self):
        """
        Terminates te class and produces the output rootfile
        """

        tfile = TFile(self.outputFileName, 'recreate')
        iov = Belle2.IntervalOfValidity.always()

        payload = Belle2.SVDCoGTimeCalibrations.t_payload()

        timeCal = SVDCoGCalibrationFunction()
        # Bias and Scale
        tbBias = [-50, -50, -50, -50]
        tbScale = [1, 1, 1, 1]
        tbBias_err = [1, 1, 1, 1]
        tbScale_err = [1, 1, 1, 1]
        # tbCovScaleBias = [1, 1, 1, 1]

        TCOGMEAN = 0
        T0MEAN = 0

        '''
        geoCache = Belle2.VXD.GeoCache.getInstance()
        for layer in geoCache.getLayers(Belle2.VXD.SensorInfoBase.SVD):
            layerNumber = layer.getLayerNumber()
            li = layerNumber - 3
            for ladder in geoCache.getLadders(layer):
                ladderNumber = ladder.getLadderNumber()
                ldi = ladderNumber - 1
                for sensor in geoCache.getSensors(ladder):
                    sensorNumber = sensor.getSensorNumber()
                    si = sensorNumber - 1
                    for side in range(2):
                        for tb in range(4):
                            n = self.nList[li][ldi][si][side][tb]
                            NTOT += n
        '''
        geoCache = Belle2.VXD.GeoCache.getInstance()
        gDirectory.mkdir("plots")
        gDirectory.cd("plots")
        for layer in geoCache.getLayers(Belle2.VXD.SensorInfoBase.SVD):
            layerNumber = layer.getLayerNumber()
            li = layerNumber - 3
            gDirectory.mkdir("layer" + str(layer))
            gDirectory.cd("layer" + str(layer))
            for ladder in geoCache.getLadders(layer):
                ladderNumber = ladder.getLadderNumber()
                ldi = ladderNumber - 1
                for sensor in geoCache.getSensors(ladder):
                    sensorNumber = sensor.getSensorNumber()
                    si = sensorNumber - 1
                    for side in range(2):
                        for tb in range(4):
                            # Resolution distribution Histograms with Gaussian Fit
                            res = self.resList[li][ldi][si][side][tb]
                            fitResult = int(TFitResultPtr(res.Fit(self.gaus, "R")))

                            if res.GetEntries() > 5:
                                if side == 1:
                                    self.MeanHistUTB.Fill(res.GetMean(), tb)
                                    self.RMSHistUTB.Fill(res.GetRMS(), tb)
                                    if fitResult > -1:
                                        self.MeanFitUTB.Fill(self.gaus.GetParameter(1), tb)
                                        self.RMSFitUTB.Fill(self.gaus.GetParameter(2), tb)
                                else:
                                    self.MeanHistVTB.Fill(res.GetMean(), tb)
                                    self.RMSHistVTB.Fill(res.GetRMS(), tb)
                                    if fitResult > -1:
                                        self.MeanFitVTB.Fill(self.gaus.GetParameter(1), tb)
                                        self.RMSFitVTB.Fill(self.gaus.GetParameter(2), tb)

                            res.Write()
                            # COG Distribution Histograms
                            cog = self.cogList[li][ldi][si][side][tb]
                            cog.Write()
                            # CDC EventT0 Distribution Histograms
                            cdc = self.cdcList[li][ldi][si][side][tb]
                            cdc.Write()
                            # SNR Distribution Histograms
                            snr = self.snrList[li][ldi][si][side][tb]
                            # snrMean = snr.GetMean()
                            snr.Write()
                            # ScatterPlot Histograms with Linear Fit
                            sp = self.spList[li][ldi][si][side][tb]
                            # covscalebias = sp.GetCovariance()
                            pfxsp = sp.ProfileX()
                            sp.Write()
                            pfxsp.Write()

                            if sp.GetRMS() != 0:
                                m = sp.GetCovariance() / pow(sp.GetRMS(1), 2)
                                # m = sp.GetCovariance()/cog.GetRMS()
                                m_err = 2 / pow(sp.GetRMS(), 3) * sp.GetRMSError() * sp.GetCovariance()
                                q = sp.GetMean(2) - m * sp.GetMean(1)
                                q_err = math.sqrt(pow(sp.GetMeanError(2), 2) +
                                                  pow(m * sp.GetMeanError(1), 2) + pow(m_err * sp.GetMean(1), 2))
                            else:
                                m = 1
                                m_err = 0
                                q = 0
                                q_err = 0

                            if side == 1:
                                self.AlphaUTB.Fill(m, tb)
                                self.BetaUTB.Fill(q, tb)
                            else:
                                self.AlphaVTB.Fill(m, tb)
                                self.BetaVTB.Fill(q, tb)

                            n = self.nList[li][ldi][si][side][tb]

                            tbBias[tb] = q
                            tbScale[tb] = m
                            tbBias_err[tb] = q_err
                            tbScale_err[tb] = m_err
                            TCOGMEAN += n * (m * self.sumCOGList[li][ldi][si][side][tb] / n + q) / self.NTOT

                        T0MEAN = self.EventT0Hist.GetMean()
                        '''
                        print(
                            "Mean of the CoG corrected distribution: " +
                            str(TCOGMEAN) +
                            " Mean of the T0 distribution: " +
                            str(T0MEAN))
                        '''
                        if not self.notApplyCDCLatencyCorrection:
                            tbBias[0] = tbBias[0] - T0MEAN
                            tbBias[1] = tbBias[1] - T0MEAN
                            tbBias[2] = tbBias[2] - T0MEAN
                            tbBias[3] = tbBias[3] - T0MEAN

                        timeCal.set_bias(tbBias[0], tbBias[1], tbBias[2], tbBias[3])
                        timeCal.set_scale(tbScale[0], tbScale[1], tbScale[2], tbScale[3])
                        print("setting CoG calibration for " + str(layerNumber) + "." + str(ladderNumber) + "." + str(sensorNumber))
                        payload.set(layerNumber, ladderNumber, sensorNumber, bool(side), 1, timeCal)
            gDirectory.cd("../")

        gDirectory.cd("../")
        self.AlphaUTB.Write()
        self.AlphaVTB.Write()
        self.BetaUTB.Write()
        self.BetaVTB.Write()
        self.MeanFitUTB.Write()
        self.MeanFitVTB.Write()
        self.RMSFitUTB.Write()
        self.RMSFitVTB.Write()
        self.MeanHistUTB.Write()
        self.MeanHistVTB.Write()
        self.RMSHistUTB.Write()
        self.RMSHistVTB.Write()
        self.EventT0Hist.Write()

        Belle2.Database.Instance().storeData(Belle2.SVDCoGTimeCalibrations.name, payload, iov)

        tfile.Close()


def read_file():
    """
    read_file - A function to read the data from input file and stores it into a list of lists
    :return: a list of lists which each list represents votes options given by each voter
    """
    file_name = input("Enter the name of the file: ")
    votes_result = []
    with open(file_name, 'r') as fh:
        for line in fh:
            vote = []
            for number in line.strip().split(','):
                try:
                    vote.append(int(number))
                except ValueError:
                    continue
            votes_result.append(vote)
    return votes_result

def get_candidates_id(votes_list):
    """
    get_candidates_id - A function to determine the ID of candidates who are still in competition
    :param votes_list: a list of lists containing votes for each candidate who is still in competition
    :return: a list of candidates' ID
    """
    candidates_id = []
    for i in range(len(votes_list)):
        for j in range(len(votes_list[i])):
            if votes_list[i][j] not in candidates_id:
                candidates_id.append(votes_list[i][j])
    return candidates_id

def get_votes_dict(votes_list):
    """
    get_votes_dict - A function to convert a list of votes to a dictionary structure type
    :param votes_list: a list of votes
    :return: votes_dict a dictionary, key: candidate' ID and value: the number of first place votes
    """
    candidates_id = get_candidates_id(votes_list)
    votes_dict = {}
    for i in range(len(candidates_id)):
        votes_dict[candidates_id[i]] = 0
        for j in range(len(votes_list)):
            if votes_list[j][0] == candidates_id[i]:
                votes_dict[candidates_id[i]] += 1
    return votes_dict

def eliminate_candidate(votes_dict):
    """
    eliminate_candidate - A function to determine which candidate has should be eliminated in a round,
    which incorporates the tie-breaking method for those candidates with equal first place votes
    :param votes_dict: a dictionary of votes, key: candidate's ID and value: the number of first place votes
    :return: a list of candidates which are eliminated
    """
    # calculate sum of first place votes
    sum_votes = 0
    for keys, values in votes_dict.items():
        sum_votes += values

    # determine the candidate with highest first place vote
    highest_votes = 0
    highest_candidate = ''
    for key, value in votes_dict.items():
        if highest_votes < value:
            highest_votes = value
            highest_candidate = key

    # check if candidate with highest first place votes has more than 50% votes and
    # produce an ordered list of eliminated candidates
    elimination_list = []
    if (highest_votes / sum_votes) * 100 > 50:
        for keys in sorted(votes_dict.keys()):
            if keys != highest_candidate:
                elimination_list.append(keys)
        elimination_list.append(highest_candidate)

    # otherwise, determine candidate with the minimum first place votes
    else:
        lowest_votes = highest_votes
        lowest_candidate = highest_candidate
        for keys, values in votes_dict.items():
            if lowest_votes > values:
                lowest_votes = values
                lowest_candidate = keys
            elif lowest_votes == values and lowest_candidate < keys:
                lowest_votes = values
                lowest_candidate = keys
        elimination_list.append(lowest_candidate)
    return elimination_list

def update_votes(votes_list, eliminated_list):
    """
    update_votes - A function to update the votes in the election by eliminating
    candidates with minimum first place vote.
    :param votes_list: a list of votes
    :param eliminated_list: a list of candidates who were eliminated in a round of competition
    :return: an updated list of votes without eliminated candidates
    """
    for i in range(len(votes_list)):
        if eliminated_list[0] in votes_list[i]:
            votes_list[i].remove(eliminated_list[0])
    votes_list = list(filter(None, votes_list))
    return votes_list

def main():
    votes_list = read_file()
    candidates_id = get_candidates_id(votes_list)
    votes_dict = get_votes_dict(votes_list)
    elimination_list = []
    elimination_list.extend(eliminate_candidate(votes_dict))
    while len(elimination_list) < len(candidates_id):
        votes_list = update_votes(votes_list, eliminate_candidate(votes_dict))
        votes_dict = get_votes_dict(votes_list)
        eliminate_candidate(votes_dict)
        elimination_list.extend(eliminate_candidate(votes_dict))

    # print candidates based on the elimination order
    print("Elimination order: ", end='')
    for i in range(len(elimination_list) - 1):
        print(elimination_list[i], end=', ')
    print(elimination_list[len(elimination_list) - 1])

main()


# Entries and Functions
import tkinter as tk
from tkinter import END

root = tk.Tk()
root.title("Entry Basics!")
root.geometry("500x500")
root.resizable(False, False)
root.iconbitmap("thinking.ico")

# Define functions
def make_label():
    ''' Print a label to the app '''
    text = tk.Label(output_frame, text=text_entry.get(), bg="#f00")
    text.pack()
    text_entry.delete(0, END)

def count_up(number):
    ''' Count up on the app '''
    # global value

    text = tk.Label(output_frame, text=number, bg="red")
    text.pack()

    value = number + 1

# Define Frames
input_frame = tk.Frame(root, bg="#00f", width=500, height=100)
input_frame.pack(padx=10, pady=10)

output_frame = tk.Frame(root, bg="#f00", width=500, height=400)
output_frame.pack(padx=10, pady=(0, 10))

# Add inputs
text_entry = tk.Entry(input_frame, width=40)
text_entry.grid(row=0, column=0, padx=5, pady=5)
input_frame.grid_propagate(False)

print_button = tk.Button(input_frame, text="Print", command=make_label)
print_button.grid(row=0, column=1, padx=5, pady=5, ipadx=30)

# Keep output frame size
output_frame.pack_propagate(False)

# Pass a parameter with lambda
value = True
count_button = tk.Button(input_frame, text="Count", command=lambda: count_up(value))
count_button.grid(row=1, column=0, columnspan=2, padx=5, pady=5, sticky="WE")

root.mainloop()


"""
File: preprocessText.py
Author: Saúl Sosa Díaz
Date: 26/04/2023
Description: The "preprocessText" function reads a CSV file containing text data, processes it, and writes the processed data to a text file named "NewsProcessed.txt" in a folder named "data" in the current directory.
into a text file named "NewsProcessed.txt" in a folder named "data" in the current directory.
"""

from utilTexts import *
import os

def preprocessTexts(nameFile):
    """
    The function creates a preprocessed test file by reading a CSV file, preprocessing the text data,
    and writing the preprocessed data to a text file.
    """
    print("Preproceando Nuevas noticias")
    df = readFileText(nameFile)
    Test = preprocessText(df['texto'])
    writeFile(os.path.join(".", "data", "NewsProcessed.txt"), Test)
    print(bcolors.OKGREEN + "Las noticias se han preprocesado correctamente." + bcolors.ENDC)

if __name__ == "__main__":
    preprocessText("test")


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

"""Messages."""

from dataclasses import dataclass
from math import ceil, log
from typing import Any, Dict, List, Optional, Union

from tno.mpc.encryption_schemes.shamir import ShamirSecretSharingScheme

from sacti.config import INPUT_BIT_LENGTH, PARTIES_LIST

class SightingShare(object):
    """SightingShare object."""

    def __init__(self, uuid: str, value: int, ss: ShamirSecretSharingScheme) -> None:
        """Initialize a new SightingShare object."""
        self.uuid = uuid
        self.bits_shares: Dict[int, CheckShares] = {
            p: CheckShares(self.uuid, [], None, None) for p in PARTIES_LIST
        }
        for i, l in enumerate(self._get_bits(value, INPUT_BIT_LENGTH)):
            for p in PARTIES_LIST:
                self.bits_shares[p].is_bit.append([])

            for b in l:
                onebit_shares = ss.share_secret(b).shares
                for party in PARTIES_LIST:
                    self.bits_shares[party].is_bit[i].append(onebit_shares[party])

    def _get_bits(self, amount: int, bitlength: int) -> List[List[int]]:
        bits = []
        for _ in range(bitlength):
            bit = amount & 1 if amount > 0 else 0
            amount = amount >> 1
            bits.append(bit)  # little-endian
        bits = bits[::-1]  # big-endian
        if bitlength <= 2:
            return [bits]

        return [bits] + self._get_bits(sum(bits), int(ceil(log(bitlength, 2))))

    def __repr__(self) -> str:
        """Represent a SightingShare object."""
        return f"SightingShare: uuid={self.uuid}, bit_shares={self.bits_shares}"

@dataclass
class CheckShares:
    """CheckShares dataclass."""

    uuid: str
    is_bit: List[List[int]]
    belongs: Optional[List[int]]
    is_zero: Optional[int]

@dataclass
class PrometheusEventMessage:
    """PrometheusEventMessage dataclass."""

    uuid: str
    sightings: Dict[str, Union[Dict[Any, Any], CheckShares, int]]
    damage: Union[Dict[int, Any], int, CheckShares]

class PrometheusEvent(object):
    """PrometheusEvent object."""

    def __init__(
        self,
        uuid: str,
        sightings: Dict[Any, Any],
        damage: int,
        ss: ShamirSecretSharingScheme,
    ) -> None:
        """Initialize a new PrometheusEvent."""
        super().__init__()
        self.uuid = uuid
        self.sightings = []

        for attribute_id, amount in sightings.items():
            self.sightings.append(SightingShare(attribute_id, amount, ss))
        self.damage = SightingShare("", damage, ss)

    def __repr__(self) -> str:
        """Represent PrometheusEvent."""
        return f"PrometheusEvent: uuid={self.uuid}, sightings={self.sightings}, damage={self.damage}"

    def generate_msg(
        self,
        parties: Optional[List[int]] = None,
    ) -> Dict[int, Dict[str, PrometheusEventMessage]]:
        """Generate message."""
        if parties is None:
            parties = PARTIES_LIST

        msg: Dict[int, Dict[str, PrometheusEventMessage]] = {p: {} for p in parties}
        for p in parties:
            msg[p] = {
                self.uuid: PrometheusEventMessage(
                    self.uuid,
                    {s.uuid: s.bits_shares[p] for s in self.sightings},
                    self.damage.bits_shares[p],
                )
            }
        return msg