"""empty message

Revision ID: a939b9aa0cfb
Revises:
Create Date: 2019-10-23 15:55:54.888936

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'a939b9aa0cfb'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('avatar',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('image_file', sa.String(length=100), nullable=True),
    sa.Column('price', sa.Integer(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('player',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(length=64), nullable=True),
    sa.Column('chips', sa.Integer(), nullable=True),
    sa.Column('is_in', sa.Boolean(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('avatar_player',
    sa.Column('avatar_id', sa.Integer(), nullable=False),
    sa.Column('player_id', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['avatar_id'], ['avatar.id'], ),
    sa.ForeignKeyConstraint(['player_id'], ['player.id'], ),
    sa.PrimaryKeyConstraint('avatar_id', 'player_id')
    )
    op.create_table('card',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('value', sa.String(length=2), nullable=False),
    sa.Column('symbol', sa.String(length=1), nullable=False),
    sa.Column('player_id', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['player_id'], ['player.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('card')
    op.drop_table('avatar_player')
    op.drop_table('player')
    op.drop_table('avatar')
    # ### end Alembic commands ###


#!/usr/bin/env python3

class LinkedListNode(object):

	def __init__(self, value):
		self.value = value
		self.nextnode = None

class DoublyLinkedListNode(object):

	def __init__(self, value):
		self.value = value
		self.next_node = None
		self.prev_node = None

a = LinkedListNode(1)
b = LinkedListNode(2)
c = LinkedListNode(3)

a.nextnode = b
b.nextnode = c

a = DoublyLinkedListNode(1)
b = DoublyLinkedListNode(2)
c = DoublyLinkedListNode(3)

# Setting b after a
a.next_node = b
b.prev_node = a
# Setting c after b
b.next_node = c
c.prev_node = b

Linked Lists/Linked Lists Interview Problems/Linked List Interview Problems /Implement_a_Linked_List.py


import threading
from queue import Queue
##import time

### lock to serialize console output
##lock = threading.Lock()
##
##def do_work(item):
##    time.sleep(.1) # pretend to do some lengthy work.
##    # Make sure the whole print completes or threads can mix up output in one line.
##    with lock:
##        print(threading.current_thread().name,item)
##
### The worker thread pulls an item from the queue and processes it
##def worker():
##    while True:
##        item = q.get()
##        do_work(item)
##        q.task_done()
##
### Create the queue and thread pool.
##q = Queue()
##for i in range(4):
##     t = threading.Thread(target=worker)
##     t.daemon = True  # thread dies when main thread (only non-daemon thread) exits.
##     t.start()
##
### stuff work items on the queue (in this case, just a number).
##start = time.perf_counter()
##for item in range(20):
##    q.put(item)
##
##q.join()       # block until all tasks are done
##
### "Work" took .1 seconds per task.
### 20 tasks serially would be 2 seconds.
### With 4 threads should be about .5 seconds (contrived because non-CPU intensive "work")
##print('time:',time.perf_counter() - start)

class threadingOperation:
    dest=False #holds a pointer to function to be multithreaded.
    thCount=1 #specifies number of threads to be created
    myQueue=False
    def __init__(self,destFunc,thCount):
        self.dest=destFunc
        self.thCount=thCount
    def worker(self): #one worker per thread, each one will work until all tasks done, then dies
        while True:
            self.dest( self.myQueue.get() ) #passes task to multied function
            self.myQueue.task_done() #signals to queue that particular task is finished
    def thread(self,taskList):
        #taskList is a list of stuff
        #each element of the list is passed to an instance of the function
        #named in dest
        self.myQueue=Queue() #make queue
        for i in range(self.thCount):
            t=threading.Thread(target=self.worker)
            t.daemon=True
            t.start()
        for x in taskList:
            self.myQueue.put(x)
        self.myQueue.join()


from cricket_center.models import PlayerDetail, JoiningDetail, IndiaWestIndiesTeam, MatchDetail, ContestDetail
from django.db.models import Q
from django.shortcuts import render, get_object_or_404

def update_total_team_points():
        player_points_dict = {}
        for player in PlayerDetail.objects.filter(Q(player_current_team__exact='WI') | Q(player_current_team__exact='IND')):
            player_points_dict[player.player_name] = player.current_points
        for detail in JoiningDetail.objects.all():
            total_points = 0
            team = IndiaWestIndiesTeam.objects.filter(full_team_name__exact=detail.joined_user + "[" + str(detail.joined_user_team) + "]")
            total_points = total_points + player_points_dict[team.first().Keeper]
            total_points = total_points + player_points_dict[team.first().Player2]
            total_points = total_points + player_points_dict[team.first().Player3]
            total_points = total_points + player_points_dict[team.first().Player4]
            total_points = total_points + player_points_dict[team.first().Player5]
            total_points = total_points + player_points_dict[team.first().Player6]
            total_points = total_points + player_points_dict[team.first().Player7]
            total_points = total_points + player_points_dict[team.first().Player8]
            total_points = total_points + player_points_dict[team.first().Player9]
            total_points = total_points + player_points_dict[team.first().Player10]
            total_points = total_points + (player_points_dict[team.first().Player11])
            total_points = total_points + player_points_dict[team.first().Captain]
            total_points = total_points + player_points_dict[team.first().Vice_Captain] / 2
            detail.total_team_points = total_points
            detail.save()

def CallThisForDestribution(match_slug):
    contest_obj = ContestDetail.objects.filter(contest_of_match__exact=match_slug)
    for contest in contest_obj:
        if contest.confirmed or contest.filled_status:
            DistributeWinning(contest.contest_slug, contest.prize_dist_type, contest.contest_winners)
        else:
            RefundContestAmount(match_slug, contest.contest_slug)

contest_prize_dict = {"hund_players_65_winners": {1: 60, 2: 45, 3: 35, 4: 25, 5: 25, 6: 20, 7: 20, 8: 20, 9: 20, 10: 20, 11: 20, 12: 20, 13: 20, 14: 20, 15: 20, 16: 20, 17: 20, 18: 20, 19: 20,
                           20: 20, 21: 20, 22: 20, 23: 20, 24: 20, 25: 20, 26: 14, 27: 14, 28: 14, 29: 14, 30: 14, 31: 14, 32: 14, 33: 14, 34: 14, 35: 14, 36: 14,
                           37: 14, 38: 14, 39: 14, 40: 14, 41: 8, 42: 8, 43: 8, 44: 8, 45: 8, 46: 8, 47: 8, 48: 8, 49: 8, 50: 8, 51: 8, 52: 8, 53: 8, 54: 8, 55: 8,
                           56: 8, 57: 8, 58: 8, 59: 8, 60: 8, 61: 8, 62: 8, 63: 8, 64: 8, 65: 8,
    }
}

def DistributeWinning(contest_slug, prize_dist_type, winners):
    all_joined = JoiningDetail.objects.filter(joined_contest_slug__exact=contest_slug).order_by('-total_team_points')
    tie_amount = 0
    tie_count = 1
    tie_start = None
    temp_var = None
    for i, joined in enumerate(all_joined):
        print("H")
        try:
            print("T")
            if joined.total_team_points == all_joined[i + 1].total_team_points:
                temp_var = True
            else:
                temp_var = False
        except IndexError:
            temp_var = False
        if temp_var:
            tie_amount = tie_amount + contest_prize_dict[prize_dist_type][i + 1]
            tie_count = tie_count + 1
            if tie_start is None:
                tie_start = i + 1
            print("Tie Start :" + str(tie_start))
            print("Me")
        else:
            print("IE")
            if (tie_amount != 0) and (tie_start is not None):
                tie_amount = tie_amount + contest_prize_dict[prize_dist_type][joined.rank]
                print("tie" + str(tie_amount))
                print("tiecount" + str(tie_count))
                winning_amount = tie_amount / (tie_count)
                for j in all_joined[tie_start - 1: i + 1]:
                    print("Executed")
                    print(winning_amount)
                    print(j.rank, j.joined_user)
                    j.winnings = winning_amount
                    print(j.winnings, winning_amount)
                    j.save()
                tie_amount = 0
                tie_start = 0
            if (tie_amount is 0) and (tie_start is None):
                print("No Teu")
                joined.winnings = contest_prize_dict[prize_dist_type][joined.rank]
                print(contest_prize_dict[prize_dist_type][joined.rank])
                joined.save()

def RefundContestAmount():
    pass
# # # from django.http import HttpResponseRedirect
# # # from django.urls import reverse
# # # from django.conf import settings

# # # # class AuthRequiredMiddleware(object):
# # # #     def process_request(self, request):
# # # #         if not request.user.is_authenticated():
# # # #             return HttpResponseRedirect(reverse('home'))
# # # #         return None

# # # class StackOverflowMiddleware(object):
# # #     def __init__(self, get_response):
# # #         self.get_response = get_response

# # #     def __call__(self, request):
# # #         response = self.get_response(request)
# # #         if not request.user.is_authenticated():
# # #             return HttpResponseRedirect(reverse('IndexView'))
# # #         return response

# import re
# from django.conf import settings
# from django.shortcuts import redirect

# EXEMPT_URLS = ['IndexView']#[re.compile(settings.LOGIN_URL.lstrip('/'))]

# # # if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
# # #     EXEMPT_URL = []

# class LogInRequiredMiddleware:

#     def __init__(self, get_response):
#         self.get_response = get_response

#     def __call__(self, request):
#         response = self.get_response(request)
#         return response

#     def process_view(self, request, view_func, view_args, view_kwargs):
#         assert hasattr(request, 'user')
#         path = request.path_info
#         print(path)
#         if not request.user.is_authenticated():
#             if path not in EXEMPT_URLS:
#                 return redirect(settings.LOGIN_URL)

# # from django.shortcuts import HttpResponseRedirect

# # class LogInRequiredMiddleware(object):
# #     def __init__(self, get_response):
# #         self.get_response = get_response

# #     def __call__(self, request):
# #         # Code to be executed for each request before
# #         # the view (and later middleware) are called.

# #         response = self.get_response(request)
# #         if not request.user.is_authenticated():
# #             return HttpResponseRedirect('IndexView')

# #         # Code to be executed for each request/response after
# #         # the view is called.

# #         return response


# importing the requests library
import requests
import numpy as np
import  os
from bs4 import BeautifulSoup

# Cadenas de Pais Y Palabras
country = ["Colombie","Canada","Cuba","Chine","Cameroun","Cambodge","Costa Rica","Croatie","République tchèque","Argentine","Afghanistan","Australie","Algérie","Autriche","Brésil","Bolivie","Belgique","Bangladesh","Danemark","République dominicaine","Egypte","Ethiopie","Finlande","Ghana","Allemagne","Grèce","Guatemala","Hongrie","Islande","Inde","Indonésie","Iran","Irak","Irlande","Israël","Italie","Jamaïque","Japon","Kenya","Lituanie","Luxembourg","Malaisie","Maroc","Pays-Bas","Nouvelle Zélande","Namibie","Norvège","Nicaragua","Pakistan","Panama","Portugal","Pérou","Pologne","Philippines","Russie","Singapour","Afrique du Sud","Corée du Sud","Suède","Suisse","Thaïlande","Turquie","Émirats arabes unis","Royaume-Uni","États-Unis","Vietnam","Mexique","Équateur","Venezuela","Espagne","France","Estonie","Slovaquie","Slovénie","Uruguay","Paraguay","Chili","Sri Lanka","Roumanie","Tanzanie","Tunisie","Bulgarie","Nigeria","Lettonie","Arabie Saoudite","Biélorussie","Serbie","Sénégal","Ecosse"]
keywords = ['science']
#keywords = ['art']
exclude_keywords = "sport"

start_day = "01"
start_month = "01"
end_day = "31"
end_month = "12"

syears = ["2007"]

datos = []
year = []
links = []
tcountry = []
urls = []

# api-endpoint
for y in syears:
        print("_________________________")
        print(y)
        for c in country:
                print(c)
                for k in keywords:
                        URL = "https://www.lemonde.fr/recherche/?keywords="+c+"+"+k+"&operator=and&exclude_keywords="+exclude_keywords+"&qt=recherche_texte_titre&period=custom_date&start_day="+start_day+"&start_month="+start_month+"&start_year="+y+"&end_day="+end_day+"&end_month="+end_month+"&end_year="+y+"&sort=desc"                        # sending get request and saving the response as response object
                        r = requests.get(URL)
                        urls.append(r.url)
                        #print(r.url)

                         # extracting data in json format
                        soup = BeautifulSoup(r.text, "html.parser")
                        tags = soup.findAll('strong')
                        nav = tags[3].text
                        print(nav)

                        #Appends
                        datos.append(nav)
                        tcountry.append(c)
                        year.append(y)

#csvList = [country, datos, year, links]
csvList = [tcountry, datos, year]

#TXT
l = np.asarray(csvList)
ruta = os.getcwd() + os.sep
np.savetxt( "output_LM"+" "+y+".txt",   # Archivo de salida
           l.T,        # Trasponemos los datos
           fmt="%s",       # Usamos números enteros
           delimiter=",")

#CSV
l = np.asarray(csvList)
ruta = os.getcwd() + os.sep
np.savetxt( "output_LM"+" "+y+".csv",   # Archivo de salida
           l.T,        # Trasponemos los datos
           fmt="%s",       # Usamos números enteros
           delimiter=",")

print("Los archivos se han exportado satisfactoriamente")


from kivy.app import App
from kivy.config import Config
Config.set('graphics', 'fullscreen', '0')
Config.set('graphics', 'width', '648')
Config.set('graphics', 'height', '1152')
Config.write()
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.core.text import FontContextManager as FCM
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button  # przyciski
from kivy.uix.image import Image
from kivy.graphics import *
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
import gmaps
import googlemaps
import sys
import datetime
from datetime import timedelta
import requests

gmaps.configure(api_key="KLUCZAPI")
GoogleMaps=googlemaps.Client(key="KLUCZAPI") #dla skrócenia komend

class LoginScreen(FloatLayout):  # ekran nr 1

    def __init__(self, **var_args):

        super(LoginScreen, self).__init__(**var_args)
        now = datetime.datetime.now()
        hour = str(now.hour)
        if hour == "0":
            hour = "00"
        minuta = str(now.minute)

        #tlo
        self.tlo = Image(source='Tloo1.png')
        self.tlo.opacity = 0.75
        self.tlo.size_hint_x = 1
        self.tlo.size_hint_y = 1
        self.tlo.pos_hint = {"x": 0, "top": 1}
        self.add_widget(self.tlo)

        self.skad = TextInput(multiline=False, size_hint=(0.45, 0.1), font_size=20, pos_hint={"x": 0.28, "top": 0.7},
                              text='            Skąd wychodzisz?')
        self.add_widget(self.skad)

        self.dokad = TextInput(multiline=False, size_hint=(0.45, 0.1), font_size=20, pos_hint={"x": 0.28, "top": 0.5},
                               text='       Dokąd chcesz dojechać?')
        self.add_widget(self.dokad)

        self.godzina = TextInput(multiline=False, size_hint=(0.05, 0.04), font_size=15, pos_hint={"x": 0.4, "top": 0.3},
                              text=hour)

        self.minuta = TextInput(multiline=False, size_hint=(0.05, 0.04), font_size=15, pos_hint={"x": 0.5, "top": 0.3},
                                 text=minuta)
        self.add_widget(self.godzina)
        self.add_widget(self.minuta)

        przycisk = Button(text='Wyszukaj!')
        przycisk.bind(on_press=self.clkfunc)
        przycisk.opacity = 0.9
        self.add_widget(przycisk)

        # logo na gorze
        self.img = Image(source='2019.png')
        self.img.opacity = 0.9
        self.img.size_hint_x = 1
        self.img.size_hint_y = 0.26
        self.img.pos_hint = {"x": 0, "top": 0.98}
        self.add_widget(self.img)

        # obrazek skad
        self.img1 = Image(source='skad2.png')
        self.img1.opacity = 0.9
        self.img1.size_hint_x = 0.1
        self.img1.size_hint_y = 0.05
        self.img1.pos_hint = {"x": 0.18, "top": 0.7}
        self.add_widget(self.img1)

        # obrazek dokad
        self.img2 = Image(source='skad3.png')
        self.img2.opacity = 0.9
        self.img2.size_hint_x = 0.1
        self.img2.size_hint_y = 0.05
        self.img2.pos_hint = {"x": 0.18, "top": 0.5}
        self.add_widget(self.img2)

        # obrazek zegara
        self.img3 = Image(source='clocku.png')
        self.img3.opacity = 0.9
        self.img3.size_hint_x = 0.1
        self.img3.size_hint_y = 0.05
        self.img3.pos_hint = {"x": 0.18, "top": 0.31}
        self.add_widget(self.img3)

    def clkfunc(self, event): # przycisk ktory odpowiada za zebranie danych + nowy ekran

        adres1 = self.skad.text + "Łódź"
        adres2 = self.dokad.text+ "Łódź"

        now=datetime.datetime.now()
        now-= timedelta(hours=(now.hour),minutes=now.minute)
        now+= timedelta(hours=int(self.godzina.text),minutes=int(self.minuta.text))

        #adres1 = "Piotrkowska cetnurm łódź"
        #adres2 = "Mikołaja Kopernika 76/78"

        self.clear_widgets()

        while True:
            try:
                geocode1 = GoogleMaps.geocode(adres1)
                geocode2 = GoogleMaps.geocode(adres2)
                for x, y in geocode1[0].items():  # wyciganiecie szerokosci geograf z pierwszej lokalizacji
                    if (x == "geometry"):
                        for i, j in y.items():
                            if (i == "location"):
                                lat1 = list(j.values())[0]
                                lng1 = list(j.values())[1]
                                lokacja1 = []
                                lokacja1.append(lat1)
                                lokacja1.append(lng1)

                for xx, yy in geocode2[0].items():  # wyciganiecie szerokosci geograf z 2 lokalizacji
                    if (xx == "geometry"):
                        for ii, jj in yy.items():
                            if (ii == "location"):
                                lat2 = list(jj.values())[0]
                                lng2 = list(jj.values())[1]
                                lokacja2 = []
                                lokacja2.append(lat2)
                                lokacja2.append(lng2)
                break
            except:
                print("Błedne lokacje lub brak przejazdów")
                sys.exit()

        POMIN = False
        przesiadka = False
        wskazowki = (GoogleMaps.directions(lokacja1, lokacja2, mode="transit", departure_time=now))
        direkcje = (GoogleMaps.distance_matrix(adres1, adres2, mode='transit'))

        odlegloscD = (direkcje['rows'][0]['elements'][0]['distance']['text'])  # odleglosc całej drogi od A do B
        czasD = (direkcje['rows'][0]['elements'][0]['duration']['text'])

        if 'Walk' in (wskazowki[0]['legs'][0]['steps'][0]['html_instructions']) and len(wskazowki[0]['legs'][0]['steps'])<2:
            POMIN = True
        try:
            nazwatramwaju = (wskazowki[0]['legs'][0]['steps'][0]['transit_details']['headsign'])
            nrtramwaju = (wskazowki[0]['legs'][0]['steps'][0]['transit_details']['line']['short_name'])
            godzinawyjazdutram = (wskazowki[0]['legs'][0]['steps'][0]['transit_details']['departure_time']['text'])
            godzinadojazdu = (wskazowki[0]['legs'][0]['steps'][0]['transit_details']['arrival_time']['text'])
            gdziewsiadasz = (wskazowki[0]['legs'][0]['steps'][0]['transit_details']['departure_stop']['name'])
            lprzystankow = (wskazowki[0]['legs'][0]['steps'][0]['transit_details']['num_stops'])
        except:
            try:
                nazwatramwaju = (wskazowki[0]['legs'][0]['steps'][1]['transit_details']['headsign'])
                lprzystankow = (wskazowki[0]['legs'][0]['steps'][1]['transit_details']['num_stops'])
                nrtramwaju = (wskazowki[0]['legs'][0]['steps'][1]['transit_details']['line']['short_name'])
                godzinawyjazdutram = (wskazowki[0]['legs'][0]['steps'][1]['transit_details']['departure_time']['text'])
                godzinadojazdu = (wskazowki[0]['legs'][0]['steps'][1]['transit_details']['arrival_time']['text'])
                gdziewsiadasz = (wskazowki[0]['legs'][0]['steps'][1]['transit_details']['departure_stop']['name'])
            except:
                lprzystankow = ""
                nrtramwaju = ""
                godzinawyjazdutram = ""
                godzinadojazdu = ""
                gdziewsiadasz = ""
                nazwatramwaju = ""

        try:
            nazwatramwaju2 = (wskazowki[0]['legs'][0]['steps'][2]['transit_details']['headsign'])
            nrtramwaju2 = (wskazowki[0]['legs'][0]['steps'][2]['transit_details']['line']['short_name'])
            lprzystankow2 = (wskazowki[0]['legs'][0]['steps'][2]['transit_details']['num_stops'])
            godzinawyjazdutram2 = (wskazowki[0]['legs'][0]['steps'][2]['transit_details']['departure_time']['text'])
            godzinadojazdu2 = (wskazowki[0]['legs'][0]['steps'][2]['transit_details']['arrival_time']['text'])
            gdziewsiadasz2 = (wskazowki[0]['legs'][0]['steps'][2]['transit_details']['departure_stop']['name'])
        except:
            try:
                gdziewsiadasz2 = (wskazowki[0]['legs'][0]['steps'][3]['transit_details']['departure_stop']['name'])
                godzinadojazdu2 = (wskazowki[0]['legs'][0]['steps'][3]['transit_details']['arrival_time']['text'])
                godzinawyjazdutram2 = (wskazowki[0]['legs'][0]['steps'][3]['transit_details']['departure_time']['text'])
                lprzystankow2 = (wskazowki[0]['legs'][0]['steps'][3]['transit_details']['num_stops'])
                nrtramwaju2 = (wskazowki[0]['legs'][0]['steps'][3]['transit_details']['line']['short_name'])
                nazwatramwaju2 = (wskazowki[0]['legs'][0]['steps'][3]['transit_details']['headsign'])
            except:
                nazwatramwaju2 = ""
                nrtramwaju2 = ""
                lprzystankow2 = ""
                godzinawyjazdutram2 = ""
                godzinadojazdu2 = ""
                gdziewsiadasz2 = ""

        if not POMIN:

            if nazwatramwaju2!="":
                droga=(
                    "\nWyjazd: " + godzinawyjazdutram + "\nze stacji: \n"+gdziewsiadasz2+ "\n\nWsiądź do: \n     [" + str(
                        nrtramwaju) + "] " + str(nazwatramwaju) + "\nPrzejedź " + str(
                        lprzystankow)+ " przystanków " + "\n\nWsiądź do: \n     [" + str(
                        nrtramwaju2) + "] " + str(nazwatramwaju2) + "\nPrzejedź " + str(
                        lprzystankow2)+  "przystanków\n\n\nOdległość: " + odlegloscD)
            else:
                droga=("\nWyjazd: " + godzinawyjazdutram + "\nze stacji: \n"+gdziewsiadasz+ "\nWsiądź do: [" +str(nrtramwaju) +"] "+ str(
                    nazwatramwaju) + "\nLiczba przystanków: " + str(lprzystankow)+"\nOdległość: " + odlegloscD  +"\nDojedziesz o: " +godzinadojazdu)

        else:

            if (len(wskazowki[0]['legs'][0]['steps'])) == 1 and godzinawyjazdutram!="" :
                droga=("\nWyjazd o:\n" + godzinawyjazdutram + "\n\n" + wskazowki[0]['legs'][0]['steps'][0][
                'html_instructions'] + "\nNazwa tramwaju:\n" + str(nazwatramwaju) + "\nNr: " + str(nrtramwaju))

            elif (len(wskazowki[0]['legs'][0]['steps'])) == 2:
                droga=(wskazowki[0]['legs'][0]['steps'][0][
                'html_instructions'] + "\nWyjedź o: " + godzinawyjazdutram + "\nOdległoość: " + odlegloscD + "\nCzas: " + czasD + "\nNazwa pierwszego tramwaju: " + str(
                nazwatramwaju) + "\nNr: " + str(nrtramwaju) + "\nLiczba przystanków: " + str(
                lprzystankow) + "\nNazwa drugiego tramwaju: " + str(nazwatramwaju2) + " Nr: " + str(
                nrtramwaju2) + "\nLiczba przystanków: " + str(lprzystankow2))
            else:
                droga=("Przejdź się!\n"+wskazowki[0]['legs'][0]['steps'][0]['html_instructions'])

        self.add_widget(Button(text=droga,pos_hint = {"x": 0, "top": 1},size_hint=(1.1, 1)))
        self.tlo = Image(source='Tloo1.png')
        self.tlo.opacity = 0.2
        self.tlo.size_hint_x = 1
        self.tlo.size_hint_y = 1
        self.tlo.pos_hint = {"x": 0, "top": 1}
        self.add_widget(self.tlo)

        self.canvas.add(Color(72/255, 19/255, 91/255))
        self.canvas.add(Rectangle(pos=(0, 730), size=(1000, 130)))

        print(len(wskazowki[0]['legs'][0]['steps']))

        self.two = Image(source='twopts.png')
        self.two.opacity = 0.9
        self.two.size_hint_x = 0.2
        self.two.size_hint_y = 0.1
        self.two.pos_hint = {"x": 0.4, "top": 0.98}
        self.add_widget(self.two)
        #user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
        #map.map_source = source
        #MapView().map_source = "osm"
        #mapview = MapView(zoom=11, lat=50.6394, lon=3.057)
        #self.add_widget(mapview)

class MyApi(App):
    def build(self):
        self.title = 'Trip Planner- Mikolaj Bozecki'
        return LoginScreen()

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


import os
import numpy as np
import argparse

'''
m = 'lenet'
d = 'MNIST'
check_results = ['{}-{}-dense'.format(m, d),
                 '{}-{}-rs-10'.format(m, d),
                 '{}-{}-rs-2'.format(m, d)]
for c in check_results:
'''

# c = 'lenet-CIFAR10-rs-2-wrap'

parser = argparse.ArgumentParser()
parser.add_argument('--exp_name', type=str, default='lenet-MNIST-rs-2')

args = parser.parse_args()

results_dir = os.path.join('./log_dir', args.exp_name)

results_npz = os.listdir(results_dir)

test_acc = []
for r_npz in results_npz:
    if 'npz' in r_npz:
        full_r_npz = os.path.join(results_dir, r_npz)
        r = np.load(full_r_npz)
        print(r['train_losses'].shape, r['train_accs'].shape, r['test_accs'].shape)
        test_acc.append(r['test_accs'])

test_acc = np.asarray(test_acc)

print(args.exp_name)
print(100 * (1.0 - np.mean(test_acc, 0)))
print(np.std(test_acc, 0))


from odoo import api, fields, models, _
import odoo.addons.decimal_precision as dp
from odoo.exceptions import ValidationError,UserError
from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT, float_compare
import datetime as dt
from datetime import datetime, timedelta
import calendar
import time
import re
from odoo.addons import decimal_precision as dp
from dateutil import relativedelta
import logging
_logger = logging.getLogger(__name__)
from odoo.tools import email_re, email_split, email_escape_char, float_is_zero, float_compare, \
    pycompat, date_utils

class sale_custom(models.Model):
    _inherit="sale.order"
    date_valid=fields.Integer('validity ')
    user_id=fields.Many2one('res.users',string="Sales Rep")
    discount=fields.Selection(related='partner_id.discount',string='Discount')
    reason=fields.Selection([('A','A'),('B','B')],'Reason')
    comment_cancel=fields.Char('Comment')
    order_date=fields.Date('Order Date',default=dt.datetime.strftime(datetime.today(),'%Y-%m-%d'))
    #region=fields.Many2one(related='user_id.region',string='Region')

    @api.onchange('order_date')
    def get_order_date(self):
        self.order_date=dt.datetime.strftime(datetime.today(),'%Y-%m-%d')

    @api.onchange('partner_id')
    def get_blacklist(self):
        if self.partner_id.is_blacklist==True:
            raise ValidationError('you can not create sale order for this customer')
    @api.constrains('order_date')
    def get_date(self):
        _logger.info(type(self.order_date))
        _logger.info(type(datetime.today()))
        if self.order_date < dt.datetime.today().date():
            raise ValidationError('Order Date must be greater than Today')
    @api.constrains('reason','comment_cancel')
    def print_message_reason(self):
        message_body= "Customer :"+str(self.partner_id.name) +"
"+"  Cancelation Reason: "+str(self.reason)
        if self.comment_cancel:
            message_body+="
"+"  Cancelation Comment: "+str(self.comment_cancel)
        _logger.info('Message')
        _logger.info(message_body)
        #sql="insert into mail_message(body,res_id,model,message_type,create_uid) values("+message_body+","+str(self.id)+",'sale.order','notification',"+ str(self.env.uid)+")"
        #_logger.info(sql)
        #self._cr.execute(sql)
        value={
        'body':message_body,
        'res_id':self.id,
        'model':'sale.order',
        'message_type':'notification',
        }
        if (self.reason and self.comment_cancel) or self.reason:
            self.message_ids.create(value)

    @api.multi
    def action_cancel_order(self):
        self.write({'state': 'cancel'})
        _logger.info('Cancel')
        _logger.info('idddd')
        _logger.info(self.id)

        cancel_oreder=self.env['sale.order.cancelled'].search([('cancelled_order','=',self.id)])
        self.env['ir.cron'].clear_caches()
        res= { 'name':'',
         'view_type': 'form',
        'view_mode': 'form',
        'res_model': 'sale.order.cancelled',
        'target': 'new',
         'view_type': 'form',
        'view_id':self.env.ref('sale_custom.cancel_custom_order_from').id ,
        'tag': 'reload',
        'context':{'default_cancelled_order': self.id},
        'res_id':cancel_oreder.id,
        'flags': {'form': {'action_buttons': True}} ,
        'type': 'ir.actions.act_window', }

        return res
    @api.onchange('date_valid')
    def change_validity_date_vlid(self):
        _logger.info('Validation')
        if self.date_valid<0:
            raise ValidationError('validity date must be postive value')

        if self.date_valid>0:
            self.validity_date=datetime.strftime(dt.datetime.today() +timedelta(days=self.date_valid),'%Y-%m-%d %H:%M')
            _logger.info(self.validity_date)
        """if not self.date_valid and self.create_date:
            self.validity_date= datetime.strftime(self.create_date,'%Y-%m-%d %H:%M')"""
    @api.constrains('date_valid')
    def save_validity_date_vlid(self):
        _logger.info('Validation')

        if self.date_valid>0:
            self.validity_date=datetime.strftime(dt.datetime.today() +timedelta(days=self.date_valid),'%Y-%m-%d %H:%M')
            _logger.info(self.validity_date)
    @api.onchange('confirmation_date')
    def get_state_action(self):
        _logger.info('ssssssssssss')
        if self.state=='sale':
            _logger.info('777777777777')
            if self.partner_id.credit_limit<self.amount_total:
                warning_mess = {
                            'title': _('Customer Credit Limit!'),
                            'message' : 'Credit Limit for Customer is less than total sale order'
                        }

                return {'warning': warning_mess}

    @api.multi
    @api.onchange('order_line','discount','amount_untaxed','amount_tax')
    def get_discount_list(self):
        _logger.info('sdfsdfdsf')
        _logger.info(self.discount)
        self.amount_untaxed=0
        self.amount_tax=0
        dif=0
        for rec in self.order_line:
                rec.price_subtotal=rec.product_uom_qty*rec.price_unit
                if rec.discount2=='1':
                     rec.price_subtotal-=rec.price_subtotal*0.15
                if rec.discount2=='2':
                    rec.price_subtotal-=(rec.price_subtotal*0.15)+(rec.price_subtotal*0.15*0.05)
                if rec.discount2=='3':
                    dis_value=(rec.price_subtotal*0.15)+(rec.price_subtotal*0.15*0.05)+(rec.price_subtotal*0.15*0.05*0.05)
                    price_discount=rec.price_subtotal-dis_value
                    rec.price_subtotal-=(rec.price_subtotal*0.15)+(rec.price_subtotal*0.15*0.05)+(rec.price_subtotal*0.15*0.05*0.05)
                self.amount_untaxed+=rec.price_subtotal
                rec.price_total_discount=rec.price_subtotal
                if rec.tax_id :
                    _logger.info('TAXES')
                    _logger.info(rec.tax_id.amount)
                    _logger.info(self.amount_tax)
                    self.amount_tax+=rec.price_subtotal*(rec.tax_id.amount/100)
                    self.price_total_discount=rec.price_subtotal*(rec.tax_id.amount/100)+rec.price_subtotal

        dif= self.amount_untaxed
        if self.discount=='1':

            _logger.info('self.amount_untaxed*0.15')
            _logger.info(self.amount_untaxed*0.15)
            self.amount_untaxed-=self.amount_untaxed*0.15
            _logger.info(self.amount_untaxed)
        if self.discount=='2':
            self.amount_untaxed-=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)
        if self.discount=='3':
            dis_value=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)+(self.amount_untaxed*0.15*0.05*0.05)
            price_discount=self.amount_untaxed-dis_value
            self.amount_untaxed-=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)+(self.amount_untaxed*0.15*0.05*0.05)

        self.update({'amount_untaxed':self.amount_untaxed})
        if self.amount_tax:
            self.update({'amount_total':self.amount_untaxed+self.amount_tax})
        else:
            self.update({'amount_total':self.amount_untaxed+self.amount_tax})
        dif-=self.amount_untaxed
        for rec in self.order_line:
            rec.price_total_discount-=(dif/len(self.order_line))
    @api.constrains('order_line')
    def get_discount_list2(self):
        _logger.info('constrains')
        _logger.info(self.discount)
        self.amount_untaxed=0
        self.amount_tax=0
        dif=0
        for rec in self.order_line:
                rec.price_subtotal=rec.product_uom_qty*rec.price_unit
                if rec.discount2=='1':
                     rec.price_subtotal-=rec.price_subtotal*0.15
                if rec.discount2=='2':
                    rec.price_subtotal-=(rec.price_subtotal*0.15)+(rec.price_subtotal*0.15*0.05)
                if rec.discount2=='3':
                    dis_value=(rec.price_subtotal*0.15)+(rec.price_subtotal*0.15*0.05)+(rec.price_subtotal*0.15*0.05*0.05)
                    price_discount=rec.price_subtotal-dis_value
                    rec.price_subtotal-=(rec.price_subtotal*0.15)+(rec.price_subtotal*0.15*0.05)+(rec.price_subtotal*0.15*0.05*0.05)
                self.amount_untaxed+=rec.price_subtotal
                rec.price_total_discount=rec.price_subtotal
                if rec.tax_id :
                    _logger.info('TAXES')
                    _logger.info(rec.tax_id.amount)
                    _logger.info(self.amount_tax)
                    self.amount_tax+=rec.price_subtotal*(rec.tax_id.amount/100)
                    self.price_total_discount=rec.price_subtotal*(rec.tax_id.amount/100)+rec.price_subtotal

        dif= self.amount_untaxed
        if self.discount=='1':

            _logger.info('self.amount_untaxed*0.15')
            _logger.info(self.amount_untaxed*0.15)
            self.amount_untaxed-=self.amount_untaxed*0.15
            _logger.info(self.amount_untaxed)
        if self.discount=='2':
            self.amount_untaxed-=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)
        if self.discount=='3':
            dis_value=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)+(self.amount_untaxed*0.15*0.05*0.05)
            price_discount=self.amount_untaxed-dis_value
            self.amount_untaxed-=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)+(self.amount_untaxed*0.15*0.05*0.05)

        self.update({'amount_untaxed':self.amount_untaxed})
        if self.amount_tax:
            self.update({'amount_total':self.amount_untaxed+self.amount_tax})
        else:
            self.update({'amount_total':self.amount_untaxed+self.amount_tax})
        dif-=self.amount_untaxed
        for rec in self.order_line:
            rec.price_total_discount-=(dif/len(self.order_line))

class cancel_order(models.Model):
    _name="sale.order.cancelled"
    reason=fields.Selection([('A','A'),('B','B')],'Reason',required=True)
    comment_cancel=fields.Char('Comment')
    cancelled_order=fields.Many2one('sale.order')
    @api.constrains('reason','comment_cancel')
    def get_reaon(self):
        _logger.info('Reason')
        self.cancelled_order.reason=self.reason
        self.cancelled_order.comment_cancel=self.comment_cancel
        _logger.info(self.cancelled_order)

    @api.model
    def create(self,vals):
        _logger.info('CREATE')
        _logger.info(self.reason)
        return super(cancel_order,self).create(vals)

class sale_order_line(models.Model):
    _inherit='sale.order.line'
    discount2=fields.Selection([('1','15%'),('2','%15,5%'),('3','%15,%5,5%')],'Discount',store=True)
    price_total_discount=fields.Float('Total price Discount')
    @api.constrains('product_uom_qty')
    def get_nagtive_value(self):
        if self.product_uom_qty<0:
            raise ValidationError('Order Quantity must be postive value')

    @api.multi
    def write(self,values):
        _logger.info('writeeee')
        return super(sale_order_line,self).write(values)
    @api.multi
    @api.onchange('discount2','price_subtotal','tax_id')
    def calculated_discount(self):
        _logger.info('Change')
        _logger.info(self.discount2)
        if self.discount2:
            self.price_subtotal=self.product_uom_qty*self.price_unit
            if self.discount2=='1':
                self.price_subtotal-=self.price_subtotal*0.15
            if self.discount2=='2':
                self.price_subtotal-=(self.price_subtotal*0.15)+(self.price_subtotal*0.15*0.05)
            if self.discount2=='3':
                dis_value=(self.price_subtotal*0.15)+(self.price_subtotal*0.15*0.05)+(self.price_subtotal*0.15*0.05*0.05)
                price_discount=self.price_subtotal-dis_value
                self.price_subtotal-=(self.price_subtotal*0.15)+(self.price_subtotal*0.15*0.05)+(self.price_subtotal*0.15*0.05*0.05)
            if not self.discount2:
                self.price_subtotal=self.product_uom_qty*self.price_unit

    @api.onchange('product_uom_qty', 'product_uom', 'route_id')
    def _onchange_product_id_check_availability(self):
        _logger.info('FFFFFFFFFFFFFFFFFFF')
        if not self.product_id or not self.product_uom_qty or not self.product_uom:
            self.product_packaging = False
            return {}
        if self.product_id.type == 'product':
            precision = self.env['decimal.precision'].precision_get('Product Unit of Measure')
            product = self.product_id.with_context(
                warehouse=self.order_id.warehouse_id.id,
                lang=self.order_id.partner_id.lang or self.env.user.lang or 'en_US'
            )
            product_qty = self.product_uom._compute_quantity(self.product_uom_qty, self.product_id.uom_id)
            if float_compare(product.virtual_available, product_qty, precision_digits=precision) == -1:
                is_available = self._check_routing()
                if not is_available:
                    message =  _('You plan to sell %s %s of %s but you only have %s %s available in %s warehouse.') % \
                            (self.product_uom_qty, self.product_uom.name, self.product_id.name, product.virtual_available, product.uom_id.name, self.order_id.warehouse_id.name)
                    # We check if some products are available in other warehouses.
                    if float_compare(product.virtual_available, self.product_id.virtual_available, precision_digits=precision) == -1:
                        message += _('\nThere are %s %s available across all warehouses.\n\n') % \
                                (self.product_id.virtual_available, product.uom_id.name)
                        for warehouse in self.env['stock.warehouse'].search([]):
                            quantity = self.product_id.with_context(warehouse=warehouse.id).virtual_available
                            if quantity > 0:
                                message += "%s: %s %s\n" % (warehouse.name, quantity, self.product_id.uom_id.name)
                    warning_mess = {
                        'title': _('Not enough inventory!'),
                        'message' : message
                    }
                    if warning_mess:
                        return {}

                    #return {'warning': warning_mess}
        return {}

class invoice_discount(models.Model):
    _inherit='account.invoice'
    discount=fields.Selection(related='partner_id.discount',string='Discount')
    @api.one
    @api.depends('invoice_line_ids.price_subtotal', 'tax_line_ids.amount', 'tax_line_ids.amount_rounding',
                 'currency_id', 'company_id', 'date_invoice', 'type')
    def _compute_amount(self):
        _logger.info('depends account invoice')
        round_curr = self.currency_id.round
        self.amount_untaxed = sum(line.price_subtotal for line in self.invoice_line_ids)
        _logger.info('UN TAXE')
        _logger.info(self.amount_untaxed)
        if self.discount=='1':
            self.amount_untaxed-=self.amount_untaxed*0.15
        if self.discount=='2':
            self.amount_untaxed-=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)
        if self.discount=='3':
            dis_value=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)+(self.amount_untaxed*0.15*0.05*0.05)
            price_discount=self.amount_untaxed-dis_value
            self.amount_untaxed-=(self.amount_untaxed*0.15)+(self.amount_untaxed*0.15*0.05)+(self.amount_untaxed*0.15*0.05*0.05)
        _logger.info(self.amount_untaxed)
        self.update({'amount_untaxed':self.amount_untaxed})
        self.amount_tax = sum(round_curr(line.amount_total) for line in self.tax_line_ids)
        self.amount_total = self.amount_untaxed + self.amount_tax
        amount_total_company_signed = self.amount_total
        amount_untaxed_signed = self.amount_untaxed
        if self.currency_id and self.company_id and self.currency_id != self.company_id.currency_id:
            currency_id = self.currency_id
            amount_total_company_signed = currency_id._convert(self.amount_total, self.company_id.currency_id, self.company_id, self.date_invoice or fields.Date.today())
            amount_untaxed_signed = currency_id._convert(self.amount_untaxed, self.company_id.currency_id, self.company_id, self.date_invoice or fields.Date.today())
        sign = self.type in ['in_refund', 'out_refund'] and -1 or 1
        self.amount_total_company_signed = amount_total_company_signed * sign
        self.amount_total_signed = self.amount_total * sign
        self.amount_untaxed_signed = amount_untaxed_signed * sign

    @api.multi
    def action_move_create(self):
        _logger.info('action_move_create SALE CUST')
        """ Creates invoice related analytics and financial move lines """
        account_move = self.env['account.move']
        desc=0
        total_line=0
        for line in self.invoice_line_ids:
            total_line+=line.price_subtotal
        _logger.info('VALUE OF DISCOUNT')
        desc=abs((self.amount_untaxed-total_line))
        for inv in self:
            if not inv.journal_id.sequence_id:
                raise UserError(_('Please define sequence on the journal related to this invoice.'))
            if not inv.invoice_line_ids.filtered(lambda line: line.account_id):
                raise UserError(_('Please add at least one invoice line.'))
            if inv.move_id:
                continue

            if not inv.date_invoice:
                inv.write({'date_invoice': fields.Date.context_today(self)})
            if not inv.date_due:
                inv.write({'date_due': inv.date_invoice})
            company_currency = inv.company_id.currency_id

            # create move lines (one per invoice line + eventual taxes and analytic lines)
            iml = inv.invoice_line_move_line_get()
            iml += inv.tax_line_move_line_get()
            _logger.info('IML')
            _logger.info(iml)

            diff_currency = inv.currency_id != company_currency
            # create one move line for the total and possibly adjust the other lines amount
            total, total_currency, iml = inv.compute_invoice_totals(company_currency, iml)

            name = inv.name or ''
            if inv.payment_term_id:
                totlines = inv.payment_term_id.with_context(currency_id=company_currency.id).compute(total, inv.date_invoice)[0]
                res_amount_currency = total_currency
                for i, t in enumerate(totlines):
                    if inv.currency_id != company_currency:
                        amount_currency = company_currency._convert(t[1], inv.currency_id, inv.company_id, inv._get_currency_rate_date() or fields.Date.today())
                    else:
                        amount_currency = False

                    # last line: add the diff
                    res_amount_currency -= amount_currency or 0
                    if i + 1 == len(totlines):
                        amount_currency += res_amount_currency
                    _logger.info('TOTAL PAYEMrnt')
                    _logger.info(t[1]-desc)
                    iml.append({
                        'type': 'dest',
                        'name': name,
                        'price': t[1]-desc,
                        'account_id': inv.account_id.id,
                        'date_maturity': t[0],
                        'amount_currency': diff_currency and amount_currency,
                        'currency_id': diff_currency and inv.currency_id.id,
                        'invoice_id': inv.id
                    })
            else:
                _logger.info('TOTAL After Valdition')

                iml.append({
                    'type': 'dest',
                    'name': name,
                    'price': total-desc,
                    'account_id': inv.account_id.id,
                    'date_maturity': inv.date_due,
                    'amount_currency': diff_currency and total_currency,
                    'currency_id': diff_currency and inv.currency_id.id,
                    'invoice_id': inv.id
                })
                _logger.info(total)
                _logger.info(type(total))
            part = self.env['res.partner']._find_accounting_partner(inv.partner_id)
            line = [(0, 0, self.line_get_convert(l, part.id)) for l in iml]
            line = inv.group_lines(iml, line)

            line = inv.finalize_invoice_move_lines(line)
            account_discount=self.env['res.config.settings'].search([])
            account_discount_id=0
            if self.discount:
                for rec in account_discount:
                    if not rec.discount_account_id:
                        raise ValidationError('Please Select Account Discount...')
                    else :
                        account_discount_id=rec.discount_account_id.id

                line.append((0, 0, { 'partner_id': part.id, 'name': 'Discount', 'debit':desc , 'credit':False , 'account_id':account_discount_id , 'analytic_line_ids': [], 'amount_currency': 0, 'currency_id': False, 'quantity': 1.0, 'product_id': False, 'product_uom_id': False, 'analytic_account_id': False, 'invoice_id': inv.id, 'tax_ids': False, 'tax_line_id': False, 'analytic_tag_ids': False}))

            date = inv.date or inv.date_invoice
            move_vals = {
                'ref': inv.reference,
                'line_ids': line,
                'journal_id': inv.journal_id.id,
                'date': date,
                'narration': inv.comment,
            }
            move = account_move.create(move_vals)
            # Pass invoice in method post: used if you want to get the same
            # account move reference when creating the same invoice after a cancelled one:
            move.post(invoice = inv)
            # make the invoice point to that move
            vals = {
                'move_id': move.id,
                'date': date,
                'move_name': move.name,
            }
            inv.write(vals)
        return True

class invoice_line_discount(models.Model):
    _inherit='account.invoice.line'
    discount2=fields.Selection(related='sale_line_ids.discount2',string='Discount')
    price_untaxes_discount=fields.Float('subtotal',compute="_compute_price")
    @api.one
    @api.depends('price_unit', 'discount', 'invoice_line_tax_ids', 'quantity',
        'product_id', 'invoice_id.partner_id', 'invoice_id.currency_id', 'invoice_id.company_id',
        'invoice_id.date_invoice', 'invoice_id.date')
    def _compute_price(self):
        _logger.info('COMPUTE PRICE')
        currency = self.invoice_id and self.invoice_id.currency_id or None
        price = self.price_unit
        if self.discount2:
            if self.discount2=='1':
                price-=price*0.15
            if self.discount2=='2':
                price-=(price*0.15)+(price*0.15*0.05)
            if self.discount2=='3':
                dis_value=(price*0.15)+(price*0.15*0.05)+(price*0.15*0.05*0.05)
                price_discount=price-dis_value
                price-=(price*0.15)+(price*0.15*0.05)+(price*0.15*0.05*0.05)

        taxes = False
        if self.invoice_line_tax_ids:
            taxes = self.invoice_line_tax_ids.compute_all(price, currency, self.quantity, product=self.product_id, partner=self.invoice_id.partner_id)
        self.price_subtotal = price_subtotal_signed = taxes['total_excluded'] if taxes else self.quantity * price
        self.price_total = taxes['total_included'] if taxes else self.price_subtotal

        _logger.info('DISCOUNT')
        _logger.info(self.price_subtotal)
        if self.invoice_id.currency_id and self.invoice_id.currency_id != self.invoice_id.company_id.currency_id:
            currency = self.invoice_id.currency_id
            date = self.invoice_id._get_currency_rate_date()
            price_subtotal_signed = currency._convert(price_subtotal_signed, self.invoice_id.company_id.currency_id, self.company_id or self.env.user.company_id, date or fields.Date.today())
        sign = self.invoice_id.type in ['in_refund', 'out_refund'] and -1 or 1
        self.price_subtotal_signed = price_subtotal_signed * sign
        self.price_untaxes_discount=self.price_subtotal
class inherite_confi_setting(models.TransientModel):
    _inherit='res.config.settings'
    discount_account_id=fields.Many2one('account.account',string='Sale Discount Account',related='company_id.discount_account_id',readonly=False)


import sys

def check_module(conf, module_name):
    conf.start_message("Checking for module %r" % (module_name,))
    python = sys.executable
    cmd = [python, "-c", "'import %s'" % module_name]
    ret = conf.try_command(" ".join(cmd), kw={"shell": True})
    if ret:
        conf.end_message("yes")
    else:
        conf.end_message("no")
    return ret


import eel, platform, sys, datetime, urllib.request, urllib.parse, chess, chess.pgn, chess.engine
from tkinter import Tk
from tkinter.filedialog import askopenfilename, asksaveasfile

eel.init("web")

whiteType = None
blackType = None
whiteID = None
blackID = None
curMove = None
curMoveNum = None
board = None
pgn = None
node = None
engine = chess.engine.SimpleEngine.popen_uci("stockfish_10_x64.exe")
whiteEngSpeed = 1.0
blackEngSpeed = 1.0
whiteEngine = None
blackEngine = None
hint = None

@eel.expose
def startNewGame(wType, bType, wID, bID):
    global whiteType
    whiteType = wType
    global blackType
    blackType = bType
    global whiteID
    whiteID = wID
    global blackID
    blackID = bID
    global curMove
    curMove = "white"
    global curMoveNum
    curMoveNum = 1
    global board
    board = chess.Board()
    global pgn
    pgn = chess.pgn.Game()
    pgn.headers["Event"] = "Desktop Chess"
    pgn.headers["Site"] = platform.node()
    pgn.headers["Date"] = datetime.datetime.now()
    pgn.headers["Round"] = "1"
    pgn.headers["White"] = whiteID
    pgn.headers["Black"] = blackID
    eel.updatePgnDisplay(str(pgn))
    updateBoardDisplay()
    if whiteType == "engine":
        global whiteEngine
        whiteEngine = chess.engine.SimpleEngine.popen_uci(whiteID)
    if blackType == "engine":
        global blackEngine
        blackEngine = chess.engine.SimpleEngine.popen_uci(blackID)
    if whiteType == "human":
        genHint()
        eel.openMoveInput(curMove)
    else:
        makeEngineMove(whiteEngine)

@eel.expose
def selectFile():
    Tk().withdraw()
    return askopenfilename()

@eel.expose
def saveFile(contents):
    Tk().withdraw()
    path = asksaveasfile()
    f = open(path.name, "w")
    f.write(contents)
    f.close()

@eel.expose
def testMove(move):
    global board
    return chess.Move.from_uci(move) in board.legal_moves

@eel.expose
def submitMove(move):
    global board
    global curMove
    global pgn
    global node
    global engine
    board.push(chess.Move.from_uci(move))
    updateBoardDisplay()
    # Update PGN and curMove
    if curMove == "white":
        global curMoveNum
        if curMoveNum == 1:
            node = pgn.add_variation(chess.Move.from_uci(move))
        else:
            node = node.add_variation(chess.Move.from_uci(move))
        curMove = "black"
    else:
        node = node.add_variation(chess.Move.from_uci(move))
        info = engine.analyse(board, chess.engine.Limit(depth=20))
        node.comment = "Score: " + str(info["score"].relative.score())
        curMove = "white"
    curMoveNum += 1
    # Check for continuation of game
    if board.is_game_over():
        updatePgnResult()
        eel.updatePgnDisplay(str(pgn))
        eel.endGame()
        return
    eel.updatePgnDisplay(str(pgn))
    # Handle next move
    if curMove == "white" and whiteType == "human":
        genHint()
        eel.openMoveInput(curMove)
    elif curMove == "black" and blackType == "human":
        genHint()
        eel.openMoveInput(curMove)
    elif curMove == "white" and whiteType == "engine":
        global whiteEngine
        makeEngineMove(whiteEngine)
    else:
        global blackEngine
        makeEngineMove(blackEngine)

def makeEngineMove(enginePlayer):
    global board
    global curMove
    global pgn
    global node
    global engine
    global whiteEngSpeed
    global blackEngSpeed
    eel.closeMoveInput(curMove)
    if curMove == "white":
        result = enginePlayer.play(board, chess.engine.Limit(time=whiteEngSpeed))
    else:
        result = enginePlayer.play(board, chess.engine.Limit(time=blackEngSpeed))
    board.push(result.move)
    updateBoardDisplay()
    # Update PGN and curMove
    if curMove == "white":
        global curMoveNum
        if curMoveNum == 1:
            node = pgn.add_variation(result.move)
        else:
            node = node.add_variation(result.move)
        curMove = "black"
    else:
        node = node.add_variation(result.move)
        info = engine.analyse(board, chess.engine.Limit(depth=20))
        node.comment = "Score: " + str(info["score"].relative.score())
        curMove = "white"
    curMoveNum += 1
    # Check for continuation of game
    if board.is_game_over():
        updatePgnResult()
        eel.updatePgnDisplay(str(pgn))
        eel.endGame()
        return
    eel.updatePgnDisplay(str(pgn))(continueFromEngineMove)

def continueFromEngineMove(x):
    global board
    global curMove
    global pgn
    global node
    global engine
    global engineTime
    # Handle next move
    if curMove == "white" and whiteType == "human":
        genHint()
        eel.openMoveInput(curMove)
    elif curMove == "black" and blackType == "human":
        genHint()
        eel.openMoveInput(curMove)
    elif curMove == "white" and whiteType == "engine":
        global whiteEngine
        makeEngineMove(whiteEngine)
    else:
        global blackEngine
        makeEngineMove(blackEngine)

def updatePgnResult():
    global board
    global pgn
    global node
    if board.is_game_over():
        result = board.result()
        pgn.headers["Result"] = result
        node.comment += "Result: " + result
        eel.updatePgnDisplay(str(pgn))

def genHint():
    global board
    global engine
    global hint
    result = engine.play(board, chess.engine.Limit(time=1))
    hint = result.move.uci()

@eel.expose
def getHint():
    global hint
    return hint

@eel.expose
def setWhiteEngSpeed(speed):
    global whiteEngSpeed
    whiteEngSpeed = float(speed)

@eel.expose
def setBlackEngSpeed(speed):
    global blackEngSpeed
    blackEngSpeed = float(speed)

def updateBoardDisplay():
    global board
    eel.updateBoardDisplay("https://chessboardimage.com/" + urllib.parse.quote(board.fen()) + ".png")

try:
    eel.start("main.html", mode="chrome", size=(1280, 720))
except EnvironmentError:
    if sys.platform in ["win32", "win64"] and int(platform.release()) >= 10:
        eel.start("main.html", mode="edge", size=(1280, 720))
    else:
        raise


import json
import time
from operator import itemgetter

import openpyxl
import requests

start_time = time.time()

wb = openpyxl.load_workbook('report.xlsx')

YDAuth = {'za4aroff.ol': 'AgAAAAAzN9ktAAXAInwzJfwlY0E4taHqCQUC33I',
          'macsim.reshetar': 'AgAAAAArGY4IAAXAIq_OsOIJXEgIvBjrf0dpP0s'}

direct_client_logins = ["za4aroff.ol", "za4aroff.ol", "macsim.reshetar", "za4aroff.ol"]  # НП СПБ, НП МСК, 1001, Brand
clientTokens = {"za4aroff.ol": "AgAAAAAzN9ktAAXAInwzJfwlY0E4taHqCQUC33I",
                "macsim.reshetar": "AgAAAAArGY4IAAXAIq_OsOIJXEgIvBjrf0dpP0s"}
date1 = "2019-10-08"
date2 = "2019-10-09"
ids = ["35656455", "37340325", "42890799", "54227233"]
metrics = ["ym:s:goal39547444visits", "ym:s:goal39545641visits", "ym:s:goal44259842visits", "ym:s:goal52718371visits"]
dimensions = "ym:s:goal,ym:s:lastsignDirectClickOrder,ym:s:lastsignDirectBannerGroup"
filters = ["ym:s:goal==39547444", "ym:s:goal==39545641", "ym:s:goal==44259842", "ym:s:goal==52718371"]
url = "https://api-metrika.yandex.net/stat/v1/data"

def saveConversions(login_list, clientTokens, directIDs, metrics, startDate, endDate, filters):
    if 'Конверсии' in wb.sheetnames:
        report = wb['Конверсии']
    else:
        report = wb.create_sheet('Конверсии')

    for n, field in enumerate(['Кампания', 'Группа', 'ID Группы', 'Конверсии']):  # Вводим поля таблицы
        _ = report.cell(column=1 + n, row=1, value=field)

    for n, acc in enumerate(login_list):
        requestURL = url + "?direct_client_logins=%s&ids=%s&metrics=%s&date1=%s&date2=%s&dimensions=%s&filters=%s" \
                           "&pretty=true" % (acc, directIDs[n], metrics[n], startDate, endDate, dimensions, filters[n])

        headers = {"Authorization": "OAuth " + clientTokens.get(acc), "Client-Login": acc, }
        req = requests.get(requestURL, headers=headers)
        # print(req.text)
        jsonReport = json.loads(req.text)

        maxRow = report.max_row
        print(jsonReport["data"])
        for index, item in enumerate(jsonReport["data"]):
            if item['dimensions'][1]['name'] != "Other campaigns":
                _ = report.cell(row=index + maxRow, column=1, value=item['dimensions'][1]['name'])
                _ = report.cell(row=index + maxRow, column=2, value=item['dimensions'][2]['name'])
                _ = report.cell(row=index + maxRow, column=3, value=item['dimensions'][2]['id'])
                _ = report.cell(row=index + maxRow, column=4, value=int(item['metrics'][0]))
                print("Найдены конверсии в кампании %s, в группе %s в количестве: %s." % \
                      (item['dimensions'][1]['name'], item['dimensions'][2]['name'], int(item['metrics'][0])))
    wb.save(filename="report.xlsx")

def connectConversionsWithCampaigns():  # Добавляем конверсии в таблицу с данными
    data = wb["Данные"]
    conversions = wb["Конверсии"]
    for n, field in enumerate(["Конверсии", "% конверсии", "CPA"]):  # Вводим поля таблицы
        _ = data.cell(column=8 + n, row=1, value=field)

    dataList = []  # Сортируем "Данные" по группе объявлений
    for n, row in enumerate(data):
        dataList.append([])
        for col in row:
            dataList[n].append(col.value)
    sortedCosts = sorted(dataList[1:], key=itemgetter(3))
    maxCol = data.max_column
    for n, row in enumerate(sortedCosts):
        for col in range(maxCol):
            _ = data.cell(row=n + 2, column=col + 1, value=row[col])

    dataList = []  # Сортируем "Конверсии" по группе объявлений
    dataRow = 0
    for n, row in enumerate(conversions):
        if row[2].value != None:
            dataList.append([])
            for m, col in enumerate(row):
                # print(col.value)
                if col.value == None:
                    dataList[dataRow].append("")
                elif str(col.value).isdigit():
                    dataList[dataRow].append(int(col.value))
                else:
                    dataList[dataRow].append(str(col.value))
            dataRow += 1

    # print(dataList)
    sortedConversions = sorted(dataList[1:], key=itemgetter(2))
    maxCol = conversions.max_column
    for n, row in enumerate(sortedConversions):
        for col in range(maxCol):
            _ = conversions.cell(row=n + 2, column=col + 1, value=row[col])

    convCounter = 1
    for camp in range(1, data.max_row):  # Соотносим конверсии с группами объявлений
        if convCounter < conversions.max_row:
            if data["D"][camp].value == int(conversions["C"][convCounter].value):
                _ = data.cell(row=camp + 1, column=8, value=int(conversions["D"][convCounter].value))
                _ = data.cell(row=camp + 1, column=10, value=float(data["G"][camp].value)
                                                             / int(conversions["D"][convCounter].value))
                if data["F"][camp].value > 0:
                    _ = data.cell(row=camp + 1, column=9,
                                  value=int(conversions["D"][convCounter].value) / data["F"][camp].value)
                else:
                    _ = data.cell(row=camp + 1, column=9, value=0)
                print("Выгружаю конверсии для %s из кампании %s." %
                      (conversions["B"][convCounter].value, conversions["A"][convCounter].value))
                convCounter += 1
        else:
            break

    wb.save(filename="report.xlsx")

def mainFunc(login_list, clientTokens, directIDs, metrics, startDate, endDate, filters):
    saveConversions(login_list, clientTokens, directIDs, metrics, startDate, endDate, filters)
    connectConversionsWithCampaigns()

mainFunc(direct_client_logins, clientTokens, ids, metrics, date1, date2, filters)
print("\n--- %s seconds ---" % (time.time() - start_time))


buah = {'apel' : 5000, 'jeruk' : 8500, 'mangga' : 7800, 'duku' : 6500}
def myData(x):
    print('Data buah : ')
    for n, i in x.items():
        print('- {0} (Harga Rp {1} / kg)'.format(n, i))

def buy(beli, kg):
    harga = buah.get(beli)
    total = harga * kg
    return total

while True:
    print('Menu : ')
    print('A. Tambah data buah')
    print('B. Beli buah')
    print('C. Hapus data buah')
    jawab = None
    while jawab not in('A', 'B', 'C', 'D'):
        jawab = str(input('\nPilihan menu: '))
        if (jawab == "A"):

            tambah = str(input('\nMasukan nama buah : '))
            if tambah in buah.keys():
              print('Nama buah sudah ada dalam data')
            else:
                while True:
                    try:
                        hargaTambah = int(input('Masukan harga satuan : '))
                    except ValueError:
                        print('Input angka saja !')
                        continue
                    else:
                        break
                buah[tambah] = hargaTambah
                print('{0} (Harga Rp {1} ditambahkan)'.format(tambah, hargaTambah))
                print('')
                myData(buah)

        elif(jawab == "B"):
            myData(buah)
            total = 0
            selesai = False
            while not selesai:
                while True:
                    namaBuah = str(input('\nBuah yang akan dibeli : '))
                    if namaBuah not in buah.keys():
                        print('Buah tidak ada')
                        continue
                    else:
                        break
                while True:
                    try:
                        banyak = float(input('Berapa kg : '))
                    except ValueError:
                        print('Input angka saja !')
                        continue
                    else:
                        break

                total = total + buy(namaBuah, banyak)
                jawab = None
                while jawab not in("y", "n"):
                    jawab = str(input('Beli lagi (y/n)? : '))
                    if(jawab == "y"):
                        selesai = False
                        print('')
                    elif(jawab == "n"):
                        selesai = True
                    else:
                        print('Masukan pilihan')
            print('-----------------------------------')
            print('Total harga           : Rp {0}'.format(total))
            print('')
            break
        elif(jawab == "C"):
            myData(buah)
            hapus = str(input('Masukan nama buah yang akan dihapus : '))
            if hapus in buah.keys():
                del buah[hapus]
                print('Buah {0} telah dihapus'.format(hapus))
                print('')
                myData(buah)
        elif(jawab == "D"):
            exit()


with open('drug_name', 'r+', encoding='utf8') as test:
    names = ''
    for line in test:
        name = line.strip()
        names = names + name

    chars = []
    for char in names:
        chars.append(char)
    print('去重前字数：{}'.format(len(chars)))
    result = list(set(chars))
    print('去重后字数：{}'.format(len(result)))
    print(result)
    test.write('\n')
    test.write(str(result))


from torch import tensor

from QNetwork import QNetwork
import random
import torch
import torch.nn.functional as F
import numpy as np
from ReplayBuffer import ReplayBuffer
import os

BATCH_SIZE = 64
GAMMA = 0.99  #
TAU = 1e-3

class Agent:
    def __init__(self, env, action_size, state_size, use_dueling=False,
                 use_double=False, network_file=None):
        self.device = torch.device('cpu')
        self.action_size = action_size
        self.env = env
        self.state_size = state_size
        self.seed = 1234
        self.target_network = QNetwork(state_size=state_size, action_size=action_size, seed=self.seed,
                                       use_dueling=use_dueling).to(self.device)
        self.local_network = QNetwork(state_size=state_size, action_size=action_size, seed=self.seed,
                                      use_dueling=use_dueling).to(self.device)
        self.optimizer = torch.optim.Adam(self.local_network.parameters(), lr=5e-4)

        if network_file is not None:
            if os.path.exists(network_file):
                checkpoints = torch.load(network_file)
                self.local_network.load_state_dict(checkpoints['local'])
                self.target_network.load_state_dict(checkpoints['target'])
                self.optimizer.load_state_dict(checkpoints['optimizer'])

        self.memory = ReplayBuffer(self.seed, batch_size=BATCH_SIZE, device=self.device)
        self.use_double = use_double

    def act(self, state, epsilon):
        if random.random() > epsilon:
            self.local_network.eval()
            state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)
            ans = None
            with torch.no_grad():
                ans = self.local_network.forward(state).cpu().data.numpy()
                ans = np.argmax(ans).astype(int)
            self.local_network.train()
            return ans
        else:
            return random.choice(range(self.action_size))

    def soft_update(self, local_model, target_model):
        for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
            target_param.data.copy_(TAU * local_param.data + (1.0 - TAU) * target_param.data)

    def step(self, timestep, state, next_state, action, reward, done):
        self.memory.add(state, next_state, action, reward, done)

        if timestep % 4 == 0:
            if len(self.memory) >= BATCH_SIZE:
                states, next_states, actions, rewards, dones = self.memory.sample()
                q_target = None
                if not self.use_double:
                    q_target = self.target_network(next_states).detach().max(1)[0].unsqueeze(1)  # need to be fixed
                else:
                    indice = torch.argmax(self.local_network(next_states).detach(), 1)
                    q_target = self.target_network(next_states).detach().gather(1, indice.unsqueeze(1))

                target = rewards + (GAMMA * q_target * (1 - dones))
                q_expected = self.local_network(states).gather(1, actions)
                loss = F.mse_loss(q_expected, target)
                self.optimizer.zero_grad()
                loss.backward()
                self.optimizer.step()
                self.soft_update(self.local_network, self.target_network)


#
# plan class for Gig-o-Matic 2 - links members to gigs
#
# Aaron Oppenheimer
# 24 August 2013
#

import debug
from google.appengine.ext import ndb
from debug import debug_print
import webapp2

import gig
import band
import member
import assoc
import datetime

plan_text = ["No Plan", "Definitely", "Probably", "Don't Know", "Probably Not", "Can't Do It", "Not Interested"]

#
# class for plan
#
class Plan(ndb.Model):
    """ Models a gig-o-matic plan """
    member = ndb.KeyProperty()
    value = ndb.IntegerProperty()
    feedback_value = ndb.IntegerProperty()
    comment = ndb.StringProperty(indexed=False)
    section = ndb.KeyProperty()
    last_update = ndb.DateTimeProperty(auto_now=True)

    @classmethod
    def lquery(cls, *args, **kwargs):
        if debug.DEBUG:
            print('{0} query'.format(cls.__name__))
        return cls.query(*args, **kwargs)

    def set_comment(self, the_comment):
        self.comment=the_comment;
        self.put()

def new_plan(the_gig, the_member, value):
    """ associate a gig and a member """
    the_plan = Plan(parent=the_gig.key, member=the_member.key, value=value, comment="", section=None)
    the_plan.put()
    return the_plan

def get_plan_from_id(the_gig, id):
    """ Return plan object by id; needs the key for the parent, which is the band for this plan"""
    return Plan.get_by_id(int(id), parent=the_gig.key)

def get_plan_keys_for_gig_key(the_gig_key):
    """ Return plan objects by gig"""
    plan_query = Plan.lquery(ancestor=the_gig_key)
    plan_keys = plan_query.fetch(keys_only=True)
    return plan_keys

def get_plan_for_member_key_for_gig_key(the_member_key, the_gig_key):
    plan_query = Plan.lquery(Plan.member==the_member_key, ancestor=the_gig_key)
    plans = plan_query.fetch()
    if len(plans)>1:
        return None #todo what to do if there's more than one plan
    if len(plans)>0:
        return plans[0]
    else:
        # no plan? make a new one
        return new_plan(the_gig_key.get(), the_member_key.get(), 0)

def get_plan_for_member_for_gig(the_member, the_gig):
    return get_plan_for_member_key_for_gig_key(the_member_key=the_member.key, the_gig_key=the_gig.key)

def get_recent_changes_for_band_key(the_band_key, the_time_delta_days=1, keys_only=False):
    "find plans for gigs belonging to a band key that have changed lately"
    plan_query = Plan.lquery(Plan.last_update>(datetime.datetime.now() - datetime.timedelta(days=the_time_delta_days)), ancestor=the_band_key)
    plans = plan_query.fetch(keys_only=keys_only)
    return plans

def update_plan(the_plan, the_value):
    the_plan.value=the_value
    the_plan.put()

def update_plan_feedback(the_plan, the_value):
    the_plan.feedback_value=the_value
    the_plan.put()

def update_plan_comment(the_plan, the_value):
    the_plan.comment=the_value
    the_plan.put()

def update_plan_section_key(the_plan, the_section_key):
    the_plan.section=the_section_key
    the_plan.put()

def remove_section_from_plans(the_section_key):
    """ if any plans have this section key, set the section to None """
    plan_query = Plan.lquery(Plan.section==the_section_key)
    the_plans = plan_query.fetch()
    for the_plan in the_plans:
        the_plan.section=None
    ndb.put_multi(the_plans)

def delete_plans_for_gig_key(the_gig_key):
    """ A gig is being deleted, so forget everyone's plans about it """
    plan_query = Plan.lquery(ancestor=the_gig_key)
    the_plan_keys = plan_query.fetch(keys_only=True)
    ndb.delete_multi(the_plan_keys)

