import datetime

from logic.func import (
    check,
    write_db,
)

from logic.utils import conv_time

def make_real_numbers_of_shares_outstanding(
    all_sec_objects,
    each_shares_outstanding_object,
):
    if all_sec_objects:
        dif_1 = [
            all_sec_objects[-1].shares_outstanding * 1000000,
            float(each_shares_outstanding_object.get("val")) * 1000,
        ]
        dif_2 = [
            all_sec_objects[-1].shares_outstanding * 1000000,
            float(each_shares_outstanding_object.get("val")) / 1000,
        ]
        if 100 - (min(dif_1) / max(dif_1)) * 100 <= 20:
            shares_outstanding = round(
                float(each_shares_outstanding_object.get("val")) / 1000, 2
            )
        elif 100 - (min(dif_2) / max(dif_2)) * 100 <= 20:
            shares_outstanding = round(
                float(each_shares_outstanding_object.get("val")) / 1000000000, 2
            )
        else:
            shares_outstanding = round(
                float(each_shares_outstanding_object.get("val")) / 1000000, 2
            )
    else:
        shares_outstanding = (
            round(float(each_shares_outstanding_object.get("val")) / 1000000000, 2)
            if float(each_shares_outstanding_object.get("val")) > 1000000000
            else round(float(each_shares_outstanding_object.get("val")) / 1000000, 2)
        )

    return shares_outstanding

def save_db(
    session,
    model,
    name,
    ticker,
    date=None,
    end_date=None,
    shares=None,
    country=None,
    url=None,
    form=None,
):

    obj_to_write = (
        {
            "name": str(name),
            "ticker": str(ticker),
            "date": date,
            "shares_outstanding": shares,
            "end_date": end_date,
            "form": form,
        }
        if end_date
        else {
            "name": str(name),
            "ticker": str(ticker),
            "date": date,
            "shares_outstanding": shares,
        }
    )
    if country == "uk":
        obj_to_write.update({"url": url})
    from_date = datetime.datetime(2013, 1, 1)
    if date > from_date:
        db_obj_shares_with_such_date = (
            session.query(model).filter(model.name == name, model.date == date).first()
        )
        if end_date:
            lst_objects_of_model = session.query(model).filter(model.name == name).all()
            late = next(
                (
                    each_object_of_model
                    for each_object_of_model in lst_objects_of_model
                    if each_object_of_model.end_date > conv_time(end_date)
                    and each_object_of_model.date < date
                ),
                None,
            )
            if not late:
                if not db_obj_shares_with_such_date:
                    write_db(model, session, obj_to_write)
                elif db_obj_shares_with_such_date.form and form:
                    if db_obj_shares_with_such_date.end_date == conv_time(end_date):
                        prio = (
                            ("a", "not6"),
                            ("q", ""),
                            ("k", "not6"),
                            ("f", ""),
                            ("a", "6"),
                            ("6", ""),
                        )
                        my_form = next(
                            index for index, i in enumerate(prio) if check(i, form)
                        )
                        form_from_db = next(
                            index
                            for index, i in enumerate(prio)
                            if check(i, db_obj_shares_with_such_date.form)
                        )
                        if my_form <= form_from_db:
                            session.delete(db_obj_shares_with_such_date)
                            write_db(model, session, obj_to_write)
                    elif db_obj_shares_with_such_date.end_date < conv_time(end_date):
                        session.delete(db_obj_shares_with_such_date)
                        write_db(model, session, obj_to_write)
        elif not db_obj_shares_with_such_date:
            write_db(model, session, obj_to_write)


# coding: utf-8

__author__ = "lau.wenbo"

'''
存储数据至TXT文件中
'''

import requests
from pyquery import PyQuery as pq

url = "https://www.zhihu.com/explore"
headers = {
    "User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36"
}
html = requests.get(url=url, headers=headers).text
doc = pq(html)
items = doc('.explore-tab .feed-item').items()
for item in items:
    question = item.find('h2').text()
    author = item.find('.author-link-line').text()
    answer = pq(item.find('.content').html()).text()
    file = open('explore.txt', 'a', encoding='utf-8')
    file.write('\n'.join([question, author, answer]))
    file.close()


# 2022-2-14 给定数组nums，有序排列2n + 1个正整数
# 其中每个元素都会出现两次，唯有一个数只会出现一次。找出该数