def delete_plans_for_member_key_for_band_key(the_member_key, the_band_key):
    """ A gig is being deleted, so forget everyone's plans about it """
    plan_query = Plan.lquery(Plan.member==the_member_key, ancestor=the_band_key)
    plans = plan_query.fetch(keys_only=True)
    ndb.delete_multi(plans)

class UpdatePlan(webapp2.RequestHandler):
    def post(self):
        """post handler - if we are edited by the template, handle it here and redirect back to info page"""
        the_value=int(self.request.get("val", 0))
        the_plan_key=self.request.get("pk",'0')

        if (the_plan_key=='0'):
            return #todo figure out what to do if no plan passed in

        the_plan=ndb.Key(urlsafe=the_plan_key).get()

        if (the_plan is not None):
            update_plan(the_plan, the_value)
        else:
            pass # todo figure out why there was no plan

class UpdatePlanFeedback(webapp2.RequestHandler):
    def post(self):
        """post handler - if we are edited by the template, handle it here and redirect back to info page"""
        the_value=int(self.request.get("val", 0))
        the_plan_key=self.request.get("pk",'0')

        if (the_plan_key=='0'):
            return #todo figure out what to do if no plan passed in

        the_plan=ndb.Key(urlsafe=the_plan_key).get()

        if (the_plan is not None):
            update_plan_feedback(the_plan, the_value)
        else:
            pass # todo figure out why there was no plan

        strings = band.get_feedback_strings(the_plan.key.parent().parent().get())

        if the_value == 0:
            resp = ''
        elif the_value <= len(strings):
            resp = strings[the_value-1]
        self.response.write(resp)

class UpdatePlanComment(webapp2.RequestHandler):
    def post(self):
        """post handler - if a comment is edited, update the database"""

        the_value=self.request.get("value", "")
        the_plan_key=self.request.get("pk",'0')

        if (the_plan_key=='0'):
            return #todo figure out what to do if no plan passed in

        the_plan=ndb.Key(urlsafe=the_plan_key).get()

        if (the_plan is not None):
            update_plan_comment(the_plan, the_value)
        else:
            pass # todo figure out why there was no plan

class UpdatePlanSection(webapp2.RequestHandler):
    def post(self):
        """post handler - if a section is edited, update the database"""

        the_section_keyurl=self.request.get("sk", '0')
        the_plan_keyurl=self.request.get("pk",'0')

        if (the_plan_keyurl=='0' or the_section_keyurl=='0'):
            return #todo figure out what to do if no plan passed in

        the_plan=ndb.Key(urlsafe=the_plan_keyurl).get()
        the_section_key=ndb.Key(urlsafe=the_section_keyurl)

        if (the_plan is not None):
            update_plan_section_key(the_plan, the_section_key)
        else:
            pass # todo figure out why there was no plan


"""Preference management for camera component."""
from __future__ import annotations

from typing import Final

from homeassistant.core import HomeAssistant
from homeassistant.helpers.typing import UNDEFINED, UndefinedType