class Solution(object):
    def singleNonDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = (len(nums) // 2) * 2
        for i in range(0, count, 2):
            if nums[i] == nums[i+1]:
                continue
            else:
                return nums[i]
        return nums[-1]


#! /usr/bin/python3
import os
import time
import pyqrcode
from pyqrcode import QRCode
from googlesearch import search
web= input("please enter topic: ")
# print(search(web))
url=[]
u=0
for i in search(web, stop=3):
	print(i)
	time.sleep(1)
	url.append(i)

print(url)

for i in range(3):
    qr= pyqrcode.create(url[u])
    qr.svg("url"+str(i)+".png", scale=8)
    u+=1
    print(qr.terminal())

os.system('mkdir /var/www/html/qr')

os.system('mv *.png /var/www/html/qr')


# DESAFIO 40 - Média Clássica.
nota1 = float(input("Digite a primeira nota: "))
nota2 = float(input("Digite a segunda nota:"))
media = (nota1 + nota2) / 2
print(f"Tirando {nota1} e {nota2}, a média do aluno é {media:.1f}")
resultado = 0
if media < 5:
    resultado = "REPROVADO!"
elif media >= 5 and media < 7:
    resultado = " em RECUPERAÇÃO!"
else:
    resultado = "APROVADO!"
print(f"O Aluno está {resultado} ")


import curses
import time

import RPi.GPIO as GPIO

MOTOR_RIGHT_IN1 = 31
MOTOR_RIGHT_IN2 = 29
MOTOR_RIGHT_ENABLE = 33
SENSOR_RIGHT = 37

MOTOR_LEFT_IN1 = 38
MOTOR_LEFT_IN2 = 40
MOTOR_LEFT_ENABLE = 32
SENSOR_LEFT = 36

GPIO.setmode(GPIO.BOARD)
GPIO.setup(MOTOR_RIGHT_IN1, GPIO.OUT)
GPIO.setup(MOTOR_RIGHT_IN2, GPIO.OUT)
GPIO.setup(MOTOR_RIGHT_ENABLE, GPIO.OUT)
GPIO.setup(MOTOR_LEFT_IN1, GPIO.OUT)
GPIO.setup(MOTOR_LEFT_IN2, GPIO.OUT)
GPIO.setup(MOTOR_LEFT_ENABLE, GPIO.OUT)

GPIO.setup(SENSOR_RIGHT, GPIO.IN)
GPIO.setup(SENSOR_LEFT, GPIO.IN)

PWM_RIGHT_ENABLE = GPIO.PWM(MOTOR_RIGHT_ENABLE, 1000)  # 1Khz
PWM_RIGHT_ENABLE.start(0)

PWM_LEFT_ENABLE = GPIO.PWM(MOTOR_LEFT_ENABLE, 1000)  # 1Khz
PWM_LEFT_ENABLE.start(0)

GPIO.output(MOTOR_RIGHT_IN1, GPIO.LOW)
GPIO.output(MOTOR_RIGHT_IN2, GPIO.LOW)
PWM_RIGHT_ENABLE.ChangeDutyCycle(0)

GPIO.output(MOTOR_LEFT_IN1, GPIO.LOW)
GPIO.output(MOTOR_LEFT_IN2, GPIO.LOW)
PWM_LEFT_ENABLE.ChangeDutyCycle(0)

# Get the curses window, turn off echoing of keyboard to screen, turn on
# instant (no waiting) key response, and use special values for cursor keys
screen = curses.initscr()
curses.noecho()
curses.cbreak()

screen.timeout(400)
screen.keypad(True)

PWM_DUTY_CYCLE_MINIMUM_PERCENT = 50
PWM_DUTY_CYCLE_MAXIMUM_PERCENT = 100
PWM_DUTY_CYCLE_PERCENT = 50

def left_motor_forward():
    GPIO.output(MOTOR_LEFT_IN1, GPIO.HIGH)
    GPIO.output(MOTOR_LEFT_IN2, GPIO.LOW)
    PWM_LEFT_ENABLE.ChangeDutyCycle(PWM_DUTY_CYCLE_PERCENT)

def left_motor_stop():
    GPIO.output(MOTOR_LEFT_IN1, GPIO.LOW)
    GPIO.output(MOTOR_LEFT_IN2, GPIO.LOW)
    PWM_LEFT_ENABLE.ChangeDutyCycle(0)

def left_motor_backward():
    GPIO.output(MOTOR_LEFT_IN1, GPIO.LOW)
    GPIO.output(MOTOR_LEFT_IN2, GPIO.HIGH)
    PWM_LEFT_ENABLE.ChangeDutyCycle(PWM_DUTY_CYCLE_PERCENT)

def right_motor_forward():
    GPIO.output(MOTOR_RIGHT_IN1, GPIO.HIGH)
    GPIO.output(MOTOR_RIGHT_IN2, GPIO.LOW)
    PWM_RIGHT_ENABLE.ChangeDutyCycle(PWM_DUTY_CYCLE_PERCENT)

def right_motor_stop():
    GPIO.output(MOTOR_RIGHT_IN1, GPIO.LOW)
    GPIO.output(MOTOR_RIGHT_IN2, GPIO.LOW)
    PWM_RIGHT_ENABLE.ChangeDutyCycle(0)

def right_motor_backward():
    GPIO.output(MOTOR_RIGHT_IN1, GPIO.LOW)
    GPIO.output(MOTOR_RIGHT_IN2, GPIO.HIGH)
    PWM_RIGHT_ENABLE.ChangeDutyCycle(PWM_DUTY_CYCLE_PERCENT)

try:
    while True:
        char = screen.getch()

        if char == curses.KEY_UP:
            print("up")
            left_motor_forward()
            right_motor_forward()
        elif char == curses.KEY_DOWN:
            print("down")
            left_motor_backward()
            right_motor_backward()
        elif char == curses.KEY_RIGHT:
            print("right")
            left_motor_forward()
            right_motor_stop()
        elif char == curses.KEY_LEFT:
            print("left")
            right_motor_forward()
            left_motor_stop()
        elif char == curses.KEY_PPAGE:
            print("DUTY CYCLE " + str(PWM_DUTY_CYCLE_PERCENT))
            PWM_DUTY_CYCLE_PERCENT += 1
            if PWM_DUTY_CYCLE_PERCENT >= PWM_DUTY_CYCLE_MAXIMUM_PERCENT:
                PWM_DUTY_CYCLE_PERCENT = PWM_DUTY_CYCLE_MAXIMUM_PERCENT
            time.sleep(0.1)
        elif char == curses.KEY_NPAGE:
            print("DUTY CYCLE " + str(PWM_DUTY_CYCLE_PERCENT))
            PWM_DUTY_CYCLE_PERCENT -= 1
            if PWM_DUTY_CYCLE_PERCENT <= PWM_DUTY_CYCLE_MINIMUM_PERCENT:
                PWM_DUTY_CYCLE_PERCENT = PWM_DUTY_CYCLE_MINIMUM_PERCENT
            time.sleep(0.1)
        else:
            print("stop motor")
            left_motor_stop()
            right_motor_stop()

finally:
    # Close down curses properly, inc turn echo back on!
    curses.nocbreak();
    screen.keypad(0);
    curses.echo()
    curses.endwin()

    left_motor_stop()
    right_motor_stop()


from pyspark.sql import DataFrame
from pyspark.sql.functions import col, concat, lit, when, trim, rpad, substring, concat_ws, regexp_replace, expr, element_at, array_position, size
from typing import Union

# TODO: Confermare l'ipotesi che NREA = 0 è invalido (è il default del campo)
def cciaaRea_transform(cciaa_column: str, nrea_column: str, cciaarea_column: str = "cciaaRea", drop = False):
  def _(df: DataFrame):
    df = df.withColumn(cciaarea_column, \
      when((trim(col(cciaa_column)) != "") & (col(nrea_column).cast("bigint") > 0), concat(trim(col(cciaa_column)), lit("/"), col(nrea_column).cast("bigint"))) \
      .otherwise(lit(None))
    )
    if (drop):
      df = df.drop(cciaa_column).drop(nrea_column)
    return df
  return _

# es. 00000DE129444585
def codiceFiscale_impresa_transform(codiceFiscale_in_column: str, codiceFiscale_out_column: str = "codiceFiscale", drop = False):
  """Create
  Args:
      codiceFiscale_in_column (str): [description]
      codiceFiscale_out_column (str, optional): [description]. Defaults to "codiceFiscale".
      drop (bool, optional): [description]. Defaults to False.
  """
  def _(df: DataFrame):
    df = (df
      .withColumn("__trimmed_IMS_C_FISCALE", trim(col(codiceFiscale_in_column)))
      .withColumn("__codiceFiscalePersonaUtilizzabile", col("__trimmed_IMS_C_FISCALE").rlike("[A-Z]{6}\d{2}"))
      .withColumn("__codiceFiscaleImpresaUtilizzabilePaddatoAllInizio", col("__trimmed_IMS_C_FISCALE").rlike("^[ 0O.\-*]{5}[0-9O]{11}$") & ~col("__trimmed_IMS_C_FISCALE").rlike("^[0O.\-*]+$"))
      .withColumn("__codiceFiscaleImpresaUtilizzabilePaddatoAllaFine", col("__trimmed_IMS_C_FISCALE").rlike("^[0-9O]{11}[ 0O.\-*]{5}$") & ~col("__trimmed_IMS_C_FISCALE").rlike("^[0O.\-*]+$"))
      .withColumn("__codiceFiscaleImpresaInternazionaleUtilizzabilePaddatoAllInizio", col("__trimmed_IMS_C_FISCALE").rlike("^[ 0O.\-*]{5}[a-zA-Z]{2}[0-9O]{9}$") & ~col("__trimmed_IMS_C_FISCALE").rlike("^[0O.\-*]+$"))
      .withColumn("__codiceFiscaleImpresaInternazionaleUtilizzabilePaddatoAllaFine", col("__trimmed_IMS_C_FISCALE").rlike("^[a-zA-Z]{2}[0-9O]{9}[ 0O.\-*]{5}$") & ~col("__trimmed_IMS_C_FISCALE").rlike("^[0O.\-*]+$"))
      .withColumn(codiceFiscale_out_column,
        when(col("__trimmed_IMS_C_FISCALE") == "", lit(None))
        .when(col("__codiceFiscalePersonaUtilizzabile"), col("__trimmed_IMS_C_FISCALE"))
        .when(col("__codiceFiscaleImpresaUtilizzabilePaddatoAllInizio"), regexp_replace(col("__trimmed_IMS_C_FISCALE").substr(-11, 11), "[O]", "0"))
        .when(col("__codiceFiscaleImpresaUtilizzabilePaddatoAllaFine"), regexp_replace(col("__trimmed_IMS_C_FISCALE").substr(1, 11), "[O]", "0"))
        .when(col("__codiceFiscaleImpresaInternazionaleUtilizzabilePaddatoAllInizio"), col("__trimmed_IMS_C_FISCALE").substr(-11, 11))
        .when(col("__codiceFiscaleImpresaInternazionaleUtilizzabilePaddatoAllaFine"), col("__trimmed_IMS_C_FISCALE").substr(1, 11))
        .otherwise(None)
      )
      .drop("__codiceFiscalePersonaUtilizzabile")
      .drop("__codiceFiscaleImpresaUtilizzabilePaddatoAllInizio")
      .drop("__codiceFiscaleImpresaUtilizzabilePaddatoAllaFine")
      .drop("__codiceFiscaleImpresaInternazionaleUtilizzabilePaddatoAllInizio")
      .drop("__codiceFiscaleImpresaInternazionaleUtilizzabilePaddatoAllaFine")
      .drop("__trimmed_IMS_C_FISCALE")
    )

    if (drop):
      df = df.drop(codiceFiscale_in_column)
    return df
  return _

def codiceFiscale_persona_transform(codiceFiscale_in_column: str, codiceFiscale_out_column: str = "codiceFiscale", drop = False):
  def _(df: DataFrame):
    df = df \
      .withColumn("__trimmed_IMS_C_FISCALE", trim(col(codiceFiscale_in_column))) \
      .withColumn("__codiceFiscalePersonaUtilizzabile", col("__trimmed_IMS_C_FISCALE").rlike("[A-Z]{6}\d{2}")) \
      .withColumn(codiceFiscale_out_column, \
        when(col("__trimmed_IMS_C_FISCALE") == "", lit(None)) \
        .when(col("__codiceFiscalePersonaUtilizzabile"), col("__trimmed_IMS_C_FISCALE")) \
        .otherwise(None) \
      ) \
      .drop("__codiceFiscalePersonaUtilizzabile") \
      .drop("__trimmed_IMS_C_FISCALE")

    if (drop):
      df = df.drop(codiceFiscale_in_column)

    return df
  return _

def date_transform(date_in_column: str, date_out_column: str, drop = False):
  def _(df: DataFrame):
    df = df.withColumn(date_out_column, when(col(date_in_column).isNotNull() & (col(date_in_column) != "0001-01-01"), col(date_in_column).cast("date")).otherwise(None))
    if (drop):
      df = df.drop(date_in_column)
    return df
  return _

def timestamp_transform(date_in_column: str, date_out_column: str, drop = False):
  def _(df: DataFrame):
    df = df.withColumn(date_out_column, when(col(date_in_column).isNotNull(), col(date_in_column).cast("timestamp")).otherwise(None))
    if (drop):
      df = df.drop(date_in_column)
    return df
  return _

def numeric_transform(in_column: str, out_column: str, missing = 0, value_type = "bigint", drop = False):
  def _(df: DataFrame):
    df = df \
      .withColumn("__numeric_transform_valore", col(in_column).cast(value_type)) \
      .withColumn(out_column, \
        when(col("__numeric_transform_valore").isNotNull() & (col("__numeric_transform_valore") != missing), col("__numeric_transform_valore")) \
        .otherwise(lit(None).cast(value_type))
      ) \
      .drop("__numeric_transform_valore")
    if (drop):
      df = df.drop(in_column)
    return df
  return _

def string_transform(in_column: str, out_column: str, missing: Union[str, None] = None, drop = False):
  def _(df: DataFrame):
    df = df.withColumn(out_column, when(col(in_column).isNotNull() & (trim(col(in_column)) != ""), trim(col(in_column))).otherwise(missing))
    if (drop):
      df = df.drop(in_column)
    return df
  return _

def ateco_transform(in_column: str, out_column: str, drop = False):
  def _(df: DataFrame):
    df = df \
      .withColumn("__ateco2007Codice", rpad(trim(col(in_column)), 6, "0")) \
      .withColumn(out_column, concat_ws(".", substring(col("__ateco2007Codice"), 1, 2), substring(col("__ateco2007Codice"), 3, 2), substring(col("__ateco2007Codice"), 5, 2))) \
      .drop("__ateco2007Codice")
    if (drop):
      df = df.drop(in_column)
    return df
  return _

def codiceFiscale_persona_fisica_valido_transform(in_column: str, out_column: str):
  def _(df: DataFrame):
    df = df \
      .withColumn(out_column, col(in_column).rlike("^[A-Z]{6}\d{2}[A-Z]\d{2}[A-Z]\d{3}[A-Z]$"))
    return df
  return _

def codiceFiscale_persona_giuridica_paddato_valido_transform(in_column: str, out_column: str):
  def _(df: DataFrame):
    df = df \
      .withColumn(out_column, col(in_column).rlike("^00000\d{11}$") & (col("__trimmed_IMS_C_FISCALE") != "00000000000"))
    return df
  return _

def indirizzo_impresa_transform(out_column: str, decodifica_via_df: DataFrame):
  def _(df: DataFrame):
    df = (df
      .transform(string_transform("IMS_C_VIA", "__trimmed_IMS_C_VIA"))
      # Decodifica il toponimo dell'indirizzo e crea una stringa indirizzo
      .join(decodifica_via_df.select(col("codice").alias("__trimmed_IMS_C_VIA"), col("descrizione").alias("__IMS_C_VIA_decodificato")), ["__trimmed_IMS_C_VIA"], how="left")
      .withColumn("indirizzoSedeToponimo",
        when(col("__IMS_C_VIA_decodificato").isNotNull(), col("__IMS_C_VIA_decodificato"))
        .when(col("__trimmed_IMS_C_VIA").isNotNull(), col("__trimmed_IMS_C_VIA"))
      )
      .drop("__trimmed_IMS_C_VIA").drop("__IMS_C_VIA_decodificato")
      .transform(string_transform("IMS_VIA", "indirizzoSedeVia"))
      .transform(string_transform("IMS_N_CIVICO", "indirizzoSedeNumeroCivico"))
      .transform(string_transform("IMS_COMUNE", "indirizzoSedeComune"))
      .transform(string_transform("IMS_C_COMUNE", "indirizzoSedeComuneCodiceISTAT"))
      .transform(string_transform("IMS_FRAZIONE", "indirizzoSedeFrazione"))
      .transform(string_transform("IMS_CAP", "indirizzoSedeCAP"))
      .transform(string_transform("IMS_SGL_PROVINCIA", "indirizzoSedeSiglaProvincia"))
      .transform(string_transform("indirizzoSedeSiglaProvincia", "indirizzoSedeProvincia"))
      .transform(string_transform("IMS_CAP", "indirizzoSedeCAP"))
      .withColumn("__indirizzo",
        when(col("indirizzoSedeVia").isNotNull(),
          concat(
            when(col("indirizzoSedeToponimo").isNotNull(), concat(col("indirizzoSedeToponimo"), lit(" "))).otherwise(lit("")),
            col("indirizzoSedeVia"),
            lit(","),
            when(col("indirizzoSedeNumeroCivico").isNotNull(), concat(lit(" "), col("indirizzoSedeNumeroCivico"), lit(","))).otherwise(lit(""))
          )
        )
      )
      .withColumn("__provincia", when(col("indirizzoSedeProvincia").isNotNull(), concat(lit("("), col("indirizzoSedeProvincia"), lit(")"))).otherwise(lit("")))
      .withColumn("__localita",
        when(col("indirizzoSedeCAP").isNotNull() & col("indirizzoSedeFrazione").isNotNull() & col("indirizzoSedeComune").isNotNull(),
          concat(col("indirizzoSedeCAP"), lit(" "), col("indirizzoSedeFrazione"), lit(" "), col("indirizzoSedeComune"))
        )
        .when(col("indirizzoSedeCAP").isNotNull() & col("indirizzoSedeFrazione").isNotNull() & col("indirizzoSedeComune").isNull(),
          concat(col("indirizzoSedeCAP"), lit(" "), col("indirizzoSedeFrazione"))
        )
        .when(col("indirizzoSedeCAP").isNotNull() & col("indirizzoSedeFrazione").isNull() & col("indirizzoSedeComune").isNotNull(),
          concat(col("indirizzoSedeCAP"), lit(" "), col("indirizzoSedeComune"))
        )
        .when(col("indirizzoSedeCAP").isNotNull() & col("indirizzoSedeFrazione").isNull() & col("indirizzoSedeComune").isNull(),
          concat(col("indirizzoSedeCAP"))
        )
        .when(col("indirizzoSedeCAP").isNull() & col("indirizzoSedeFrazione").isNotNull() & col("indirizzoSedeComune").isNotNull(),
          concat(col("indirizzoSedeFrazione"), lit(" "), col("indirizzoSedeComune"))
        )
        .when(col("indirizzoSedeCAP").isNull() & col("indirizzoSedeFrazione").isNotNull() & col("indirizzoSedeComune").isNull(),
          col("indirizzoSedeFrazione")
        )
        .when(col("indirizzoSedeCAP").isNull() & col("indirizzoSedeFrazione").isNull() & col("indirizzoSedeComune").isNotNull(),
          col("indirizzoSedeComune")
        )
        # Caso .when(col("indirizzoSedeCAP").isNull() & col("indirizzoSedeFrazione").isNull() & col("indirizzoSedeComune").isNull(),
        .otherwise(lit(""))
      )
      .withColumn(out_column,
        when(col("__indirizzo").isNotNull(), concat_ws(" ", col("__indirizzo"), col("__localita"), col("__provincia"), col("paese")))
        .otherwise(concat_ws(" ", col("__localita"), col("__provincia"), col("paese")))
      )
    )
    return df
  return _

def indirizzo_unita_locale_transform(out_column: str, decodifica_via_df: DataFrame):
  def _(df: DataFrame):
    df = (df \
      .withColumn("__trimmed_ULS_C_VIA", trim(col("ULS_C_VIA"))) \
      # Decodifica il toponimo dell'indirizzo e crea una stringa indirizzo
      .join(decodifica_via_df.select(col("codice").alias("__trimmed_ULS_C_VIA"), col("descrizione").alias("__ULS_C_VIA_decodificato")), ["__trimmed_ULS_C_VIA"], how="left") \
      .withColumn("indirizzoSedeToponimo", \
        when(col("__ULS_C_VIA_decodificato").isNotNull(), col("__ULS_C_VIA_decodificato")) \
        .otherwise(col("ULS_C_VIA"))
      ) \
      .drop("__trimmed_ULS_C_VIA").drop("__ULS_C_VIA_decodificato") \
      .withColumn("indirizzoSedeVia", trim(col("ULS_VIA"))) \
      .withColumn("indirizzoSedeNumeroCivico", trim(col("ULS_N_CIVICO"))) \
      .withColumn("indirizzoSedeComune", trim(col("ULS_COMUNE"))) \
      .withColumn("indirizzoSedeComuneCodiceISTAT", trim(col("ULS_C_COMUNE"))) \
      .withColumn("indirizzoSedeCAP", trim(col("ULS_CAP"))) \
      .withColumn("indirizzoSedeSiglaProvincia", trim(col("ULS_SGL_PRV"))) \
      .withColumn("indirizzoSedeProvincia", trim(col("indirizzoSedeSiglaProvincia"))) \
      \
      .withColumn(out_column, concat( \
        col("indirizzoSedeToponimo"), \
        lit(" "), \
        col("indirizzoSedeVia"), \
        lit(", "), \
        col("indirizzoSedeNumeroCivico"), \
        lit(", "), \
        concat(col("indirizzoSedeCAP"), lit(" "), col("indirizzoSedeComune"), lit(" ("), col("indirizzoSedeProvincia"), lit(")")), \
        lit(" "), \
        col("paese"), \
      ))
    )
    return df
  return _

def valore_valuta_transform(valore_column: str, valuta_column: str, euro_column: str):
  """
  Ritorna una trasformazione che converte in euro la colonna `valore_column` espressa
  in valuta `valuta_column` e crea la colonna `euro_column`.

  Attenzione! Non c'è una valuta di default, quindi se il campo valuta_column non è presente
  o non è supportato, `euro_column` avrà valore `null`.

  Parametri
    `valore_column` nome della colonna con il valore.
    `valuta_column` nome della colonna con la valuta in cui è espresso il valore.
    `euro_column` nome della colonna con la valuta espressa in auro.

  Return
    la trasformazione.

  Esempio
    >>> from common.transforms import valore_valuta_transform
    >>> df = df.transform(valore_valuta_transform("TIT_VALORE", "TIT_VALUTA", "valoreTitolo"))

    +---------------+-----------------------------+
    | valore_column | valuta_column | euro_column |
    +---------------+---------------+-------------+
    | 1936.27       |             L |           1 |
    +---------------+---------------+-------------+
  """
  def _(df: DataFrame):
    df = df \
      .withColumn(euro_column, \
        when(trim(col(valuta_column)) == 'EU', col(valore_column).cast("float")) \
        .when(trim(col(valuta_column)) == 'L', col(valore_column).cast("float") / 1936.27) \
      )
    return df
  return _

def country_to_iso3166_transform(in_column: str, country_iso3166alpha2_column: str, country_iso3166name_column: str, iso3166_df: DataFrame):
  def _(df: DataFrame):
    df = df \
      .withColumn("__paeseCodice", \
        when(col(in_column).isNotNull() & (trim(col(in_column)) != ""), trim(col(in_column))) \
        .otherwise("I") \
        ).join(iso3166_df.select( \
          col("infocamere_id").alias("__paeseCodice"),
          col("iso_id").alias("__iso_id"), \
          col("iso_name").alias("__iso_name"), \
        ), ["__paeseCodice"], how="left") \
      .withColumn(country_iso3166alpha2_column, \
        when(col('__iso_id').isNotNull(), col("__iso_id")) \
        .otherwise("XE") \
      ) \
      .withColumn(country_iso3166name_column, \
        when(col('__iso_name').isNotNull(), col("__iso_name")) \
        .otherwise("Non esistente") \
      ) \
      .drop("__paeseCodice", "__iso_name", "__iso_id")
    return df
  return _

# TODO: documentare che in mancanza di informazioni sul passato estendiamo la validità del primo dato conosciuto
def valid_value_at_transform(values_array_column: str, values_dates_column: str, after_column: str, value_name: str, extend_past = True):
  def _(df: DataFrame):

    df = df \
      .withColumn("__dataProduzioneDopoOUgualeATipoImpresaTempi", expr(f"transform({values_dates_column}, date -> {after_column} >= date)")) \
      .withColumn("__tipoImpresaIndiceValido", array_position(col("__dataProduzioneDopoOUgualeATipoImpresaTempi"), False) - 1) \
      .withColumn(value_name, \
        when(col("__tipoImpresaIndiceValido") >= 1, element_at(col(values_array_column), col("__tipoImpresaIndiceValido").cast("integer"))) \
        .when(col("__tipoImpresaIndiceValido") == 0, \
          when(lit(extend_past), element_at(col(values_array_column), 1)) \
          .otherwise(lit(None))
        ) \
        .otherwise(element_at(col(values_array_column), size(col(values_array_column)))) \
      ) \
      .drop("__dataProduzioneDopoOUgualeATipoImpresaTempi", "__tipoImpresaIndiceValido") \

    return df
  return _


import argparse

from cosmpy.aerial.client import LedgerClient, NetworkConfig
from cosmpy.aerial.contract import LedgerContract
from cosmpy.aerial.wallet import LocalWallet
from cosmpy.crypto.address import Address
from cosmpy.crypto.keypairs import PrivateKey

def _parse_commandline():
    parser = argparse.ArgumentParser()
    parser.add_argument("contract_path", help="The path to the contract to upload")
    parser.add_argument(
        "contract_address",
        nargs="?",
        type=Address,
        help="The address of the contract is already deployed",
    )
    return parser.parse_args()

def main():
    args = _parse_commandline()

    wallet = LocalWallet(PrivateKey("T7w1yHq1QIcQiSqV27YSwk+i1i+Y4JMKhkpawCQIh6s="))

    ledger = LedgerClient(NetworkConfig.latest_stable_testnet())

    contract = LedgerContract(args.contract_path, ledger, address=args.contract_address)
    contract.deploy({}, wallet)

    print(f"Contract deployed at: {contract.address}")

    result = contract.query({"get": {"owner": str(wallet.address())}})
    print("Initial state:", result)

    contract.execute({"set": {"value": "foobar"}}, wallet).wait_to_complete()

    result = contract.query({"get": {"owner": str(wallet.address())}})
    print("State after set:", result)

    contract.execute({"clear": {}}, wallet).wait_to_complete()

    result = contract.query({"get": {"owner": str(wallet.address())}})
    print("State after clear:", result)

if __name__ == "__main__":
    main()


"""Filesystem utility functions."""
from __future__ import absolute_import
import os, glob
import errno
import torch
import logging

from ..config import cfg

def save_checkpoint(args, model, epoch, optimizer=None, lr_scheduler=None, is_best=False):
    """Save Checkpoint"""
    directory = os.path.expanduser(cfg.TRAIN.MODEL_SAVE_DIR)
    if not os.path.exists(directory):
        os.makedirs(directory)
    model_state_dict = model.module.state_dict() if hasattr(model, 'module') else model.state_dict()
    filename = '{}_epoch_{}.pth'.format(cfg.TIME_STAMP, str(epoch))
    if is_best:
        best_filename = 'best_model.pth'
        best_filename = os.path.join(directory, best_filename)
        torch.save(model_state_dict, best_filename)
    else:
        pre_filename = glob.glob('{}*.pth'.format(cfg.TIME_STAMP))
        try:
            for p in pre_filename:
                os.remove(p)
        except OSError as e:
            logging.info(e)

        # save epoch
        save_state = {
            'epoch': epoch,
            'state_dict': model_state_dict,
            'optimizer': optimizer.state_dict(),
            'lr_scheduler': lr_scheduler.state_dict()
        }
        filename = os.path.join(directory, filename)
        if not args.distributed or (args.distributed and args.local_rank % args.num_gpus == 0):
            torch.save(save_state, filename)
            # logging.info('Epoch {} model saved in: {}'.format(epoch, filename))

def makedirs(path):
    """Create directory recursively if not exists.
    Similar to `makedir -p`, you can skip checking existence before this function.
    Parameters
    ----------
    path : str
        Path of the desired dir
    """
    try:
        os.makedirs(path)
    except OSError as exc:
        if exc.errno != errno.EEXIST:
            raise


"""
Create a Python program that reads a text file and counts the occurrences of each
word using a dictionary. The program should print the words and their counts.
"""

def count_words(file_path: str):
    all_words = {}

    with open(file_path, "r") as file:
        text = file.read()

    words = text.split()
    for word in words:
        if word in all_words:
            all_words[word] += 1
        else:
            all_words[word] = 1

    return all_words
print(count_words("example.txt"))


"""Parse output from clang-tidy's stdout"""
import argparse
import pathlib
import json
from typing import Dict, Union, List
import logging

log_commander = logging.getLogger("PylintMatcher")
log_commander.setLevel(logging.DEBUG)  # be sure that log commands are output
console_handler = logging.StreamHandler()  # Create special stdout stream handler
console_handler.setFormatter(logging.Formatter("%(message)s"))  # no formatted log cmds
log_commander.addHandler(console_handler)  # Use special handler for log_commander
log_commander.propagate = False  # prevent duplicate messages in the parent logger obj

def annotate_pylint_note(obj: Dict[str, Union[int, str]]) -> str:
    """Translate a 1 notification from pylint to github's checks API.

    :param dict obj: The JSON object output by pylint (for 1 notification).
        A typical JSON object output from pylint looks like:

        .. code-block:: json

            {
                "type": "error",
                "module": "basic_test",
                "obj": "",
                "line": 3,
                "column": 19,
                "path": "tests/basic_test.py",
                "symbol": "syntax-error",
                "message": "invalid syntax (<unknown>, line 3)",
                "message-id": "E0001"
            }

    :Returns:
        A `str` that can be used by github's workflow log commands.
    """
    priority = {
        "convention": "notice",
        "refactor": "notice",
        "warning": "warning",
        "error": "error",
        "fatal": "error",
    }
    return (
        "::{level} file={path},line={line},title={path}:{line}:{col} {symbol} [{code}]"
        "::{msg}".format(
            level=priority[obj["type"]],
            path=obj["path"],
            line=obj["line"],
            col=obj["column"],
            symbol=obj["symbol"],
            code=obj["message-id"],
            msg=obj["message"],
        )
    )

if __name__ == "__main__":
    arg_parser = argparse.ArgumentParser()
    arg_parser.add_argument("json_output", type=pathlib.Path)
    args = arg_parser.parse_args()

    pylint_result: List[Dict[str, Union[int, str]]] = json.loads(
        pathlib.Path(args.json_output).read_text(encoding="utf-8")
    )
    for note in pylint_result:
        log_commander.info(annotate_pylint_note(note))


import re
def cleaner(path):
    file = open(path)
    line2 = ""
    for line in file.readlines():
        m = re.split("\s+",line)
        line1 = ""
        for word in m:
            line1 = line1 + word + ","
        line2 = line2 + line1[:len(line1)-2] + "\n"
    file.close()
    file = open(path,"w")
    file.write(line2)
    file.close()

cleaner("data.txt")


import os
import cv2
import numpy
from PIL import Image
import wsq
import shutil
import sys

class FingerData:

  def __init__(self, sample, file):
    self.main = file
    self.sample = sample
    # self.home = homeDir

  # Compares sample file with fingerprint entries
  def match(self):

    # sampleFile = os.listdir(self.destination)   # assigning sample file a variable
    sampleFile = numpy.array(Image.open("Temp/"+self.sample))
    best_score = 0.0

    # # Group finger data into an array
    # self.fileCount = len(os.listdir(self.dir))

    # if (self.fileCount%self.modulo):
    #     splitNum = self.fileCount%self.modulo
    # else:
    #     splitNum = (self.fileCount)/self.modulo

    # self.dataList = numpy.array_split(os.listdir(self.dir), splitNum)

    # for i in range(len(self.dataList)):
    #   # print("Scanning Array: "+str(i))
    #   if (os.path.exists(self.home+"Temp")):
    #     shutil.rmtree(self.home+"Temp")

    #   for file in self.dataList[i]:
    #     filePath = self.dir+file
    #     self.sample_conversion(filePath, "Temp")

    #     filePath = self.home+"Temp/"+file+".png"
    dataFile = numpy.array(Image.open("Temp/"+self.main))

    # Matching Algorithm
    sift = cv2.SIFT_create()

    keypoints_1, descriptors_1 = sift.detectAndCompute(sampleFile, None)
    keypoints_2, descriptors_2 = sift.detectAndCompute(dataFile, None)

    matches = cv2.FlannBasedMatcher({'algorithm': 1, 'trees': 10},
                                            {}).knnMatch(descriptors_1, descriptors_2, k=2)

    match_points = []
    for p, q in matches:
        if p.distance < 0.1 * q. distance:
            match_points.append(p)

    keypoints = 0
    if len (keypoints_1) < len (keypoints_2):
        keypoints = len(keypoints_1)
    else:
        keypoints = len(keypoints_2)

    if len (match_points) / keypoints * 100 > best_score:
        best_score = len(match_points) / keypoints * 100

    if best_score > 80.0:
      return {"response": 200, "score": best_score, "Name": self.main}

    return {"response": 404, "score": best_score, "Name": self.main}

  def clean(self):
    shutil.rmtree("Temp")

class FingerConversion:
  def __init__(self, file):
    self.file = file
    self.destination = "Temp"

  def sample_conversion(self):
    finger_image = Image.open(self.file)
    finger_image = finger_image.convert('L')

    try:
        os.mkdir(self.destination)
    except:
        print(self.destination+" folder exists.")

    name, ext = os.path.splitext(self.file)
    newName = name+".png"
    finger_image.save(newName)

    try:
      shutil.move(newName, self.destination)
      return str(newName)
    except:
      os.remove(newName)
      sys.exit(name+" is already in "+ self.destination + " folder, delete and restart process")


from random import choice

class RandomWalk():

    def __init__(self, dot_ammount=1000):

        self.dot_ammount = dot_ammount

        self.x_values = [0]
        self.y_values = [0]

    def get_step(self):

        xy_direction = choice([1,-1])
        xy_rand = choice([0,1,2,3,4,5,6,7,8,9])
        xy_step = xy_direction * xy_rand

        return xy_step

    def cords_gen(self):

        while len(self.x_values) < self.dot_ammount:

            x_step = self.get_step()
            y_step = self.get_step()

            if x_step == 0 and y_step == 0:
                continue

            x = self.x_values[-1] + x_step
            y = self.y_values[-1] + y_step

            self.x_values.append(x)
            self.y_values.append(y)


from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
from .views import UserPublicProfile

app_name = "users"

urlpatterns=[
	path('login/',auth_views.LoginView.as_view(template_name='users/login.html'),
												name='userLogin'),

	path('logout/',views.userLogout,name='userLogout'),
	path('signup/',views.userSignup,name='userSignup'),
	path('profile/',views.userProfile,name='userProfile'),
	path('profiles/<str:username>',UserPublicProfile.as_view(),
									name='userPublicProfile'),

	path('profile/update/',views.userProfileUpdate,name='userProfileUpdate'),

]


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb  6 08:58:45 2019

@author: hans-werner
"""
#
# Import libraries
#
# Import Python numerical library
import numpy as np

# Import plotting tools
import matplotlib.pyplot as plt

# Import our benchmark functions
from benchmark_functions import quadratic, rosenbrock

# Import our linesearch algorithm
from line_search import steepest_descent

def test_sd_quadratic():
    #
    # Quadratic Function
    #
    A = np.array([[1,0],[0,2]])
    b = np.array([1,1])
    c = 0

    # Define function for specfic parameter values
    f = lambda x: quadratic(x,A,b,c)

    # Set optimization parameters
    tol = 1e-6;
    k_max = 100;
    x0 = np.array([4,2])

    #
    # Run steepest descent method
    #
    xs, it_record, xk_record, converged = steepest_descent(f, x0, tol, k_max)

    # Extract convergence information
    iterations = it_record[:,0]
    fk = it_record[:,1]
    norm_gk = it_record[:,2]

    #
    # Optimal values
    #
    x_opt = np.linalg.solve(0.5*(A+A.T),-b)
    f_opt = f(x_opt)[0]
    #
    # Compute errors
    #
    errors = np.empty(xk_record.shape)
    errors[:,0] = xk_record[:,0]-x_opt[0]
    errors[:,1] = xk_record[:,1]-x_opt[1]
    e_norm = np.sqrt(errors[:,0]**2+errors[:,1]**2)

    if converged:
        print('Converged in %d steps'%(iterations[-1]))

    #
    # Plot results
    #
    fig, ax = plt.subplots(3,1, sharex=True)
    plt.subplots_adjust(hspace=0.5)

    # Plot errors in function values
    ax[0].semilogy(iterations, np.abs(fk-f_opt), '.-')
    ax[0].set_title('log(|f(xk)-f(x*)|)')

    # Plots norm of the gradient
    ax[1].semilogy(iterations, norm_gk,'.-')
    ax[1].set_title('log(|grad(f)|)')

    ax[2].semilogy(iterations, e_norm,'.-')
    ax[2].set_title('log(|xk-x*|)')

    plt.xlabel('iterations')
    plt.savefig('question9_convergence_plots.png')

    # Return values for use in calculate_rho function.
    return xk_record, x_opt

def test_sd_rosenbrock():
    """
    Test the steepest descent method for the Rosenbrock function
    """
    pass

def compute_rho(iterates, minimizer):

    # Compute errors at each step.
    errors = iterates - minimizer
    errors = np.sqrt(errors[:, 0]**2 + errors[:, 1]**2)

    # Find error ratios - round to 6 decimal places.
    error_ratios = np.around(np.divide(errors[1:], errors[:-1]), 6)

    # Find largest error ratio (smallest percent decrease).
    return np.max(error_ratios)

if __name__ == '__main__':

    x_k, x_opt = test_sd_quadratic()

    print(compute_rho(x_k, x_opt))


from __future__ import annotations

import sys
from typing import Callable, Dict, FrozenSet, Iterable, List, TypeVar

from networkx import DiGraph, Graph

from .cluster import Cluster
from .unrooted_hierarchical_clusterer import UnrootedHierarchicalClusterer

T = TypeVar("T")

class NeighborJoiningClusterer(UnrootedHierarchicalClusterer[T]):
    def __init__(self, get_distance: Callable[[T, T], float]) -> None:
        self._get_distance = get_distance

    def generate_clusters(self, data_objects: Iterable[T]) -> Graph[Cluster[T]]:
        tree: DiGraph[Cluster[T]] = DiGraph()
        clusters: List[Cluster[T]] = []
        for data_object in data_objects:
            cluster = Cluster[T](data_object, description=str(data_object))
            clusters.append(cluster)
            tree.add_node(cluster, cluster=cluster)

        distances: Dict[FrozenSet[Cluster[T]], float] = {}
        for i in range(len(clusters)):
            for j in range(i + 1, len(clusters)):
                distance = self._get_distance(
                    next(iter(clusters[i].data_objects)), next(iter(clusters[j].data_objects))
                )
                distances[frozenset([clusters[i], clusters[j]])] = distance

        while len(clusters) > 2:
            r = {
                c: sum(distances[frozenset([c, oc])] / (len(clusters) - 2) for oc in clusters if oc is not c)
                for c in clusters
            }
            min_i = 0
            min_j = 0
            min_dist = 0
            min_q = sys.float_info.max
            for i in range(len(clusters)):
                for j in range(i + 1, len(clusters)):
                    dist = distances[frozenset([clusters[i], clusters[j]])]
                    q = dist - r[clusters[i]] - r[clusters[j]]
                    if q < min_q:
                        min_q = q
                        min_dist = dist
                        min_i = i
                        min_j = j

            i_cluster = clusters[min_i]
            j_cluster = clusters[min_j]
            del distances[frozenset([i_cluster, j_cluster])]

            u_cluster = Cluster[T](description="BRANCH")
            tree.add_node(u_cluster, cluster=u_cluster)

            i_len = (min_dist / 2) + ((r[i_cluster] - r[j_cluster]) / 2)
            if i_len <= 0 and tree.out_degree(i_cluster) > 0:
                for _, target, data in tree.out_edges(i_cluster, data=True):
                    tree.add_edge(u_cluster, target, weight=data["weight"])
                tree.remove_node(i_cluster)
            else:
                tree.remove_edges_from(tree.in_edges(i_cluster))
                tree.add_edge(u_cluster, i_cluster, weight=max(i_len, 0))
            j_len = min_dist - i_len
            if j_len <= 0 and tree.out_degree(j_cluster) > 0:
                for _, target, data in tree.out_edges(j_cluster, data=True):
                    tree.add_edge(u_cluster, target, weight=data["weight"])
                tree.remove_node(j_cluster)
            else:
                tree.remove_edges_from(tree.in_edges(j_cluster))
                tree.add_edge(u_cluster, j_cluster, weight=max(j_len, 0))

            for k_cluster in clusters:
                if k_cluster is i_cluster or k_cluster is j_cluster:
                    continue
                ki_key = frozenset([k_cluster, i_cluster])
                kj_key = frozenset([k_cluster, j_cluster])
                distances[frozenset([k_cluster, u_cluster])] = (distances[ki_key] + distances[kj_key] - min_dist) / 2
                del distances[ki_key]
                del distances[kj_key]
            del clusters[min_j]
            del clusters[min_i]
            clusters.append(u_cluster)

        if len(clusters) == 2:
            tree.add_edge(clusters[1], clusters[0], weight=distances[frozenset([clusters[0], clusters[1]])])
            del clusters[0]

        return tree.to_undirected()


#!/usr/bin/env python
import logging
import sys
import unittest
import mango.unittest
import scipy as sp
import numpy as np
import numpy.random
import random
import mango.mpi as mpi
import mango.fmm
import mango.data
import mango.io
import os, os.path

logger, rootLogger = mpi.getLoggers(__name__)

class PValueTest(mango.unittest.TestCase):

    def testGaussianPValue(self):
        for typePair in [(None, "float32"), ("tomo", None)]:
            mtype = typePair[0]
            dtype = typePair[1]
            mean = 32000.0
            stdd = 1000.0
            noisDds = mango.data.gaussian_noise(shape=(105,223,240), mean=mean, stdd=stdd, mtype=mtype, dtype=dtype)

            pvalDds = \
                mango.fmm.gaussian_pvalue(
                    noisDds,
                    mean=mean,
                    stdd=stdd,
                    sidedness=mango.fmm.PValueSidednessType.RIGHT_SIDEDNESS
                )

            alpha = 0.05
            count = sp.sum(sp.where(pvalDds.asarray() <= alpha, 1, 0))
            if (pvalDds.mpi.comm != None):
                count = pvalDds.mpi.comm.allreduce(count)

            expCount = sp.product(noisDds.shape)*alpha
            count = float(count)
            relErr = sp.absolute(expCount-float(count))/sp.absolute(max(expCount,count))
            rootLogger.info("relErr = %s" % relErr)
            self.assertTrue(relErr < 0.10)

    def testConvolvedGaussianPValue(self):
        import matplotlib
        import matplotlib.pyplot as plt

        for typePair in [("float64", None), ("tomo_float", None)]:
            plt.clf()
            mtype = typePair[0]
            dtype = typePair[1]
            mean = 32000.0
            stdd = 1000.0
            noisDds = mango.data.gaussian_noise(shape=(100,101,102), mean=mean, stdd=stdd, mtype=mtype, dtype=dtype)
            kernelSigma = 0.6
            kernel = mango.image.discrete_gaussian_kernel(kernelSigma)
            rootLogger.info("kernal.shape=%s" % (kernel.shape,))
            rootLogger.info("sp.sum(kernal)=%s" % (sp.sum(kernel),))
            rootLogger.info("kernal (min,max)=(%s,%s)" % (np.min(kernel), np.max(kernel),))
            convMeanDds, convStddDds = mango.image.discrete_gaussian_mean_stdd(noisDds, kernelSigma)
            convStddDds = mango.image.discrete_gaussian_stdd(noisDds, kernelSigma, mean=mean)

            estMean = sp.sum(noisDds.asarray())
            if (noisDds.mpi.comm != None):
                estMean = noisDds.mpi.comm.allreduce(estMean)
            estMean /= float(sp.product(noisDds.shape))

            d = noisDds.asarray()-estMean
            estStdd = sp.sum(d*d)
            if (noisDds.mpi.comm != None):
                estStdd = noisDds.mpi.comm.allreduce(estStdd)
            estStdd = sp.sqrt(estStdd/float(sp.product(noisDds.shape)-1))

            convAvgStdd = sp.sum(convStddDds.asarray())
            if (convStddDds.mpi.comm != None):
                convAvgStdd = convStddDds.mpi.comm.allreduce(convAvgStdd)
            convAvgStdd /= float(sp.product(convStddDds.shape))
            convolveMean = sp.sum(kernel*mean)
            convolveStdd = sp.sqrt(sp.sum((kernel*kernel)*(stdd*stdd)))

            if ((convStddDds.mpi.comm == None) or (convStddDds.mpi.comm.Get_size() == 1)):
                rootLogger.info("Calculating histogram...")
                hst,edg = sp.histogram((convStddDds.asarray()*convStddDds.asarray()).flatten(), bins=1024)
                rootLogger.info("Done calculating histogram...edge (min,max)=(%s,%s)" % (np.min(edg), np.max(edg)))
                hst = sp.array(hst, copy=True, dtype="float64")
                hst /= sp.sum(hst)
                hst = hst[0:hst.size//2]
                edg = edg[0:hst.size + 1]
                xx = (edg[1:]+edg[0:-1])*0.5
                plt.plot(xx, hst)
                rootLogger.info("Calculating chi2...")
                chi2xx0 = ((sp.product(kernel.shape)-1)/(stdd*stdd))*edg
                df = sp.product(kernel.shape)-1
                chi2cdf0 = sp.stats.chi2.cdf(chi2xx0, df)
                y0 = chi2cdf0[1:]-chi2cdf0[0:-1]
                dof = ((sp.sum(kernel)**2)-(sp.sum(kernel*kernel)))/(sp.sum(kernel))
                coeffs = kernel.flatten()
                rootLogger.info("Calculating gchi2...")
                gchi2xx1 = (dof/(stdd*stdd))*edg
                gchi2cdf1 = mango.fmm.gchisqrd(coeffs, sp.zeros_like(coeffs)).cdf(gchi2xx1)
                y1 = gchi2cdf1[1:]-gchi2cdf1[0:-1]
                rootLogger.info("Done calculating gchi2.")

                #plt.plot(xx, y0)
                plt.plot(xx, y1)
                plt.title("sp.sum(hst)=%s, sp.sum(chi2)=%s" % (sp.sum(hst), sp.sum(y0)))
                dir = self.createTmpDir("testConvolvedGaussianPValue")
                plt.savefig(os.path.join(dir,"convStddDds_%s.png" % mtype), dpi=128)

                plt.figure()
                hst,edg = sp.histogram(convMeanDds.asarray().flatten(), bins=256)
                hst = sp.array(hst, copy=True, dtype="float64")
                ####hst /= sp.array(edg[1:]-edg[0:-1], dtype="float64")
                hst /= sp.sum(hst)
                xx = (edg[1:]+edg[0:-1])*0.5
                plt.plot(xx, hst)
                nd0 = sp.stats.norm.cdf(edg, loc = mean, scale = sp.sqrt(sp.sum(kernel*kernel)*stdd*stdd))
                y0 = nd0[1:]-nd0[0:-1]
                plt.plot(xx,y0)

                plt.savefig(os.path.join(dir,"convMeanDds_%s.png" % mtype), dpi=128)

            rootLogger.info("%14s=%10.5f, %14s=%10.5f" % ("mean", mean, "stdd", stdd))
            rootLogger.info("%14s=%10.5f, %14s=%10.5f" % ("convolve-mean", convolveMean, "convolve-stdd", convolveStdd))
            rootLogger.info("%14s=%10.5f, %14s=%10.5f" % ("est-stdd", estStdd, "conv-avg-stdd", convAvgStdd))

            rootLogger.info("Calculating gaussian_pvalue image for from mean-image...")
            meanPValDds = \
                mango.fmm.gaussian_pvalue(
                    convMeanDds,
                    mean=convolveMean,
                    stdd=convolveStdd,
                    sidedness=mango.fmm.PValueSidednessType.RIGHT_SIDEDNESS
                )

            alpha = 0.05
            count = sp.sum(sp.where(meanPValDds.asarray() <= alpha, 1, 0))
            if (meanPValDds.mpi.comm != None):
                count = meanPValDds.mpi.comm.allreduce(count)

            expCount = sp.product(noisDds.shape)*alpha
            count = float(count)
            relErr = sp.absolute(expCount-float(count))/sp.absolute(max(expCount,count))
            rootLogger.info("relErr = %s" % relErr)
            self.assertTrue(relErr < 0.10)

            convVarDds = mango.copy(convStddDds)
            convVarDds.asarray()[...] *= convVarDds.asarray()*((sp.product(kernel.shape)-1)/(stdd*stdd))
            rootLogger.info("Calculating generalised_chi_squared_pvalue image from variance-image...")

            ###
            ### Takes too long to compute pvalue image!!!!
            ###
#             stddPValDds = \
#                 mango.fmm.generalised_chi_squared_pvalue(
#                     convVarDds,
#                     coefficients=coeffs,
#                     noncentralities=sp.zeros_like(coeffs),
#                     sidedness=mango.fmm.PValueSidednessType.RIGHT_SIDEDNESS
#                 )
#
#             alpha = 0.05
#             count = sp.sum(sp.where(stddPValDds.asarray() <= alpha, 1, 0))
#             if (stddPValDds.mpi.comm != None):
#                 count = stddPValDds.mpi.comm.allreduce(count)
#
#             expCount = sp.product(stddPValDds.shape)*alpha
#             count = float(count)
#             relErr = sp.absolute(expCount-float(count))/sp.absolute(max(expCount,count))
#             rootLogger.info("relErr = %s" % relErr)
#             self.assertTrue(relErr < 0.10)

    def testStructuringElementPValue(self):
        import matplotlib
        import matplotlib.pyplot as plt

        dir = self.createTmpDir("testStructuringElementPValue")
        for typePair in [("float64", None), ("tomo_float", None)]:
            plt.clf()
            mtype = typePair[0]
            dtype = typePair[1]
            mean = 32000.0
            stdd = 1000.0
            noisDds = mango.data.gaussian_noise(shape=(100,101,102), mean=mean, stdd=stdd, mtype=mtype, dtype=dtype)
            se = mango.image.sphere_se(radius=2.0)
            seNumElems = sp.sum(sp.where(se.toFootprint(), 1, 0))
            rootLogger.info("se.shape=%s" % (se.toFootprint().shape,))
            rootLogger.info("sp.sum(se.toFootprint())=%s" % (seNumElems,))
            seMeanDds = mango.image.mean_filter(noisDds, se)
            seStddDds = mango.image.stdd_filter(noisDds, se)

            estMean = sp.sum(noisDds.asarray())
            if (noisDds.mpi.comm != None):
                estMean = noisDds.mpi.comm.allreduce(estMean)
            estMean /= float(sp.product(noisDds.shape))

            d = noisDds.asarray()-estMean
            estStdd = sp.sum(d*d)
            if (noisDds.mpi.comm != None):
                estStdd = noisDds.mpi.comm.allreduce(estStdd)
            estStdd = sp.sqrt(estStdd/float(sp.product(noisDds.shape)-1))

            seAvgStdd = sp.sum(seStddDds.asarray())
            if (seStddDds.mpi.comm != None):
                seAvgStdd = seStddDds.mpi.comm.allreduce(seAvgStdd)
            seAvgStdd /= float(sp.product(seStddDds.shape))
            seTheoryMean = mean
            seTheoryStdd = sp.sqrt(seNumElems*((1.0/seNumElems)**2)*(stdd*stdd))

            if ((seStddDds.mpi.comm == None) or (seStddDds.mpi.comm.Get_size() == 1)):
                rootLogger.info("Calculating histogram...")
                hst,edg = sp.histogram((seStddDds.asarray()*seStddDds.asarray()).flatten(), bins=1024)
                rootLogger.info("Done calculating histogram...edge (min,max)=(%s,%s)" % (np.min(edg), np.max(edg)))
                hst = sp.array(hst, copy=True, dtype="float64")
                hst /= sp.sum(hst)
                hst = hst[0:hst.size//2]
                edg = edg[0:hst.size + 1]
                xx = (edg[1:]+edg[0:-1])*0.5
                plt.plot(xx, hst)
                rootLogger.info("Calculating chi2...")
                chi2xx0 = ((seNumElems-1)/(stdd*stdd))*edg
                df = seNumElems-1
                chi2cdf0 = sp.stats.chi2.cdf(chi2xx0, df)
                y0 = chi2cdf0[1:]-chi2cdf0[0:-1]
                rootLogger.info("Done calculating chi2.")

                plt.plot(xx, y0)
                plt.title("sp.sum(hst)=%s, sp.sum(chi2)=%s" % (sp.sum(hst), sp.sum(y0)))
                plt.savefig(os.path.join(dir,"seStddDds_%s.png" % mtype), dpi=128)

                plt.figure()
                hst,edg = sp.histogram(seMeanDds.asarray().flatten(), bins=256)
                hst = sp.array(hst, copy=True, dtype="float64")
                ####hst /= sp.array(edg[1:]-edg[0:-1], dtype="float64")
                hst /= sp.sum(hst)
                xx = (edg[1:]+edg[0:-1])*0.5
                plt.plot(xx, hst)
                nd0 = sp.stats.norm.cdf(edg, loc = mean, scale = sp.sqrt(seNumElems*((1.0/seNumElems)**2)*stdd*stdd))
                y0 = nd0[1:]-nd0[0:-1]
                plt.plot(xx,y0)

                plt.savefig(os.path.join(dir,"seMeanDds_%s.png" % mtype), dpi=128)

            rootLogger.info("%14s=%10.5f, %14s=%10.5f" % ("mean", mean, "stdd", stdd))
            rootLogger.info("%14s=%10.5f, %14s=%10.5f" % ("seTheory-mean", seTheoryMean, "seTheory-stdd", seTheoryStdd))
            rootLogger.info("%14s=%10.5f, %14s=%10.5f" % ("est-stdd", estStdd, "se-avg-stdd", seAvgStdd))

            rootLogger.info("Calculating gaussian_pvalue image for from mean-image...")
            meanPValDds = \
                mango.fmm.gaussian_pvalue(
                    seMeanDds,
                    mean=seTheoryMean,
                    stdd=seTheoryStdd,
                    sidedness=mango.fmm.PValueSidednessType.RIGHT_SIDEDNESS
                )

            alpha = 0.05
            count = sp.sum(sp.where(meanPValDds.asarray() <= alpha, 1, 0))
            if (meanPValDds.mpi.comm != None):
                count = meanPValDds.mpi.comm.allreduce(count)

            expCount = sp.product(noisDds.shape)*alpha
            count = float(count)
            relErr = sp.absolute(expCount-float(count))/sp.absolute(max(expCount,count))
            rootLogger.info("relErr = %s" % relErr)
            self.assertTrue(relErr < 0.10)

            seVarDds = mango.copy(seStddDds)
            seVarDds.asarray()[...] *= seVarDds.asarray()*((seNumElems)-1)/(stdd*stdd)
            rootLogger.info("Calculating chi_squared_pvalue image from variance-image...")

            ###
            ### Takes too long to compute pvalue image!!!!
            ###
            stddPValDds = \
                mango.fmm.chi_squared_pvalue(
                    seVarDds,
                    dof=float(seNumElems-1),
                    sidedness=mango.fmm.PValueSidednessType.RIGHT_SIDEDNESS
                )

            alpha = 0.05
            count = sp.sum(sp.where(stddPValDds.asarray() <= alpha, 1, 0))
            if (stddPValDds.mpi.comm != None):
                count = stddPValDds.mpi.comm.allreduce(count)

            expCount = sp.product(stddPValDds.shape)*alpha
            count = float(count)
            relErr = sp.absolute(expCount-float(count))/sp.absolute(max(expCount,count))
            rootLogger.info("relErr = %s" % relErr)
            self.assertTrue(relErr < 0.10)

    def testChiSquaredPValue(self):
        for typePair in [(None, "float32"), ("float64", None)]:
            mtype = typePair[0]
            dtype = typePair[1]
            dof = 12.0
            noisDds = mango.data.chi_squared_noise(shape=(105,223,240), dof=dof, mtype=mtype, dtype=dtype)

            pvalDds = \
                mango.fmm.chi_squared_pvalue(
                    noisDds,
                    dof=dof,
                    sidedness=mango.fmm.PValueSidednessType.RIGHT_SIDEDNESS
                )

            alpha = 0.05
            count = sp.sum(sp.where(pvalDds.asarray() <= alpha, 1, 0))
            if (pvalDds.mpi.comm != None):
                count = pvalDds.mpi.comm.allreduce(count)

            expCount = sp.product(noisDds.shape)*alpha
            count = float(count)
            relErr = sp.absolute(expCount-float(count))/sp.absolute(max(expCount,count))
            rootLogger.info("relErr = %s" % relErr)
            self.assertTrue(relErr < 0.10)

class GradientChiSquaredPValueTest(mango.unittest.TestCase):

    def testDiscreteGaussianGradientChiSquaredPValue(self):
        dir = self.createTmpDir("testDiscreteGaussianGradientChiSquaredPValue")
        gSigma = 0.5
        grdKernelZ = mango.image.discrete_gaussian_gradient_kernel(axis=0, sigma=gSigma)
        sumSqrd = sp.sum(grdKernelZ*grdKernelZ)
        rootLogger.info("grdKernelZ = \n%s" % (grdKernelZ,))

        mean = 32000.0
        stdd = 4000.0
        imgDds = mango.data.gaussian_noise(shape=(100,200,200), mean=mean, stdd=stdd, mtype="tomo_float", halo=(3,3,3))

        grdDds = mango.image.discrete_gaussian_gradient_magnitude(input=imgDds, sigma=gSigma)

        mango.io.writeDds(os.path.join(dir, "tomo_floatImg.nc"), imgDds)
        mango.io.writeDds(os.path.join(dir, "tomo_floatImgGrd.nc"), grdDds)

        grdDds.updateHaloRegions()
        grdDds.mirrorOuterLayersToBorder(False)
        grdDds.subd.asarray()[...] =  grdDds.subd.asarray()*grdDds.subd.asarray()
        grdDds.subd.asarray()[...] /= (sumSqrd*(stdd*stdd))

        if ((grdDds.mpi.comm == None) or (grdDds.mpi.comm.Get_size() <= 1)):
            import matplotlib
            import matplotlib.pyplot as plt

            hst,edg = sp.histogram(grdDds.subd.asarray().flatten(), bins=1024)
            rootLogger.info("Done calculating histogram...edge (min,max)=(%s,%s)" % (np.min(edg), np.max(edg)))
            hst = sp.array(hst, copy=True, dtype="float64")
            hst /= sp.sum(hst)
            hst = hst[0:hst.size//2]
            edg = edg[0:hst.size + 1]
            xx = (edg[1:]+edg[0:-1])*0.5
            plt.plot(xx, hst, label="gradient histogram")
            rootLogger.info("Calculating chi2...")
            chi2xx0 = edg
            df = 3
            chi2cdf0 = sp.stats.chi2.cdf(chi2xx0, df)
            y0 = chi2cdf0[1:]-chi2cdf0[0:-1]

            plt.plot(xx, y0, label="Chi-squared distribution")
            plt.legend()
            plt.savefig(os.path.join(dir,"gradient_hist_and_chi_sqrd_dist.png"), dpi=100)

if __name__ == "__main__":
    #mango.setLoggingVerbosityLevel("high")
    mpi.initialiseLoggers(
        [__name__, "mango.unittest", "mango.mpi", "mango.fmm", "mango.fmmTest"],
        logLevel=logging.DEBUG
    )
    random.seed((mpi.rank+1)*23456243)
    numpy.random.seed((mpi.rank+1)*23456134)

    mango.unittest.main()


import pytest
import os
import shutil
import numpy as np
from astropy.io import fits

from .. import imgtools

dir_testing = 'testing/'
dir_verif = 'data/'

@pytest.fixture(scope="module", autouse=True)
def setUp_tearDown():
	""" rm ./testing/ before and after testing"""

	# setup
	if os.path.isdir(dir_testing):
		shutil.rmtree(dir_testing)
	os.mkdir(dir_testing)

	yield
	# tear down
	if os.path.isdir(dir_testing):
		shutil.rmtree(dir_testing)

def test_imgtools_shift():

	dx, dy = 0.3, 0.3
	subsample = 5
	data = fits.getdata(dir_verif+'j1652_wfc3_sub5.fits')

	data_shift = imgtools.shift(data, dx=dx, dy=dy, subsample=subsample)

	# check flux conservation
	assert np.absolute(data_shift.sum() - data.sum())/data.sum() < 1.e-6

	# check the shift amount is correct
	ny, nx = data.shape
	assert data.max() == data[ny//2, nx//2]

	assert data_shift.max() == data_shift[ny//2+round(dy*subsample), nx//2+round(dx*subsample)]

	# check flux conservation for fractional shift
	data_shift = imgtools.shift(data, dx=0.27990, dy=0.5812, subsample=subsample)
	assert np.absolute(data_shift.sum() - data.sum())/data.sum() < 1.e-6

	# write output file for visual inspection
	hdu = fits.PrimaryHDU(data_shift)
	hdu.writeto(dir_testing+'psf_shifted.fits')

def test_imgtools_resample():

	nx, ny = 64, 64
	subsample = 5
	data = fits.getdata(dir_verif+'j1652_wfc3_sub5.fits')

	# check that the peak is in the center of the original data
	ny_data, nx_data = data.shape
	assert data.max() == data[ny_data//2, nx_data//2]

	# resample
	data_resamp = imgtools.resample(data, nx, ny, subsample)

	# check flux conservation
	assert np.absolute(data_resamp.sum() - data.sum())/data.sum() < 1.e-6

	# check the peak is still at the center
	assert data_resamp.max() == data_resamp[ny//2, nx//2]

	# check dimension correct
	assert data_resamp.shape == (ny, nx)

	# write output file for visual inspection
	hdu = fits.PrimaryHDU(data_resamp)
	hdu.writeto(dir_testing+'psf_resampled.fits')


import joblib
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.ensemble import VotingClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import accuracy_score

def predict_diabetes(data):

    data_cleaned = data.drop(
        columns=['discharge_disposition_id', 'patient_id', 'Hospital Name', 'hospital_test_reports', 'readmission'])

    data_heart_failure = data_cleaned[data_cleaned['diabetes'] == 1]

    X = data_heart_failure.drop(columns=['discharge_destination'])
    y = data_heart_failure['discharge_destination']

    X_encoded = pd.get_dummies(X)

    X_train, X_test, y_train, y_test = train_test_split(X_encoded, y, test_size=0.3, random_state=42)

    scaler = StandardScaler()
    X_train_scaled = scaler.fit_transform(X_train)
    X_test_scaled = scaler.transform(X_test)

    logreg = LogisticRegression()
    knn = KNeighborsClassifier()

    ensemble_model = VotingClassifier(estimators=[('logreg', logreg), ('knn', knn)], voting='soft')

    ensemble_model.fit(X_train_scaled, y_train)

    joblib.dump(ensemble_model, 'diabetes2.joblib')

    y_test_pred = ensemble_model.predict(X_test_scaled)

    accuracy_test = accuracy_score(y_test, y_test_pred)
    print(f"Accuracy on the test set (Ensemble): {accuracy_test:.2f}")

    logreg.fit(X_train_scaled, y_train)
    y_test_pred_logreg = logreg.predict(X_test_scaled)
    accuracy_logreg = accuracy_score(y_test, y_test_pred_logreg)
    print(f"Accuracy of Logistic Regression on the test set: {accuracy_logreg:.2f}")

    knn.fit(X_train_scaled, y_train)
    y_test_pred_knn = knn.predict(X_test_scaled)
    accuracy_knn = accuracy_score(y_test, y_test_pred_knn)
    print(f"Accuracy of k-Nearest Neighbors (KNN) on the test set: {accuracy_knn:.2f}")

    hospital_probabilities = ensemble_model.predict_proba(X_test_scaled)

    hospital_ranking = pd.DataFrame(data={'Hospital': df['Hospital Name'].iloc[X_test.index],
                                          'Readmission Probability': hospital_probabilities[:, 1]})
    hospital_ranking = hospital_ranking.groupby('Hospital').mean().sort_values(by='Readmission Probability')

    return (hospital_ranking)


import random

from Services.DatabaseServices.databaseCommands import databaseCommands
from Services.Models.WordBoard import WordBoard

class Game:

    def __init__(self, blueTeamPlayer = "HumanP", redTeamPlayer = "HumanP", blueTeamGuide = "HumanG",
                 redTeamGuide = "HumanG", isSingleMode=False, numOfBlueWords=0, numOfRedWords=0):

        if numOfBlueWords != 0:
            self.numOfBlueWords = numOfBlueWords
            self.numOfRedWords = numOfRedWords
            self.isBluesFirst = True
        else:
            whoFirst = random.randint(0, 1)
            if whoFirst == 0:
                self.numOfBlueWords = 9
                self.numOfRedWords = 8
                self.isBluesFirst = True
            else:
                self.numOfBlueWords = 8
                self.numOfRedWords = 9
                self.isBluesFirst = False

        self.isGameCompleted = False
        self.isSingleMode = isSingleMode

        self.bluePlayer = blueTeamPlayer
        self.blueGuide = blueTeamGuide
        self.redPlayer = redTeamPlayer
        self.redGuide = redTeamGuide

        self.blueCorrectGuesses = 0
        self.blueWrongGuesses = 0
        self.redCorrectGuesses = 0
        self.redWrongGuesses = 0

        self.gameID = databaseCommands.create_game(self.bluePlayer, self.blueGuide, self.redPlayer, self.redGuide,
                                                   self.numOfBlueWords, self.numOfRedWords, self.isGameCompleted,
                                                   self.blueCorrectGuesses, self.blueWrongGuesses,
                                  self.redCorrectGuesses, self.redWrongGuesses, self.isSingleMode, self.isBluesFirst)

        self.board = WordBoard(self.gameID, self.numOfBlueWords, self.numOfRedWords)
        self.board.fillBoardWithRandomWords(self.gameID)

    def serialiseGame(self):
        gameData = {
            'GameID': self.gameID,
            'isBlueFirst': self.isBluesFirst,
            'blueWordsCount': self.numOfBlueWords,
            'redWordsCount': self. numOfRedWords
        }
        gameData = self.board.serialiseBoard(gameData)
        return gameData


"""
August 2023
Author: Rambod Azimi

How to use:
1. Enter the numbers you want to convert into barcodes, separated by spaces.
2. Choose the barcode type from the available options (EAN13, EAN8, CODE128, etc.).
3. Click the "Generate Barcodes" button to initiate the barcode generation process.

Features:
Supports multiple barcode types: EAN13, EAN8, CODE128, and more.
Fast and efficient barcode generation for multiple numbers.
Barcodes are automatically saved in the "Downloads" folder for easy access.
"""

import os
import barcode
from barcode import generate
from barcode.writer import ImageWriter
import tkinter as tk
from tkinter import filedialog

# This functions inputs a list of numbers (string type) and the barcode type, and generates the image file (png) in the Downloads folder
def generate_barcode(numbers, barcode_type):
    try:
        barcode_class = barcode.get_barcode_class(barcode_type) # Selecting the barcode type

        downloads_path = os.path.join(os.path.expanduser('~'), 'Downloads')  # Setting the path

        for number in numbers: # iterate over all the list of numbers

            code = barcode_class(number, writer=ImageWriter())

            # Generate the barcode image and save it in the "Downloads" folder
            filename = f'{barcode_type}_{number}'
            full_path = os.path.join(downloads_path, f"{filename}")
            code.save(full_path)

            print(f"Barcode generated: {full_path}")

        tk.messagebox.showinfo("Barcode Generator", "Barcodes generated successfully!")
    except barcode.errors.BarcodeNotFoundError:
        tk.messagebox.showerror("Barcode Generator", "Selected barcode type not supported.")

# Action button function
def generate_button_click():
    numbers_input = numbers_entry.get()
    numbers = numbers_input.split()
    barcode_type = barcode_type_entry.get()

    generate_barcode(numbers, barcode_type)

root = tk.Tk()
root.title("Barcode Generator")

headline_label = tk.Label(root, text="Barcode Generator", font=("Helvetica", 16, "bold"))
headline_label.pack(pady=10)

numbers_label = tk.Label(root, text="Enter the numbers separated by spaces:")
numbers_label.pack()
numbers_entry = tk.Entry(root, width=50)
numbers_entry.pack()

barcode_type_label = tk.Label(root, text="Enter the barcode type (EAN13, EAN8, CODE128, etc.):")
barcode_type_label.pack()
barcode_type_entry = tk.Entry(root, width=50)
barcode_type_entry.pack()

generate_button = tk.Button(root, text="Generate Barcodes", command=generate_button_click)
generate_button.pack(pady=10)

description_label = tk.Label(root, text="Please enter numbers separated by spaces, and select the barcode type. Then, you images are ready in your Downloads folder!")
description_label.pack(pady=10)

developer_label = tk.Label(root, text="Designed and developed by Rambod Azimi")
developer_label.pack(pady=5)

# Main
root.mainloop()


import numpy as np
import torch
import random
from PIL import Image
from scipy.spatial import cKDTree
import torch.nn.functional as F

def run_explore(env,seq,cat_feature_map, seq_lens, mask,name, init_points, end_points,iCurb_image_index):
    agent = env.agent
    network = env.network
    args = env.args

    def visualization_image(graph_record,epoch,iCurb_image_index,name,mask):
        graph_record = Image.fromarray(graph_record[0,0,:,:].cpu().detach().numpy() * 255).convert('RGB')
        mask = Image.fromarray(mask * 255).convert('RGB')
        dst = Image.new('RGB', (graph_record.width * 2, graph_record.height ))
        dst.paste(graph_record,(0,0))
        dst.paste(mask,(mask.width,0))
        dst.save('./records/train/vis/{}_{}_{}.png'.format(epoch,iCurb_image_index,name))

    def train_buffer():
        loss = 0

        loss_state_num = 0
        pre_states = torch.stack(env.buffer['pre_state']).to(env.args.device).squeeze(1)
        gt_states = torch.LongTensor(env.buffer['gt_state']).to(env.args.device).squeeze(1)
        loss_state = env.network.criterions['ce'](pre_states,gt_states)
        loss_state_num = loss_state.item()
        loss += loss_state
        #
        loss_direction_num = 0
        if len(env.buffer['pre_direction']):
            pre_directions = torch.stack(env.buffer['pre_direction']).to(env.args.device).squeeze(1)
            gt_directions = torch.FloatTensor(env.buffer['gt_direction']).to(env.args.device)
            loss_direction = torch.sum(1 - env.network.criterions['cos'](pre_directions,gt_directions))/len(env.buffer['pre_direction'])
            loss_direction_num = loss_direction.item()
            loss += loss_direction * 10

        loss_coord_num = 0
        if len(env.buffer['pre_coord']):
            pre_coords = torch.stack(env.buffer['pre_coord']).to(env.args.device).squeeze(1)
            gt_coords = torch.FloatTensor(env.buffer['gt_coord']).to(env.args.device).unsqueeze(1)
            loss_coord = env.network.criterions['bce'](pre_coords,gt_coords)
            loss_coord_num = loss_coord.item()
            loss += loss_coord * 10

        env.network.bp(loss)
        return loss_coord_num, loss_direction_num, loss_state_num

    train_len = network.train_len()
    # load data
    init_points = [[int(x[0]),int(x[1])] for x in init_points]
    end_points = [[int(x[0]),int(x[1])] for x in end_points]
    instance_num = seq.shape[0]
    # init environment
    env.init_image()
    coord_counter = 0
    stop_action_counter = 0
    direction_counter = 0
    coord_counter = 0
    loss_coord_ave = 0
    loss_direction_ave = 0
    loss_state_ave = 0
    for instance_id in range(instance_num):
        # ========================= working on a curb instance =============================
        instance_vertices = seq[instance_id]
        agent.instance_vertices = instance_vertices[:seq_lens[instance_id]].copy()
        if len(agent.instance_vertices):
            init_vertex = init_points[instance_id]
            # init_vertex =  init_vertex + 0 * np.random.normal(0, 1, 2)
            agent.init_agent(init_vertex)
            agent.end_vertex = end_points[instance_id]
            # whether use gt_direction to crop ROI
            next_direction = None
            while 1:
                agent.agent_step_counter += 1
                stop_action_counter += 1
                # crop rectcoord centering v_now
                cropped_feature_tensor = agent.crop_attention_region(cat_feature_map)
                pre_state = network.DAGMapperSH(cropped_feature_tensor)
                pre_state = pre_state.reshape(pre_state.shape[0],-1)
                pre_position = network.DAGMapperPH(cropped_feature_tensor)
                # generate labels
                gt_coord_map = env.expert_labels(pre_position,pre_state)
                env.buffer['pre_state'].append(pre_state)
                env.buffer['gt_state'].append([agent.gt_stop_action])
                if gt_coord_map is not None:
                    env.buffer['pre_coord'].append(pre_position)
                    env.buffer['gt_coord'].append(gt_coord_map)
                    coord_counter += 1
                # stop action
                if (agent.agent_step_counter > args.max_length) \
                    or (((agent.v_now[0]>=999) or (agent.v_now[0]<=0)or (agent.v_now[1]>=999) or (agent.v_now[1]<=0)) and agent.agent_step_counter > 10):
                        agent.taken_stop_action = 1
                if len(env.buffer['pre_state']) and (len(env.buffer['pre_state']) >= env.buffer_size or (instance_id == instance_num-1 and agent.taken_stop_action)):
                    loss_coord, loss_direction, loss_state = train_buffer()
                    if len(env.buffer['pre_state']) >= env.buffer_size:
                        loss_coord_ave += loss_coord * env.buffer_size
                        loss_direction_ave += loss_direction * env.buffer_size
                        loss_state_ave += loss_state * env.buffer_size
                    else:
                        loss_coord_ave += loss_coord * coord_counter
                        loss_direction_ave += loss_direction * direction_counter
                        loss_state_ave += loss_state * stop_action_counter
                    env.buffer = {'pre_direction':[],
                        'gt_direction':[],
                        'pre_coord':[],
                        'gt_coord':[],
                        'pre_state':[],
                        'gt_state':[]}
                if agent.taken_stop_action:
                    break
    # visualization
    if args.visualization:
        visualization_image(env.graph_record,env.epoch_counter,iCurb_image_index,name,mask)
    loss_direction_ave = 0 if direction_counter == 0 else loss_direction_ave / direction_counter
    loss_coord_ave = 0 if coord_counter == 0 else loss_coord_ave / coord_counter
    return loss_coord_ave, loss_direction_ave, loss_state_ave / stop_action_counter


inF = 'input.txt'

pointsx = []
pointsy = []

for line in open(inF, 'r').readlines():
    pointsx.append(int(line.split(',')[0]))
    pointsy.append(int(line.split(' ')[1]))

minx = min(pointsx)
maxx = max(pointsx)

miny = min(pointsy)
maxy = max(pointsy)

grid = [[0 for a in range(maxy + 1)] for b in range(maxx + 1)]

for index, x in enumerate(pointsx):
    y = pointsy[index]
    grid[x][y] = index

def calculateDistance(col, row, index):
    dist = abs(pointsx[index] - col) + abs(pointsy[index] - row)
    return dist

def findNearestPoint(col, row):
    moreThanOne = False
    ptIndex = 0
    dist = calculateDistance(col, row, 0)
    for index, x in enumerate(pointsx[1:]):
        y = pointsy[index]
        tmp = calculateDistance(col, row, index)
        if tmp < dist:
            dist = tmp
            ptIndex = index
            moreThanOne = False
        elif tmp == dist:
            moreThanOne = True
    return ptIndex, moreThanOne

def isInfinate(col, row):
    if col == 0 or row == 0:
        return True
    if col == maxx or row == maxy:
        return True
    return False

# init the grid
for col in range(len(grid)):
    for row in range(len(grid[0])):
        (ptindex, moreThanOne) = findNearestPoint(col, row)
        if not moreThanOne:
            grid[col][row] = ptindex
        else:
            grid[col][row] = -1

# areas = [area, isInfinate]
areas = [[0, False] for a in range(len(pointsx))]
# find the area
for col in range(len(grid)):
    for row in range(len(grid[0])):
        if grid[col][row] > 0:
            pt = grid[col][row]
            areas[pt] = [areas[pt][0] + 1, isInfinate(col, row) or areas[pt][1]]

m = 0
for a in areas:
    if not a[1]:
        if a[0] > m:
            m = a[0]

for a in range(len(grid)):
    print(grid[a])
print("max area: " + str(m))


#!/usr/bin/env python3
import numpy as np
import rospy
import torch
import torch.nn as nn
from ackermann_msgs.msg import AckermannDriveStamped
from ml_nav.msg import Image
from models import FCNN
from utils import lightning_to_torch

class PseudoVisionFcnnNavigation:
    def __init__(self):

        # setup
        rospy.loginfo("Seting up model..")
        self.config = rospy.get_param("pseudo_vision_fcnn")
        self.model = FCNN(
            self.config["input_size"] ** 2,
            self.config["classes"],
            self.config["n_layers"],
        )
        self.model.load_state_dict(lightning_to_torch(self.config["weights"]))
        self.model.eval()
        self.softmax = nn.Softmax(dim=1)

        # subscribers and publishers
        rospy.loginfo("Setting up subscribers & publishers")
        self.image_sub = rospy.Subscriber(
            "/occupancy_grid", Image, self.occ_callback, queue_size=1
        )
        self.drive_pub = rospy.Publisher("/nav", AckermannDriveStamped, queue_size=1)

        rospy.loginfo("done..")

    def occ_callback(self, data):
        grid = np.array(data.image).astype(float)
        inputs = torch.FloatTensor(grid)[None, :]
        outputs = self.softmax(self.model(inputs).detach())
        decision = torch.argmax(outputs).item()
        conf = torch.max(outputs)
        self.steer(decision, conf)

    def steer(self, direction, conf):
        drive_msg = AckermannDriveStamped()
        drive_msg.drive.speed = self.config["speed"]

        if direction == 0:
            drive_msg.drive.steering_angle = 0.3
            rospy.loginfo(f"Steering left @ {conf}")
        elif direction == 1:
            drive_msg.drive.steering_angle = -0.3
            rospy.loginfo(f"Steering right @ {conf}")
        elif direction == 2:
            drive_msg.drive.steering_angle = 0
            rospy.loginfo(f"Going Straight @ {conf}")

        self.drive_pub.publish(drive_msg)

def main():
    rospy.init_node("pseudo_vision_fcnn_nav")
    PseudoVisionFcnnNavigation()
    rospy.spin()

if __name__ == "__main__":
    main()


from skypebot import *

class Skype_Bot:
    """
    This class handles communication with Skype via SkypeBot
    """
    def __init__(self, plugins):
        self.skype = Skypebot.Skype(Events=self)
        self.skype.FriendlyName = "Skype Bot Levitan"
        self.skype.Attach()
        self.plugins = plugins

    def AttachmentStatus(self, status):
        if status == Skypebot.apiAttachAvailable:
            self.skype.Attach()

    def MessageStatus(self, msg, status):
        print("INCOMING> %s" % msg.Body)
        # msg.MarkAsSeen()
        if status == Skypebot.cmsReceived:
            for plugin in self.plugins:
                r = plugin.plugin_process_request(msg)
                if r['status']:
                    msg.Chat.SendMessage(r['message'])

    def send(self, topic, message):
        """
        Manual send to CONFERENCES to handle command line interface
        :param topic: topic of the conference (it's name)
        :param message: thing to say
        :return:
        """
        for chat in self.skype.Chats:
            if chat.Topic == topic:
                chat.SendMessage(message)


import sys
import numpy as np
import pandas as pd
from pandas.api.types import is_string_dtype
import argparse
import math

#we will use infix expression to express operations
def get_expression(s): #make a raw string to a list of operator and operand that we can easy to calculate
    s = s.replace(" ", "")
    operator = ['+', '-', '*', '/', '(', ')']   #List of operator
    expression = []
    expression.append(s[0])
    if(s[0] == '('):
        expression.append('')
    for i in range(1, len(s)):
        if s[i] in operator:
            if(expression[-1] != ''):
                expression.append(s[i])
            else:
                expression[-1] = s[i]
            expression.append('')
        else:
            expression[-1] += s[i]
    if(s[-1] in operator):
        expression.append(s[-1])
    return expression

def calc(a, op, b):         #Calculate: a op(+, -, *, /) b
    if(op == '+'):
        return a + b
    elif op == '-':
        return a - b
    elif op == '*':
        return a * b
    else:
        return a / b

def calculate(row, expression):
    operand_stack = []
    operator_stack = []
    operator = {'+' : 0, '-' : 0, '*' : 1, '/' : 1} #List of operator and priority
    for x in expression:
        if(x != '(' and x != ')' and x not in operator): #if x is an operand then push is to operand stack
            if(x.isnumeric()):
                operand_stack.append(float(x))
            else:
                operand_stack.append(row[x])
        if(x == '('): #If x is open bracket then push is to operator stack
            operator_stack.append(x)
        if(x in operator): #If x is and operator
            #If that is an operator that has priority not greater than x
            while(len(operator_stack) > 0 and operator_stack[-1] != '(' and operator[x] <= operator[operator_stack[-1]]):
                #We pop 2 operand and 1 operator to calulate and push it to operand stack
                a = operand_stack.pop()
                b = operand_stack.pop()
                op = operator_stack.pop()
                operand_stack.append(calc(a, op, b))
            #Otherwise, just push to operator stack
            operator_stack.append(x)
        if(x == ')'): #If x is close bracket
            #We pop 2 operand and 1 operator to calculate until top of operator stack is open bracket
            while(operator_stack[-1] != '('):
                a = operand_stack.pop()
                b = operand_stack.pop()
                op = operator_stack.pop()
                operand_stack.append(calc(b, op, a))
            operator_stack.pop()
    while(len(operator_stack) > 0): #pop 2 operand and 1 operator to calculate until operator stack is empty
        a = operand_stack.pop()
        b = operand_stack.pop()
        op = operator_stack.pop()
        operand_stack.append(calc(b, op, a))
    return operand_stack.pop()

def arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "-i",
        "--input"
    )
    parser.add_argument(
        "-o",
        "--output",
    )
    args = parser.parse_args()
    return args.input, args.output

if __name__ == "__main__":
    input_file, output_file = arg_parser()
    data = pd.read_csv(input_file)
    attributes = list(data)
    exp = input("Enter expression: ") #Expression that we want to calculate
    expression = get_expression(exp) #Raw String to expression for calculate
    alter_name = input("Enter new column name: ") #Name of new column
    if(alter_name == ''):
        attributes.append(' '.join(e for e in expression))
    else:
        attributes.append(alter_name)

    use_attributes = []  #Label of attributes use in expression
    for x in expression:
        if(len(x) > 1 and x.isnumeric() == False):  #Push all operand that may be an attributes list
            use_attributes.append(x)
    for attr in use_attributes:
        if attr not in attributes or is_string_dtype(data[attr]): #Check if it's an attribute or not
            #We also can't calculate of attribute's data type isn't numeric
            print(f"Invalid attributes: {attr}")
            sys.exit()

    f = open(output_file, 'w')
    f.write(','.join(attr for attr in attributes) + '\n') #Write attributes label
    for index, row in data.iterrows():
        next_line = []
        calculatable = True
        for i in range(len(attributes) - 1):
            attr = attributes[i]
            next_line.append(str(row[attr]))
            if(attr in use_attributes and pd.isna(row[attr])):
                calculatable = False #If there're a missing value in a row, we don't calculate
        if(calculatable):
            next_line.append(str(calculate(row, expression))) #Calculate expression
        else:
            next_line.append('')  #Missing value if we don't calculate
        f.write(','.join(cell for cell in next_line) + '\n')  #Write line to output file
    f.close()


""" Forms for Accounts App """

from PIL import Image
from django import forms
from django.contrib.auth.forms import UserCreationForm
from masterpoints.views import system_number_available
from .models import User
from django.core.exceptions import ValidationError

class UserRegisterForm(UserCreationForm):
    """ User Registration """

    email = forms.EmailField()

    class Meta:
        """ Meta data """

        model = User
        fields = [
            "username",
            "first_name",
            "last_name",
            "email",
            "system_number",
            "mobile",
            "password1",
            "password2",
        ]

    def clean_username(self):
        """ check system_number is valid. Don't rely on client side validation """

        username = self.cleaned_data["username"]
        if username:
            if not system_number_available(username):
                raise forms.ValidationError("Number invalid or in use")
        else:
            raise forms.ValidationError("System number missing")

        return username

class UserUpdateForm(forms.ModelForm):
    """ Used by Profile to update details """

    class Meta:
        """ Meta data """

        model = User
        fields = [
            "username",
            "first_name",
            "last_name",
            "email",
            "system_number",
            "dob",
            "mobile",
            "pic",
            "bbo_name",
        ]

    def clean_email(self):
        """ check the email is not already used """

        email = self.cleaned_data["email"]
        if email != self.instance.email:  # changed
            if User.objects.filter(email=email).exists():  # already in use
                raise ValidationError("Email already in use")
        return email

class PhotoUpdateForm(forms.ModelForm):
    """ Handles the sub-form on profile for picture """

    x = forms.FloatField(widget=forms.HiddenInput())
    y = forms.FloatField(widget=forms.HiddenInput())
    width = forms.FloatField(widget=forms.HiddenInput())
    height = forms.FloatField(widget=forms.HiddenInput())

    class Meta:
        """ Meta data """

        model = User
        fields = (
            "pic",
            "x",
            "y",
            "width",
            "height",
        )
        widgets = {
            "file": forms.FileInput(
                attrs={
                    "accept": "image/*"  # this is not an actual validation! don't rely on that!
                }
            )
        }

    def save(self):
        photo = super(PhotoUpdateForm, self).save()

        x = self.cleaned_data.get("x")
        y = self.cleaned_data.get("y")
        w = self.cleaned_data.get("width")
        h = self.cleaned_data.get("height")

        image = Image.open(photo.pic)
        cropped_image = image.crop((x, y, w + x, h + y))
        resized_image = cropped_image.resize((200, 200), Image.ANTIALIAS)
        resized_image.save(photo.pic.path)

        return photo

class BlurbUpdateForm(forms.ModelForm):
    """ Handles the sub-form on profile for wordage """

    class Meta:
        """ Meta data """

        model = User
        fields = ("about",)

class UserSettingsForm(forms.ModelForm):
    """ Used by Settings to update details """

    class Meta:
        """ Meta data """

        model = User
        fields = [
            "username",
            "receive_sms_results",
            "receive_sms_reminders",
            "receive_abf_newsletter",
            "receive_marketing",
            "receive_monthly_masterpoints_report",
            "receive_payments_emails",
            "system_number_search",
            "windows_scrollbar",
        ]


# -*- encoding: utf-8 -*-

N = input()
N1 = float(N.split()[0])
N2 = float(N.split()[1])
N3 = float(N.split()[2])

if (N1>N2 and N1>N3):
    A = N1
    if (N2>N3):
        B = N2
        C = N3
    else:
        B = N3
        C = N2
elif (N2>N1 and N2>N3):
    A = N2
    if (N1>N3):
        B = N1
        C = N3
    else:
        B = N3
        C = N1
else:
    A = N3
    if (N1>N2):
        B = N1
        C = N2
    else:
        B = N2
        C = N1

if (A>=B+C):
    print("NAO FORMA TRIANGULO")
else:
    if ((A*A)==(B*B)+(C*C)):
        print("TRIANGULO RETANGULO")
    if ((A*A)>(B*B)+(C*C)):
        print("TRIANGULO OBTUSANGULO")
    if ((A*A)<(B*B)+(C*C)):
        print("TRIANGULO ACUTANGULO")
    if (A==B and B==C):
        print("TRIANGULO EQUILATERO")
    if ((A==B and B!=C) or (B==C and C!=A) or (C==A and A!=B)):
        print("TRIANGULO ISOSCELES")


"""
Title - IPP <interpret.py>
Author - Maroš Geffert
Login - <xgeffe00>
"""

from classes.iArgsErrors import *

class InstructionList(Arg_Error_Checker):

    def __init__(self):
        super().__init__()
        self.iInstructions = {}
        self.iInstructions_in_file = 0
        self.iInstructionsCounter = 1
        self.iInstructionsDoneNumber = 0
        self.iLabels = {}

    def insert_instruction(self, instruction):
        self.iInstructions_in_file += 1
        self.iInstructions[self.iInstructions_in_file] = instruction

        if instruction.opcode == 'LABEL':
            label_name = instruction.arg1['text']
            if label_name in self.iLabels:
                self.exit_program(52, 'ERROR: Label \'{}\' already exist !'.format(label_name))
            else:
                self.iLabels[label_name] = self.iInstructions_in_file

    def get_next_instruction(self):

        if self.iInstructionsCounter <= self.iInstructions_in_file:
            self.iInstructionsDoneNumber += 1
            self.iInstructionsCounter += 1
            return self.iInstructions[self.iInstructionsCounter - 1]
        else:
            return None

    def jump_to_label(self, i_arg_label, iReturn=False):

        if iReturn == False:
            label = i_arg_label['text']
        else:
            label = i_arg_label

        if label in self.iLabels:
            self.iInstructionsCounter = self.iLabels[label] + 1
        elif iReturn == True:
            self.iInstructionsCounter = label
        else:
            self.exit_program(52, 'ERROR: Label doesnt exist')

    def check_label(self, i_arg_label, iReturn=False):
        if iReturn == False:
            label = i_arg_label['text']
        else:
            label = i_arg_label

        if label in self.iLabels:
            pass
        else:
            self.exit_program(52, 'ERROR: Label doesnt exist')

    def get_instruction_counter(self):
        return self.iInstructionsCounter - 1

    def get_instruction_done_number(self):
        return self.iInstructionsDoneNumber - 1


#!/usr/bin/env python2
import rospy
from geometry_msgs.msg import Twist
import numpy as np

class SpeedSteerToRL():
    def __init__(self):
        self.wheel_sep = float(rospy.get_param("/speed_steer_to_rl/wheel_separation"))
        self.rl_speed_pub = rospy.Publisher("control_out", Twist, queue_size=10)
        self.sub = rospy.Subscriber("cmd_in", Twist, self.callback)

    def callback(self, data):
        msg = Twist()
        speed_to_signal = float(rospy.get_param("/speed_steer_to_rl/speed_to_signal"))
        max_speed = float(rospy.get_param("/speed_steer_to_rl/max_signal"))/speed_to_signal
        speed = data.linear.x
        steer = np.radians(data.angular.z)
        vel_diff = steer * self.wheel_sep
        right_speed = self.bound(speed, -max_speed, max_speed)
        left_speed = right_speed = self.bound(speed, -max_speed, max_speed)

        right_speed = self.bound(right_speed + vel_diff/2.0, -max_speed, max_speed)
        left_speed = self.bound(left_speed - vel_diff/2.0, -max_speed, max_speed)

        if abs(right_speed) == max_speed:
            left_speed = self.bound(right_speed - vel_diff, -max_speed, max_speed)
        elif abs(left_speed) == max_speed:
            right_speed = self.bound(left_speed + vel_diff, -max_speed, max_speed)

        msg.linear.x = right_speed * speed_to_signal
        msg.angular.z = left_speed * speed_to_signal
        self.rl_speed_pub.publish(msg)

    def bound(self, val, mn, mx):
        return max(min(mx, val), mn)

if __name__ == '__main__':
    rospy.init_node('robot_control_node', anonymous=True)
    SpeedSteerToRL()
    rospy.spin()


import math
from collections import deque

def solution(n, edge):
    answer = 0

    distances = [math.inf for _ in range(n + 1)]

    visit = [False for _ in range(n+1)]

    distances[1] = 0

    graph = {i : [] for i in range(1, n+1)}

    for i in range(len(edge)):

        graph[edge[i][0]].append(edge[i][1])

        graph[edge[i][1]].append(edge[i][0])

    q = deque()

    q.append(1)

    while q:
        node = q.popleft()

        distance = distances[node]

        if visit[node] == False:

            visit[node] = True

            for i in range(len(graph[node])):

                distances[graph[node][i]] = min(distances[graph[node][i]], distance + 1)

                q.append(graph[node][i])

    maxVal = max(distances[1:])
    return distances.count(maxVal)

print(solution(6, [[3, 6], [4, 3], [3, 2], [1, 3], [1, 2], [2, 4], [5, 2]]))


import os
import datetime
import time as Time

def getFileSize(filePath):
    return os.path.getsize(filePath)

def getFileType(filePath):
    index=1
    for c in filePath:
        if c == '.':
            break
        else:
            index += 1
    return filePath[index:]

def getCompRatio(initialSize,finalSize,dp=3):
    return round((finalSize/initialSize),dp)

def getCurDate1():
    time =  datetime.datetime.now()
    return str(time)

def getCurDate():
    return Time.time()

def roundTime(time):
    pass

def calcRelTime(time,relTime):
    return round((time/relTime),6)

def getFileName(filePath):
    revName=''
    for char in filePath[::-1]:
        if char != '\\':
            revName = char + revName
        else:
            return revName

def initialAnalyseList(fileList,path=True,size=True,fileType=True):
    updatedList = []
    for file in fileList:
        fileInfo = {}
        if path:
            fileInfo['filePath'] = file
        if size:
            fileInfo['initialSize'] = getFileSize(file)
        if fileType:
            fileInfo['fileType'] = getFileType(file)

        updatedList.append(fileInfo)

    return updatedList

def initialAnalyse(filePath,fileName=True,size=True,fileType=True):
    fileInfo = {}
    fileInfo['filePath'] = filePath
    if fileName:
        fileInfo['fileName'] = getFileName(filePath)
    if size:
        fileInfo['initialSize'] = getFileSize(filePath)
    if fileType:
        fileInfo['fileType'] = getFileType(filePath)

    return fileInfo

def afterAnalyse(fileInfo,compressedPath,timeTaken=None,compPath=True,size=True,
                 compType=True,ratio=True,date=True,relTime=True):
    if compPath:
        fileInfo['compPath'] = compressedPath
    if size:
        fileInfo['compSize'] = getFileSize(compressedPath)
    if compType:
        fileInfo['compType'] = getFileType(compressedPath)
    if ratio:
        try:
            fileInfo['ratio'] = getCompRatio(fileInfo['initialSize'],fileInfo['compSize'])
        except:
            fileInfo['ratio'] = 1
    if date:
        fileInfo['date'] = round(getCurDate())
    if timeTaken:
        fileInfo['time'] = float(str(timeTaken)[:5])
    if relTime:
        fileInfo['relTime'] = 1
    return fileInfo

if __name__ == '__main__':
    pass


#!/usr/bin/python3

'''
Q2.7
    Intersection: Given two (singly) linked lists, determine if the two lists intersect. Return the intersecting node. Note that the intersection is defined based on reference, not value. That is, if the kth node of the first linked list is the exact same node (by reference) as the jth node of the second linked list, then they are intersecting.
'''

from LinkedList import LinkedList

def intersection_stack(lla, llb):
    if lla.tail is not llb.tail:
        return False

    a, b = lla.head, llb.head
    stackA, stackB = [], []
    while a or b:
        if a:
            stackA.append(a)
            a = a.next
        if b:
            stackB.append(b)
            b = b.next

    intersect = False
    while stackA and stackB:
        popA, popB = stackA.pop(), stackB.pop()
        if popA is popB:
            intersect = popA.value
        else:
            return intersect

def intersection_inplace(lla, llb):
    if lla.tail is not llb.tail:
        return False
    #else an intersection exists
    diff = 0
    print(len(lla), len(llb))
    if len(lla) > len(llb):
        diff = len(lla) - len(llb)
    elif len(lla) < len(llb):
        diff = len(llb) - len(lla)
        lla, llb = llb, lla
    longerN, shorterN = lla.head, llb.head

    for i in range(diff):
        longerN = longerN.next

    while longerN is not shorterN:
        longerN, shorterN = longerN.next, shorterN.next

    return longerN

def intersection_hash(lla, llb):
    if lla.tail is not llb.tail:
        return False
    hashA = set()

    nodeA, nodeB = lla.head, llb.head
    while nodeA:
        hashA.add(nodeA)
        nodeA = nodeA.next
    while nodeB:
        if nodeB in hashA:
            return nodeB
        nodeB = nodeB.next

#TEST
lla = LinkedList()
lla.add_multiple([1,2,3])
llb = LinkedList()
llb.add_multiple([0,1,2])
llb.tail.next = lla.tail
lla.add_multiple([4,5])
llb.tail = lla.tail
print(lla, llb)
llc = LinkedList()
llc.add_multiple([0,1,2,3,4,5])
#print(intersection_stack(lla, llb))
#print(intersection_inplace(lla, llb))
print(intersection_hash(lla, llb))
print(lla, llc)
#print(intersection_stack(lla, llc))
#print(intersection_inplace(lla, llc))
print(intersection_hash(lla, llc))


# -*- coding: utf-8 -*-
"""
Created on Thu Sep 16 16:42:09 2021

@author: Mike
"""

def maxSuma(lista):
    maximo = 0
    indiceUno = 0
    indiceDos = 0
    tabla=[0]*len(lista)
    for i in range(len(lista)):
        tabla[i] = [0]*len(lista)
    for i in range(len(lista)):
        for  j in range(0,i):
            tabla[i][j] = tabla[i-1][j]+lista[i]
            if(tabla[i][j] > maximo):
                maximo = tabla[i][j]
                indiceUno = i
                indiceDos = j
        tabla[i][i] = lista[i]
        if(tabla[i][i] > maximo):
            maximo = tabla[i][i]
    return (maximo,indiceUno,indiceDos)

def maxSuma2(lista):
    maximo = 0
    suma = 0
    for i in range(len(lista)):
        if(suma+lista[i] > 0):
            suma = suma+lista[i]
        else:
            suma = 0
        if(suma > maximo):
            maximo = suma
    return (maximo)

if __name__=="__main__":
    datos = [27,6,-50,21,-3,14,16,-8,42,33,-21,9]
    maximo,rango1,rango2=maxSuma(datos)
    print("Primera Forma")
    print(maximo)
    print(datos[rango2:rango1+1])
    print("Sgunda Forma")
    print(maxSuma2(datos))