from .const import DOMAIN, PREF_PRELOAD_STREAM

STORAGE_KEY: Final = DOMAIN
STORAGE_VERSION: Final = 1

class CameraEntityPreferences:
    """Handle preferences for camera entity."""

    def __init__(self, prefs: dict[str, bool]) -> None:
        """Initialize prefs."""
        self._prefs = prefs

    def as_dict(self) -> dict[str, bool]:
        """Return dictionary version."""
        return self._prefs

    @property
    def preload_stream(self) -> bool:
        """Return if stream is loaded on hass start."""
        return self._prefs.get(PREF_PRELOAD_STREAM, False)

class CameraPreferences:
    """Handle camera preferences."""

    def __init__(self, hass: HomeAssistant) -> None:
        """Initialize camera prefs."""
        self._hass = hass
        self._store = hass.helpers.storage.Store(STORAGE_VERSION, STORAGE_KEY)
        self._prefs: dict[str, dict[str, bool]] | None = None

    async def async_initialize(self) -> None:
        """Finish initializing the preferences."""
        prefs = await self._store.async_load()

        if prefs is None:
            prefs = {}

        self._prefs = prefs

    async def async_update(
        self,
        entity_id: str,
        *,
        preload_stream: bool | UndefinedType = UNDEFINED,
        stream_options: dict[str, str] | UndefinedType = UNDEFINED,
    ) -> None:
        """Update camera preferences."""
        # Prefs already initialized.
        assert self._prefs is not None
        if not self._prefs.get(entity_id):
            self._prefs[entity_id] = {}

        for key, value in ((PREF_PRELOAD_STREAM, preload_stream),):
            if value is not UNDEFINED:
                self._prefs[entity_id][key] = value

        await self._store.async_save(self._prefs)

    def get(self, entity_id: str) -> CameraEntityPreferences:
        """Get preferences for an entity."""
        # Prefs are already initialized.
        assert self._prefs is not None
        return CameraEntityPreferences(self._prefs.get(entity_id, {}))


# Copyright (c) 2016-present, Facebook, Inc.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.

import os
import unittest
from unittest.mock import (
    call,
    patch,
)

from ... import (
    commands,
    log,
)
from ...commands import initialize
from .command_test import (
    mock_arguments,
    mock_configuration,
)

class InitializeTest(unittest.TestCase):
    @patch.object(log, 'get_yes_no_input', return_value=True)
    @patch.object(log, 'get_input', return_value='')
    @patch('os.path.isfile')
    @patch('subprocess.call')
    @patch('builtins.open')
    def test_initialize(
            self,
            mock_open,
            subprocess_call,
            isfile,
            _get_input,
            get_yes_no_input):
        get_yes_no_input.return_value = True
        arguments = mock_arguments()
        configuration = mock_configuration()

        def exists(path):
            if path.endswith(".watchmanconfig"):
                return False
            elif path.endswith(".pyre_configuration"):
                return False
            else:
                return True

        isfile.side_effect = exists
        with patch.object(commands.Command, '_call_client'):
            initialize.Initialize(
                arguments,
                configuration,
                source_directory='.').run()
            subprocess_call.assert_has_calls([
                call(["watchman", "watch-project", "."]),
            ])
            mock_open.assert_any_call(os.path.abspath(".watchmanconfig"), "w+")


from django.urls import path
from django.conf.urls import url
from . import views
app_name='myApp'
urlpatterns = [
    path('',views.index,name='index'),
    # path('Students/',views.student),
    # path('Greades/',views.greade),
    # #url可以用正则表达式
    # url(r'Greades/(\d+)\/$',views.gradestudent),
    # #在模型中添加数据
    # path('addstudent/',views.creadstudent),
    # #在控制器中添加数据
    # path('addstudent2/',views.creadstudent2),
    # #查询数据分页
    # url(r'stu/(\d+)\/$',views.stu),
    path('main/',views.main,name='shou'),
    path('login/',views.login,name='xiang'),
    path('show/',views.show,name='xianshi'),
    path('quit/',views.quit,name='tui'),
    path('varimage/',views.varcod,name='image'),
    path('fileimage/',views.file,name='files'),
    path('ajaxstudent/',views.ajaxstudents),
    path('ajaxstudent/studentsinfo/',views.studentsinfo,name='ajax'),
    path('fufu/',views.fufu,name='fuwenben'),
    path('savefufu/',views.savefufu,name='savefu'),

]


# COPYRIGHT: see https://github.com/x19290/py.lisp4u/blob/master/0rights.md

from write_to import WriteTo

class Lisp(WriteTo):
    null = None  # to silent PyDev.

    def cons(self, car):
        return self.cons_ctor()(car, self)

    @classmethod
    def cons_ctor(cls):
        from .pair import Pair
        return Pair

    @staticmethod
    def pay_attention_to_the_ending_quote(params):
        iparams = iter(params)
        from ..globals.known import quote
        from .support.null_gen import NotNull
        from .pair import Pair
        from itertools import islice
        for y in iparams:
            if y is quote:
                ahead = tuple(islice(iparams, 2))
                if ahead.__len__() == 1:
                    raise NotNull(Pair.list(quote, ahead[0]))
                yield y
                for yy in ahead:
                    yield yy
                break
            else:
                yield y

del WriteTo


import wikipedia as wiki
import pandas as pd
import os

GENRE_TYPES = 'Talk-Show|News'
TITLE_TYPE = 'tvSeries'
PROFESSION_TYPES =  [' host',' presenter',' journalist',' news anchor','correspondent',' anchor']
SPLIT_TYPES = [' is a ',' is an ',' was a ',' was an ',' is the ']
NONE = 'Not Found'
PAGE_ERROR = 'does not match any pages'
DISAMBIGUATION_ERROR = 'disambiguation'
NETWORK_TYPES = ['FOX','ABC','CBS','NBC','CNN','United Paramount Net','Warner Bros.','Pure Independent','PBS','Pax TV','Telemundo']
REGION_TYPE = 'US'
SHOW_NOT_IN_IMDB = 'Show is not present in IMDb'
NAME_BASICS = "IMDB_Datasets/name.basics.tsv/data.tsv"
TITLE_BASICS = "IMDB_Datasets/title.basics.tsv/data.tsv"
TITLE_PRINCIPALS = "IMDB_Datasets/title.principals.tsv/data.tsv"
TITLE_AKAS = "IMDB_Datasets/title.akas.tsv/data.tsv"
TITLE_CREW = "IMDB_Datasets/title.crew.tsv/data.tsv "
Read_Namebasics = pd.read_table(NAME_BASICS, sep='\t')

""" After getting all professions of a person we can easily confirm that
    our previous top 5 prediction is right or not & by using this we find
    correct anchor.
"""

def get_wiki_professions(Anchor_Name):

  if len(wiki.search(Anchor_Name)) == 0:
    return NONE

  Store_name = Read_Namebasics.primaryName.tolist()

  try:
    if Anchor_Name in Store_name:
      anchor_content = (((wiki.page(Anchor_Name,auto_suggest=False)).content).replace(' and ',', ').replace('.','. '))
    else:
      return NONE

  except wiki.exceptions.PageError as p:
    if PAGE_ERROR in str(p):
      return NONE

  except wiki.exceptions.DisambiguationError as e:
    if Anchor_Name in Store_name:
      list_disambiguation_error = e.options

      for i in list_disambiguation_error:
        if i.find(DISAMBIGUATION_ERROR)!= -1:
          return NONE

        anchor_content = (((wiki.page(i,auto_suggest=False)).content).replace(' and ',', ').replace('.','. '))
        split_type_list = []
        prefix = None
        for x in SPLIT_TYPES:
          if x in anchor_content:
            prefix = x
            split_type_index = anchor_content.find(prefix)
            split_type_list.append(split_type_index)
          else:
            split_type_list.append(1000)

        if prefix is None:
          return NONE

        low_index = SPLIT_TYPES[split_type_list.index(min(split_type_list))]
        final_split = anchor_content.split(low_index)[1].split('. ')[0].split(', ')
        final_professions = [anchor_content.lower() for anchor_content in final_split]
        required_professions = PROFESSION_TYPES

        check_individual_prof = []
        for x in required_professions:
          final_check= [(x in y) for y in final_professions]
          check_individual_prof.append(any(final_check))

        if (any(check_individual_prof)==True):
          return final_professions
      else:
        return NONE

    else:
      return NONE

  split_type_list = []
  prefix = None
  for x in SPLIT_TYPES:
    if x in anchor_content:
      prefix = x
      split_type_index = anchor_content.find(prefix)
      split_type_list.append(split_type_index)
    else:
      split_type_list.append(1000)

  low_index = SPLIT_TYPES[split_type_list.index(min(split_type_list))]

  if prefix is None:
    return NONE

  final_split = anchor_content.split(low_index)[1].split('. ')[0].split(', ')
  final_professions = [anchor_content.lower() for anchor_content in final_split]
  return final_professions

def check_wiki_professions(list_profession):
  required_professions = PROFESSION_TYPES

  check_individual_prof = []
  for x in required_professions:
    final_check= [(x in y) for y in list_profession]
    check_individual_prof.append(any(final_check))

  if (any(check_individual_prof)==True):
    return True
  else:
    return False

"""  From top 5 anchor we get most probable anchor in that show
     Make sure that the input anchors list follows given format. Here's an example
     Anchor_list = "Colleen-Williams_Ashwini-Bhave_Elaine-Quijano_Becky-Hobbs_Heidi-Collins"
"""
def get_correct_anchor(top_5):
  top_5_list = (top_5.replace('-',' ').replace('_',',')).split(',')
  top_5_list = list(filter(None, top_5_list))

  for x in top_5_list:
    if check_wiki_professions(get_wiki_professions(x)) is True:
      Read_Namebasics = pd.read_table(NAME_BASICS, sep='\t')
      Store_name = Read_Namebasics.primaryName.tolist()
      if x in Store_name:
        return x

  return ''

## get finals anchors from the multiple probable hosts

def Final_Anchor(last_line):
  filter_probable_list = []

  ## Here all_lines[len(all_lines)-1] == put from last year code

  last_line_anchors = last_line.split('ANC|')[1].split('\n')[0].replace(' ','')

  # print(last_line)
  avoid_num = ''.join([i for i in last_line_anchors if not i.isdigit()])
  probable_host_list = avoid_num.split('probable_host:')
  probable_host_list = list(filter(None, probable_host_list))

  # print(probable_host_list)

  for i in probable_host_list:
    filter_probable_list.append(get_correct_anchor(i))
    filter_probable_list = list(filter(None, filter_probable_list))
  return filter_probable_list

#this will give us network name either from anchor or show

def get_channel(name):
  try:
    anchor_content = ((((wiki.page(name,auto_suggest=False)).content).replace(' and ',', ').replace('.','. ')))

  except wiki.exceptions.PageError as p:
    if PAGE_ERROR in str(p):
      return NONE

  except wiki.exceptions.DisambiguationError as e:
    list_disambiguation_error = e.options
    for anchor_name in list_disambiguation_error:
      if anchor_name.find(DISAMBIGUATION_ERROR)!= -1:
        return NONE

      else:
        anchor_content = ((((wiki.page(anchor_name,auto_suggest=False)).content).replace(' and ',', ').replace('.','. ')))

  Networks_list = NETWORK_TYPES
  Network_filter = []

  for network in Networks_list:
    if anchor_content.find(network)!=-1:
      Network_filter.append(network)
  return Network_filter

def get_majority_network(anchors_list):
  list_of_network = []
  for anchorlist in anchors_list:
    for anchor in anchorlist:
      list_of_network.append(get_channel(anchor))
  list_of_network = list(filter(None,list_of_network))
  # print(list_of_network)

  X ={} #dict contains networks and respected votes
  for network in list_of_network:
    for particular in network:
      if particular in X:
        X[particular] +=1
      else:
        X[particular] = 1
  Max_votes = max(X.values())
  Majority_Network = [particular for particular, votes in X.items() if votes == Max_votes]
  return Majority_Network


from flask import Blueprint, redirect, render_template, request, url_for, flash
from Blog import db
from flask_login import login_required
from Blog.post.forms import PostForm
from flask_login import current_user
from Blog.post.models import Posts

post = Blueprint('post', __name__)

@post.route('/post/new', methods = ['GET', 'POST'])
@login_required
def new_post():
    form = PostForm()
    if form.validate_on_submit():
        post = Posts(title = form.title.data, content = form.content.data, author = current_user)
        db.session.add(post)
        db.session.commit()
        flash('Your post has been created!', 'success')
        return redirect(url_for('main.home'))
    return render_template('create_post.html', title="New Post",  form=form, legend = 'New Post')

@post.route('/post/<int:post_id>')
def post_detail(post_id):
    post = Posts.query.get_or_404(post_id)
    return render_template('post.html', titile = post.title, post = post)

@post.route('/post/<int:post_id>/delete', methods = ['POST'])
def delete_post(post_id):
    post = Posts.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    db.session.delete(post)
    db.session.commit()
    flash('Your post has been deleted!', 'success')
    return redirect(url_for('main.home'))

@post.route('/post/<int:post_id>/update', methods = ['GET', 'POST'])
@login_required
def update_post(post_id):
    post = Posts.query.get_or_404(post_id)
    if post.author != current_user:
        abort(403)
    form = PostForm()
    if form.validate_on_submit():
        post.title = form.title.data
        post.content = form.content.data
        db.session.commit()
        flash('Your post has been updated!', 'success')
        return redirect(url_for('post.post_detail', post_id = post.id))
    elif request.method == 'GET':
        form.title.data = post.title
        form.content.data = post.content
    return render_template('create_post.html', title = 'Update Post', form = form, legend = 'Update Post')


import pygame

def load_image(name):
    fullname = '/'.join(['./data', name])
    image = pygame.image.load(fullname)
    image = image.convert_alpha()
    return image

def create_img(name, r):
    if name == 'Earth':
        clr = 'green'
    elif name == 'Solar':
        clr = 'yellow'
    elif name == 'Moon':
        clr = 'white'
    else:
        clr = 'cyan'
    image = pygame.Surface((2 * r, 2 * r))
    pygame.draw.circle(image, pygame.Color(clr), (r, r), r)
    return image

def create_screen(text):
    w = 1200
    h = 800
    image = pygame.Surface((w, h))
    image.fill((0, 0, 128))
    font = pygame.font.Font(None, 60)
    text_render = font.render(text, 1, pygame.Color('white'))
    text_rect = text_render.get_rect()
    text_rect.x = w//2 - text_rect.width // 2
    text_rect.y = h//2 - text_rect.height // 2
    image.blit(text_render, text_rect)
    return image


import Log
import sys

module_obj = sys.modules[__name__]
loggername = "WiiHandler"
LogClass = Log.getLogClass(label = loggername)
logclass = LogClass()
#logclass.set_child(PAUCommLib.logger.logclass)
#logclass.set_child(DataWidget.logger.logclass)
setattr(module_obj,'log',logclass.log)
#setattr(module_obj,'init_log',logclass.init_log)
#setattr(module_obj,'add_socket_handler',logclass.add_socket_handler)