# External imports
import datetime
import pytz
import time

# Internal imports
from soup import Soup, SoupParser
from game import GameState
from lines import LineGenerator

class Scraper:

    # Key assumptions:
    # 1) Games can't move backward in time.
    #        If we have a in-memory game object that is final and we get a new
    #        game state with a matching id prefix, then we must assume the new
    #        soup corresponds to a new, different game, double header scenario.
    # 2) Games can't have multiple start times.
    #        If we have a in-memory game object that has a different start time
    #        than a game update with the same game id prefix, then we must have
    #        a new game, double header scenario.
    # 3) Two games with the same id prefix can't be live at the same time.
    #        Double headers can not be concurrent, this would not make sense.
    #        Therefore, if we have a live game update with a prefix that matches
    #        multiple game ids, then it should be applied to the game that's
    #        active.
    # 4) The same game can not be updated more than once per iteration. This is
    #        a safe assumption as its unlikely for the same game to be scraped twice
    #        off the mlb.com website. And it helps resolve some double-header edge
    #        cases.

    def __init__(self, alerter):
        # Issue alerts
        self.alerter = alerter
        #
        # Game states
        # Games should transition from: pregame -> live -> final
        # They can not go backward.
        #
        # Maps: Game ID (str) -> GameState
        self.games = {
                        'pregame': {},
                        'live': {},
                        'final': {}
                     }
        # Set of ids for games that have been updated this iteration.
        self.updated = set()

    # This function prints the given message to the console
    # and issues an alert.
    def notify(self, message):
        print(message)
        self.alerter.alert(message)

    # The lookup functions take a game prefix and match it to a game in the
    # games dictionary, or constructs a new game if a match is not found.
    #
    # Returns the GameState for the given prefix.

    # Looks up prefix in a given games dictionary
    # bucket in the set('pregame', 'live', 'final')
    def match(self, bucket, prefix):
        return [id for id in self.games[bucket].keys() if id[:-1] == prefix]

    # Lookup live games that match the prefix.
    def lookup_live(self, prefix):
        # First, check if the prefix matches a game in the live game hash.
        live_matches = self.match('live', prefix)
        if live_matches:
            # If we have a match then return the GameState.
            assert(len(live_matches) == 1) # Assumption 3
            assert(not live_matches[0] in self.updated) # Assumption 4
            return self.games['live'][live_matches[0]]
        # Second check if the prefix matches a game in the pregame hash.
        pregame_matches = self.match('pregame', prefix)
        if pregame_matches:
            # If we have multiple matches then take the game with the earliest
            # start time.
            return sorted([self.games['pregame'][id] for id in pregame_matches],
                           key=lambda game: game.start_time)[0]
        # Else, we need to create a new game
        id = GameState.new_game_id(prefix)
        self.notify(f'CREATING NEW LIVE GAME {id}')
        self.games['live'][id] = GameState(id)
        return self.games['live'][id]

    # Lookup games in the pregame hash.
    #
    # NOTE - Need to fix the edge case where a double header is created
    #        in a single iteration, and the second game has a delayed start.
    #        Currently, we would change the first game's start time to the second
    #        start time, then upon the second iteration we would create another GameState
    #        for the first game but incorrectly assign it the '1' id suffix.
    #
    def lookup_pregames(self, prefix, start, delayed):
        # Check for prefix matches in the pregame hash.
        prefix_matches = self.match('pregame', prefix)
        # If we have prefix matches...
        if prefix_matches:
            # Get the game with the matching start time.
            candidate = [id for id in prefix_matches
                            if self.games['pregame'][id].start_time == start]
            # If we don't have a matching start time and the game's start time has
            # been delayed, then we update the game with the matching prefix's start time.
            #
            # Note: if there are multiple games with a matching prefix, then we choose the
            #       game with the closest start time before the new start time.
            #       (This assumes game times can't be moved forward which might not be true)
            #
            # Fix: Enforce the rule that a game can only be updated once per iteration.
            #      Therefore, if we see the second game in a double header that's been delayed,
            #      then we know to create a new game.
            if (not candidate) and delayed:
                valid_games = [id for id in prefix_matches if not id in self.updated]
                candidate = [min(valid_games,
                                 key=lambda id: abs(start-self.games['pregame'][id].start_time))]
            assert(len(candidate) <= 1) # Match should be unique (or zero).
            if candidate and not candidate[0] in self.updated:
                return self.games['pregame'][candidate[0]]
        # Else, if we have no prefix + start time matches, then make a new game.
        id = GameState.new_game_id(prefix)
        self.notify(f'CREATING NEW PREGAME {id}')
        self.games['pregame'][id] = GameState(id)
        return self.games['pregame'][id]

    # Lookup games in the final hash.
    def lookup_final(self, prefix):
        # First, check for prefix matches in the final hash.
        final_matches = self.match('final', prefix)
        # We can have multiple matches here if both games of a double header have
        # concluded. It doesn't matter, so we return the first game in the
        # match list.
        if final_matches:
            return self.games['final'][final_matches[0]]
        # Second, check for live games that may have finished.
        live_matches = self.match('live', prefix)
        # Live game prefixes must be unique.
        # We can't have the same team playing two games at the same time.
        if live_matches:
            assert(len(live_matches) == 1)
            return self.games['live'][live_matches[0]]
        # Third, check pregames hash.
        # This should be rare.
        pre_matches = self.match('pregame', prefix)
        # There is some ambiguity here which game to use since we don't have
        # start time in a final game soup, so we take the game with the
        # earliest start time.
        if pre_matches:
            return sorted([self.games['pregame'][id] for id in pre_matches],
                        key=lambda g: g.start_time)[0]
        # Else, we create a new game.
        id = GameState.new_game_id(prefix)
        self.notify(f'CREATING NEW FINAL GAME {id}')
        self.games['final'][id] = GameState(id)
        return self.games['final'][id]

    # Move the game with id from 'from' to 'to'.
    allowed_txn = set((('pregame', 'live'),
                       ('live', 'final'),
                       ('pregame', 'final')))
    def transition(self, id, orig, dest):
        # Check that the given states are valid
        assert(orig in self.games.keys() and dest in self.games.keys())
        # Check that the transition is allowed.
        assert((orig, dest) in Scraper.allowed_txn)
        # Check that a game with the same id isn't in our destination state.
        assert(not id in self.games[dest].keys())
        # Move the game
        self.games[dest][id] = self.games[orig][id]
        del self.games[orig][id]

    # Returns the time until the next game starts in seconds.
    # With a 30 min buffer for late start games, in which case 30 secs is returned.
    def time_until_next_game(self, lines):
        # Get the current time, in eastern timezone.
        nowtime = datetime.datetime.now().astimezone(pytz.timezone('US/Eastern'))
        # Get the next game start time, in eastern timezone, filtered s.t. we exclude games
        # that have already started.
        # Note: Give a 30min buffer for games that start later than their listed start time.
        gametime = min([start_time for start_time, _ in lines.values() if
                            start_time > nowtime-datetime.timedelta(minutes=30)])
        # Calculate the difference in seconds.
        secs = (gametime - nowtime).total_seconds()
        # If a game is starting later than its listed time then secs will be negative.
        # Instead, we want to wait thirty seconds.
        return secs if secs > 0 else 30

    def scrape(self, game_outpath, line_outpath, keyfile):
        webpage = Soup()
        linegen = LineGenerator(keyfile, GameState.get_id_prefix)
        while True:
            print(f"---> {datetime.date.today()} {datetime.datetime.now().strftime('%H:%M:%S')}")

            # Time the soup was brewed and lines were generated.
            timestamp = datetime.datetime.now()
            # Get current lines.
            lines = linegen.get_lines()

            # Initialize updated set to empty at the start of an iteration.
            self.updated = set()

            # Each game has its own soup that we must process.
            for soup in webpage.brew():
                # Get the game id prefix for the game soup
                teams = SoupParser.get_teams(soup)
                prefix = GameState.get_id_prefix(teams[1])
                print('Teams:', teams, ' Prefix:', prefix)
                #
                # Parse warmup games
                if SoupParser.is_warmup(soup):
                    continue # Skip warmup games
                #
                # Parse live game update
                elif SoupParser.is_live(soup):
                    # Find the GameState for the corresponding prefix
                    game = self.lookup_live(prefix)
                    # Transition the game from pregame to live, if needed.
                    if game.id in self.games['pregame'].keys():
                        self.notify(f'TRANSITIONING {game.id} from pregame to live')
                        self.transition(game.id, 'pregame', 'live')
                    # Update game state
                    game.update(timestamp,
                                SoupParser.parse_live(soup),
                                lines.get(prefix, (None, None))[1])
                    # Add to updated set.
                    self.updated.add(game.id)
                    # Dump game state and line info
                    game.dump_state(game_outpath)
                    if not game.line_info is None:
                        game.dump_lines(line_outpath)
                    # Log
                    print('---------------------------------------------------')
                    print(game)
                    print()
                #
                # Parse pre game info
                elif SoupParser.is_pregame(soup):
                    # Find the GameState for the corresponding prefix.
                    # Account for a change in start time for delayed games.
                    start_time = SoupParser.get_start_time(soup)
                    game = self.lookup_pregames(prefix, start_time, SoupParser.is_delayed(soup))
                    # Set start time if its not already set.
                    if not game.start_time:
                        game.start_time = start_time
                    # Add to updated set.
                    self.updated.add(game.id)
                #
                # Parse post game or postponed game info.
                elif (SoupParser.is_final(soup) or
                      SoupParser.is_postponed(soup) or
                      SoupParser.is_suspended(soup)):
                    # Find the GameState for the corresponding prefix
                    game = self.lookup_final(prefix)
                    # Notify if a live game is postponed or suspended.
                    if game.id in self.games['live'].keys() and SoupParser.is_postponed(soup):
                        self.notify(f'POSTPONED {game.id}')
                    if game.id in self.games['live'].keys() and SoupParser.is_suspended(soup):
                        self.notify(f'SUSPENDED {game.id}')
                    # Move the game to the final hash, if needed.
                    if game.id in self.games['pregame'].keys():
                        self.notify(f'TRANSITIONING {game.id} from pregame to final')
                        self.transition(game.id, 'pregame', 'final')
                    elif game.id in self.games['live'].keys():
                        self.notify(f'TRANSITIONING {game.id} from live to final')
                        self.transition(game.id, 'live', 'final')
                    # Add to updated set
                    self.updated.add(game.id)
                else:
                    self.notify('WARNING: Couldnt identify the game soup.')

            # Print line API usage statistics
            stats = linegen.usage()
            print('Remaining:', stats[0], ' Used:', stats[1])

            # Check for stale live games.
            for game in self.games['live'].values():
                # If a game in the live bucket hasn't been updated in a hour, then issue an alert.
                if (datetime.datetime.now() - game.timestamp).total_seconds() > 3600:
                    self.notify(f"WARNING: {game.id} hasnt been updated in over an hour")
                # If a game in the live bucket hasn't been updated in 5 hours, then drop it to the final bucket.
                if (datetime.datetime.now() - game.timestamp).total_seconds() > 5*3600:
                    self.notify(f"""WARNING: {game.id} hasn't been updated in 5 hours.\n
                                    Transitioning from live to final.""")
                    self.transition(game.id, 'live', 'final')

            # Determine wait time.
            # If we don't have a current game going, then wait for the next to start or wait two hours.
            if not self.games['live']:
                wait_time = min(self.time_until_next_game(lines), 2*60*60)
                wakeup_time = datetime.datetime.now() + datetime.timedelta(seconds=wait_time)
                self.notify(f"""No live games, sleeping {wait_time} seconds.\nWakeup time at {wakeup_time.strftime('%Y-%m-%d %H:%M:%S')}""")
            # Else, pause for a minute, then continue scraping.
            else:
                wait_time = 60
            # Sleep
            time.sleep(wait_time)


import logging as log
import time

import streamlit as st
from screens import display_upload_screen, display_download_screen
import json
import numpy as np
from common.utils import (
    rabbit_connect_and_make_channel,
    is_production,
    pg_connect_and_make_cursor,
    insert_into_sessions,
    insert_into_scheduled_images,
    any_image_ready_to_download,
    select_images_to_download,
)
import uuid

if 'rabbitmq_channel' not in st.session_state:
    connection, channel = rabbit_connect_and_make_channel()
    channel.queue_declare(queue='nst_to_be_process')

    st.session_state['rabbitmq_channel'] = channel
else:
    channel = st.session_state['rabbitmq_channel']

if 'psql_connection' not in st.session_state:
    pg_connection, pg_cursor = pg_connect_and_make_cursor()

    st.session_state['psql_connection'] = {
        'cursor': pg_cursor,
        'conn': pg_connection,
    }

PG_CURSOR = st.session_state['psql_connection']['cursor']

if 'uuid' not in st.session_state:
    uuid = str(uuid.uuid4())
    st.session_state['uuid'] = uuid
    insert_into_sessions(PG_CURSOR, uuid, 'user')

def hideAdminHamburgerMenu():
    st.markdown(""" <style>
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    </style> """, unsafe_allow_html=True)

def add_to_process_queue(content_image, style_image):
    scheduled_image_id = insert_into_scheduled_images(PG_CURSOR, content_image, style_image, st.session_state['uuid'])
    body = json.dumps({
        'scheduled_image_id': scheduled_image_id,
    })
    channel.basic_publish(exchange='',
                          routing_key='nst_to_be_process',
                          body=body)
    log.info('published')

def main():
    st.set_page_config(page_title='Umění pomocí umělé inteligence', page_icon=None, initial_sidebar_state='collapsed')  # we could add one
    st.header('Umění pomocí umělé inteligence')

    if is_production():
        hideAdminHamburgerMenu()

    st.sidebar.title("Menu")
    st.sidebar.info("Po výběru zavřete Menu křížkem.")

    if st.sidebar.button("Nahrání dalšího obrázku"):
        st.session_state['state'] = 'upload'

    if st.sidebar.button("Stahování"):
        st.session_state['state'] = 'download'

    if 'state' not in st.session_state:
        st.session_state['state'] = 'upload'

    if st.session_state['state'] == 'wait':
        message_placeholder = st.empty()
        message_placeholder.success('Vybrané obrázky byly přidány do zpracování. Nyní sledujte prezentaci.')

        if st.button("Nahrát další obrázek"):
            st.session_state['state'] = 'upload'
            st.experimental_rerun()

        if 'image_generated' not in st.session_state:
            if any_image_ready_to_download(PG_CURSOR, st.session_state['uuid']):
                message_placeholder.info(
                    'Obrázek je dostupný ke stažení po kliknutí na ">" v levém horním rohu a "Stahování".'
                )
                st.snow()
                st.session_state['image_generated'] = True
            else:
                st.experimental_rerun()

    elif st.session_state['state'] == 'upload':
        images = display_upload_screen()
        if images is not None:
            log.info('images uploaded')
            content_image, style_image = images
            if content_image is not None and style_image is not None:
                add_to_process_queue(content_image, style_image)
                st.session_state['state'] = 'wait'
                st.experimental_rerun()

    elif st.session_state['state'] == 'download':
        images = select_images_to_download(PG_CURSOR, st.session_state['uuid'])
        if len(images) == 0:
            st.info('Zatím nejsou dostupné žádné obrázky ke stažení.')
            st.text("")
            if st.button('Nahrát obrázek'):
                st.session_state['state'] = 'upload'
                st.experimental_rerun()
        else:
            display_download_screen(images)

if __name__ == '__main__':
    log.info('starting')
    main()
    log.info('quitting...')


from tkinter import *
import math

# ---------------------------- MY CONSTANTS ------------------------------- #
PINK = "#e2979c"
RED = "#e7305b"
GREEN = "#9bdeac"
YELLOW = "#f7f5dd"
FONT_NAME = "Courier"
WORK_MIN = 25
SHORT_BREAK_MIN = 5
LONG_BREAK_MIN = 20
laps = 0
timer = None

# ---------------------------- TIMER RESET ------------------------------- #
def reset_the_time():
    window.after_cancel(timer)
    canvas.itemconfig(timer_text, text="00:00")
    timer_id_label.config(text="Timer")
    check_marks.config(text="")
    global laps
    laps = 0

# ---------------------------- TIMER MECHANISM ------------------------------- #

def start_timer():
    global laps
    laps += 1

    work_sec = WORK_MIN * 60
    short_break_sec = SHORT_BREAK_MIN * 60
    long_break_sec = LONG_BREAK_MIN * 60

    if laps % 8 == 0:
        count_down(long_break_sec)
        timer_id_label.config(text="Long Break", fg=RED)
    elif laps % 2 == 0:
        count_down(short_break_sec)
        timer_id_label.config(text="Short Break", fg=PINK)
    else:
        count_down(work_sec)
        timer_id_label.config(text="Work", fg=GREEN)

# ---------------------------- COUNTDOWN MECHANISM ------------------------------- #
def count_down(count):
    count_min = math.floor(count / 60)
    count_sec = count % 60
    if count_sec < 10:
        count_sec = f"0{count_sec}"

    canvas.itemconfig(timer_text, text=f"{count_min}:{count_sec}")
    if count > 0:
        global timer
        timer = window.after(1000, count_down, count - 1)
    else:
        start_timer()
        c_marks = ""
        working_sessions = math.floor(laps/2)
        for _ in range(working_sessions):
            c_marks += "✔"
        check_marks.config(text=c_marks)

# ---------------------------- UI SETUP ------------------------------- #
window = Tk()
window.title("Pomodora")
window.config(padx=105, pady=50, bg=YELLOW)

# create label

timer_id_label = Label(text="Timer", font=(FONT_NAME, 30, "bold"), bg=YELLOW, fg=GREEN)
timer_id_label.grid(row=0, column=1)

# create a canvas widget
canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0)
tomato_img = PhotoImage(file="tomato.png")
canvas.create_image(100, 112, image=tomato_img)
timer_text = canvas.create_text(100, 130, text="00:00", font=(FONT_NAME, 35, "bold"), fill="white")
canvas.grid(row=1, column=1)

# create start button widget
start_button = Button(text="Start", font=(FONT_NAME, 10, "bold"), command=start_timer)
start_button.grid(row=2, column=0)

# create reset button widget
reset_button = Button(text="Reset", font=(FONT_NAME, 10, "bold"), command=reset_the_time)
reset_button.grid(row=2, column=2)

# create a check mark
check_marks = Label(font=(FONT_NAME, 20, "bold"), bg=YELLOW, fg=GREEN)
check_marks.grid(row=3, column=1)

window.mainloop()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
    ]

    operations = [
        migrations.CreateModel(
            name='Author',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('first_name', models.CharField(max_length=25)),
                ('last_name', models.CharField(max_length=50)),
                ('created_at', models.DateTimeField()),
                ('updated_at', models.DateTimeField()),
            ],
            options={
                'db_table': 'authors',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Quote',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('quote', models.TextField()),
                ('created_at', models.DateTimeField()),
                ('updated_at', models.DateTimeField()),
                ('author', models.ForeignKey(to='view_quotes.Author')),
            ],
            options={
                'db_table': 'quotes',
            },
            bases=(models.Model,),
        ),
    ]


from random import randint
random = str(randint(100000000, 999999999))

while True:

    # ESCOLHA DA FUNÇÃO DO PROGRAMA (VALIDAR OU CRIAR CPF):

    choise = input('Você deseja [V]alidar ou [C]riar um CPF? ').lower()

    while choise != 'v' and choise != 'c':
        choise = input('Digite [V] para Validar ou [C] para Criar: ').lower()

    if choise == 'v':
        CPF = input('Digite um CPF: ')
        create_or_validade = 11
    elif choise == 'c':
        CPF = random
        create_or_validade = 9

    # MENSAGEM DE CARACTERES INVÁLIDOS:

    while len(CPF) != create_or_validade:
        print('DIGITE OS 11 NÚMEROS DO CPF!')
        CPF = input('Digite o CPF novamente: ')

    while not CPF.isnumeric():
        print('DIGITE SOMENTE NÚMEROS!')
        CPF = input('Digite o CPF novamente: ')

    # VERIFICAÇÃO DO PRIMEIRO DÍGITO FINAL:

    verify = 10
    add = 0
    digit = [0, 0]

    for x in range(len(CPF)-2):
        ver = int(CPF[x]) * (verify)
        add += ver
        verify -= 1

    digit[0] = 11 - (add % 11)

    if digit[0] > 9:
        digit[0] = 0

    # VERIFICAÇÃO DO SEGUNDO DÍGITO FINAL:

    verify = 11
    add = 0
    ver = 0

    for y in range(len(CPF)-1):
        ver = int(CPF[y]) * (verify)
        add += ver
        verify -= 1

    digit[1] = 11 - (add % 11)

    if digit[1] > 9:
        digit[1] = 0

    # PREPARANDO PARA IMPRESSÃO:

    CPF_print = (f'{CPF[:3]}.{CPF[3:6]}.{CPF[6:9]}-{digit[0]}{digit[1]}')

    # VALIDAÇÃO CPF:

    if choise == 'c':
        CPF += str(digit[0])
        CPF += str(digit[1])

    if (int(CPF[-2]) == digit[0]) and (int(CPF[-1]) == digit[1]):
        print(f'O CPF "{CPF_print}" É VÁLIDO.')
    else:
        print(f'O CPF "{CPF_print}" É INVÁLIDO.')

    # RESPOSTA PARA LAÇO WHILE:

    answer = input('Você deseja continuar [S]im ou [N]ão? ').lower()

    while answer != 's' and answer != 'n':
        answer = input('Digite um valor válido [S] ou [N]: ').lower()

    if answer == 'n':
        break
    elif answer == 's':
        continue


from numpy import genfromtxt
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
import os
from nbastats import app
from nbastats.database import Player_Statistics, session

manager = Manager(app)

@manager.command
def run():
    port = int(os.environ.get('PORT', 8080))
    app.run(host='0.0.0.0', port=port)

@manager.command
def Load_Data(file_name):
    data = genfromtxt(file_name, delimiter=",", skip_header=1, usecols=np.arange(0,1434))

    try:
        for i in data.tolist():
            record = Player_Statistics(**{
                    'name' : i[0],
                    'team' : i[1],
                    'position' : i[2],
                    'game_played' : i[3],
                    'min_per_game' : i[4],
                    'field_goal_percent' : i[5],
                    'free_throw_percent' : i[6],
                    'three_made' : i[7],
                    'three_percent' : i[8],
                    'three_per_game' : i[9],
                    'pts_per_game' : i[10],
                    'o_reb_per_game' : i[11],
                    'd_reb_per_game' : i[12],
                    'reb_per_game' : i[13],
                    'ast_per_game' : i[14],
                    'steals_per_game' : i[15],
                    'blocks_per_game' : i[16],
                    'to_per_game' : i[17],
                    'fouls_per_game' : i[18],
                    'tot_tech' : i[19],
                    'plus_minus_rating' : i[20]
            })
            session.add(record)

        session.commit()
    except:
        session.rollback()
    finally:
        session.close()

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


import cv2
import numpy as np
import glob

CHECKBOARD = (6,9)
criteria = (cv2.TermCriteria_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)

object_points = []
image_points = []

# define 3d coordinate of chessboard points. chessboard is in center coordinate and camera moving around it
# we consider every square in chessboard as 1 unit
objp = np.zeros((1,CHECKBOARD[0]*CHECKBOARD[1], 3), np.float32)
objp[0,:,:2] = np.mgrid[0:CHECKBOARD[0], 0:CHECKBOARD[1]].T.reshape(-1, 2)
prev_img_shape = None

# read images
images = glob.glob("./camera_calibration/data/*.jpg")
for img_path in images:
    img = cv2.imread(img_path, 0)

    #find chessboard points
    ret, corners = cv2.findChessboardCorners(img, CHECKBOARD, cv2.CALIB_CB_ADAPTIVE_THRESH + cv2.CALIB_CB_FAST_CHECK + cv2.CALIB_CB_NORMALIZE_IMAGE)
    #if you find
    if ret==True:
        object_points.append(objp)
        #make a accurate chessboard points
        corners_accurate = cv2.cornerSubPix(img, corners, (11,11),(-1,-1), criteria)
        image_points.append(corners_accurate)

h, w = img.shape[:2]
#calculate intrinsic matrix and distortion and translation and rotation in every frame
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(object_points, image_points, img.shape[::-1], None, None)

print("Camera matrix : \n")
print(mtx , "\n")
print(f"focal length : {mtx[0,0]}, \n")
print("distortion : \n")
print(dist)


#!/usr/bin/env python3

# Lecture 2 S94
# A continue statement that jumps to the beginning of a while loop

more = "y"
while more.lower() == "y":
    milesDriven = float(input("Enter miles driven:\t\t"))
    gallonsUsed = float(input("Enter gallons of gas used:\t"))

    # validate input
    if milesDriven <= 0 or gallonsUsed <= 0:
        print("Both entries must be greater than zero. "
              + "Try again.\n")
        continue

    mpg = round(milesDriven / gallonsUsed, 2)
    print("Miles Per Gallon:", mpg, "\n")

    # more = raw_input("Continue? (y/n): ")
    more = input("Continue? (y/n): ")
    print

print("Okay, bye!")


lst=[2,3,4,5,6]
#find squares

squares=[num**2 for num in lst]
print(squares)

fruits=["apple","orange","mango"]

pairs=[(fruit,fruit)for fruit in fruits]
print(pairs)

lst1=[10,20]
lst2=[30,40]
#(10,30),(10,40),(20,30),(20,40)

pairs_lst=[(num1,num2) for num1 in lst1 for num2 in lst2]
print(pairs_lst)

lst1=[1,2,3,4,5]
evens=[num for num in lst1 if num%2==0]
print(evens)

lst=[7,8,9,4,3,2]
op=[ num+1 if num>5 else num-1 for num in lst]
print(op)

employees=[
    {"eid":1000,"name":"ajay","salary":25000,"designation":"developer"},
    {"eid": 1001, "name": "vijay", "salary": 22000, "designation": "developer"},
    {"eid": 1002, "name": "arun", "salary": 26000, "designation": "qa"},
    {"eid": 1003, "name": "varun", "salary": 27000, "designation": "ba"},
     {"eid": 1004, "name": "ram", "salary": 20000, "designation": "mrkt"},

]
#employees names
enames=[emp["name"] for emp in employees]
print(enames)

#developes name
developer=[emp for emp in employees if emp["designation"]=="developer"]
print(developer)

#highest salary
max_salary=max([emp["salary"] for emp in employees])
print(max_salary)


from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals

import threading

from googlecloudsdk.core import log
from googlecloudsdk.core.util import keyboard_interrupt
import six

class MashHandler(object):
  """MashHandler only invokes its base handler once.

  On the third attempt, the execution is hard-killed.
  """

  def __init__(self, base_handler):
    self._interrupts = 0
    self._base_handler = base_handler
    self._lock = threading.Lock()

  def __call__(self, signal_number, stack_frame):
    with self._lock:
      self._interrupts += 1
      # Copy the interrupts count and perform the handler outside of this
      # lock context. The handler can take a long time and we want to make
      # sure that future interrupts don't wait for it.
      interrupts = self._interrupts
    if interrupts == 1:
      # Only do the base handler once.
      self._base_handler(signal_number, stack_frame)
    elif interrupts == 3:
      # If we detect mashing, fallback to gcloud's original handler.
      keyboard_interrupt.HandleInterrupt(signal_number, stack_frame)

def GetCancelBuildHandler(client, messages, build_ref):
  """Returns a handler to cancel a build.

  Args:
    client: base_api.BaseApiClient, An instance of the Cloud Build client.
    messages: Module containing the definitions of messages for Cloud Build.
    build_ref: Build reference. Expects a cloudbuild.projects.locations.builds
      but also supports cloudbuild.projects.builds.
  """
  def _CancelBuildHandler(unused_signal_number, unused_stack_frame):
    """Cancels the build_ref build.

    Args:
      unused_signal_number: The signal caught.
      unused_stack_frame: The interrupt stack frame.

    Raises:
      InvalidUserInputError: if project ID or build ID is not specified.
    """
    log.status.Print('Cancelling...')

    # accepting both build_refs and legacy build_refs
    project_id = None
    if hasattr(build_ref, 'projectId'):
      project_id = build_ref.projectId
    elif hasattr(build_ref, 'projectsId'):
      project_id = build_ref.projectsId

    build_id = None
    if hasattr(build_ref, 'id'):
      build_id = build_ref.id
    elif hasattr(build_ref, 'buildsId'):
      build_id = build_ref.buildsId

    location = None
    if hasattr(build_ref, 'locationsId'):
      location = build_ref.locationsId

    if location is not None:
      cancel_name = 'projects/{project}/locations/{location}/builds/{buildId}'
      name = cancel_name.format(
          project=project_id, location=location, buildId=build_id)
      client.projects_locations_builds.Cancel(
          messages.CancelBuildRequest(
              name=name))
    else:
      client.projects_builds.Cancel(
          messages.CloudbuildProjectsBuildsCancelRequest(
              projectId=project_id, id=build_id))

    log.status.Print('Cancelled [{r}].'.format(r=six.text_type(build_ref)))
  return _CancelBuildHandler


from decimal import Decimal
from typing import Optional

from hummingbot.client.config.config_validators import (
    validate_bool,
    validate_decimal,
    validate_exchange,
    validate_int,
    validate_market_trading_pair,
)
from hummingbot.client.config.config_var import ConfigVar
from hummingbot.client.settings import AllConnectorSettings, required_exchanges

def maker_trading_pair_prompt():
    exchange = fixed_grid_config_map.get("exchange").value
    example = AllConnectorSettings.get_example_pairs().get(exchange)
    return "Enter the token trading pair you would like to trade on %s%s >>> " \
           % (exchange, f" (e.g. {example})" if example else "")

# strategy specific validators
def validate_exchange_trading_pair(value: str) -> Optional[str]:
    exchange = fixed_grid_config_map.get("exchange").value
    return validate_market_trading_pair(exchange, value)

def order_amount_prompt() -> str:
    trading_pair = fixed_grid_config_map["market"].value
    base_asset, quote_asset = trading_pair.split("-")
    return f"What is the amount of {base_asset} per order? >>> "

def validate_price_floor_ceiling(value: str) -> Optional[str]:
    try:
        decimal_value = Decimal(value)
    except Exception:
        return f"{value} is not in decimal format."
    if not (decimal_value == Decimal("-1") or decimal_value > Decimal("0")):
        return "Value must be more than 0 or -1 to disable this feature."

def exchange_on_validated(value: str):
    required_exchanges.add(value)

fixed_grid_config_map = {
    "strategy":
        ConfigVar(key="strategy",
                  prompt=None,
                  default="fixed_grid"),
    "exchange":
        ConfigVar(key="exchange",
                  prompt="Enter your maker spot connector >>> ",
                  validator=validate_exchange,
                  on_validated=exchange_on_validated,
                  prompt_on_new=True),
    "market":
        ConfigVar(key="market",
                  prompt=maker_trading_pair_prompt,
                  validator=validate_exchange_trading_pair,
                  prompt_on_new=True),
    "n_levels":
        ConfigVar(key="n_levels",
                  prompt="How many levels do you want on the fixed_grid? >>> ",
                  type_str="int",
                  validator=lambda v: validate_int(v, min_value=-1, inclusive=False),
                  default=5,
                  prompt_on_new=True),
    "grid_price_ceiling":
        ConfigVar(key="grid_price_ceiling",
                  prompt="Enter the ceiling price for the grid (top most order) >>>",
                  type_str="decimal",
                  validator=validate_price_floor_ceiling,
                  prompt_on_new=True),
    "grid_price_floor":
        ConfigVar(key="grid_price_floor",
                  prompt="Enter the floor price for the grid (bottom most order) >>>",
                  type_str="decimal",
                  validator=validate_price_floor_ceiling,
                  prompt_on_new=True),
    "start_order_spread":
        ConfigVar(key="start_order_spread",
                  prompt="How far away from the mid price do you want to place the "
                         "first order used to rebalance grid? (Enter 1 to indicate 1%) >>> ",
                  type_str="decimal",
                  default=Decimal("0.2"),
                  validator=lambda v: validate_decimal(v, 0, 100, inclusive=False)),
    "order_refresh_time":
        ConfigVar(key="order_refresh_time",
                  prompt="How often do you want to cancel and replace bids and asks "
                         "(in seconds)? >>> ",
                  type_str="float",
                  default=Decimal("1800"),
                  validator=lambda v: validate_decimal(v, 0, inclusive=False)),
    "max_order_age":
        ConfigVar(key="max_order_age",
                  prompt="How long do you want to cancel and replace bids and asks "
                         "with the same price (in seconds)? >>> ",
                  type_str="float",
                  default=Decimal("1800"),
                  validator=lambda v: validate_decimal(v, 0, inclusive=False)),
    "order_refresh_tolerance_pct":
        ConfigVar(key="order_refresh_tolerance_pct",
                  prompt="Enter the percent change in price needed to refresh orders at each cycle "
                         "(Enter 1 to indicate 1%) >>> ",
                  type_str="decimal",
                  default=Decimal("0"),
                  validator=lambda v: validate_decimal(v, -10, 10, inclusive=True)),
    "order_amount":
        ConfigVar(key="order_amount",
                  prompt=order_amount_prompt,
                  type_str="decimal",
                  validator=lambda v: validate_decimal(v, min_value=Decimal("0"), inclusive=False),
                  prompt_on_new=True),
    "order_optimization_enabled":
        ConfigVar(key="order_optimization_enabled",
                  prompt="Do you want to enable best bid ask jumping? (Yes/No) >>> ",
                  type_str="bool",
                  default=False,
                  validator=validate_bool),
    "ask_order_optimization_depth":
        ConfigVar(key="ask_order_optimization_depth",
                  prompt="How deep do you want to go into the order book for calculating "
                         "the top ask, ignoring dust orders on the top "
                         "(expressed in base asset amount)? >>> ",
                  required_if=lambda: fixed_grid_config_map.get("order_optimization_enabled").value,
                  type_str="decimal",
                  validator=lambda v: validate_decimal(v, min_value=0),
                  default=0),
    "bid_order_optimization_depth":
        ConfigVar(key="bid_order_optimization_depth",
                  prompt="How deep do you want to go into the order book for calculating "
                         "the top bid, ignoring dust orders on the top "
                         "(expressed in base asset amount)? >>> ",
                  required_if=lambda: fixed_grid_config_map.get("order_optimization_enabled").value,
                  type_str="decimal",
                  validator=lambda v: validate_decimal(v, min_value=0),
                  default=0),
    "take_if_crossed":
        ConfigVar(key="take_if_crossed",
                  prompt="Do you want to take the best order if orders cross the orderbook? ((Yes/No) >>> ",
                  default=True,
                  type_str="bool",
                  validator=validate_bool),
    "should_wait_order_cancel_confirmation":
        ConfigVar(key="should_wait_order_cancel_confirmation",
                  prompt="Should the strategy wait to receive a confirmation for orders cancellation "
                         "before creating a new set of orders? "
                         "(Not waiting requires enough available balance) (Yes/No) >>> ",
                  type_str="bool",
                  default=True,
                  validator=validate_bool),
}


import configparser
from typing import Optional
from pathlib import Path

class GitRepository:
    """
    A git repository
    """

    worktree: Path = None
    gitdir: Path = None
    conf: configparser.ConfigParser = None

    def __init__(self, path, force=False):
        self.worktree: Path = path
        self.gitdir: Path = path / '.git'

        if not (force or self.gitdir.is_dir()):
            raise Exception(f'Not a Git repository: {path}')

        # Read configuration file in .git/config
        self.conf = configparser.ConfigParser()
        cf: Path = repo_file(self, 'config')

        if cf and cf.exists():
            self.conf.read([cf])
        elif not force:
            raise Exception('Configuration file missing')

        if not force:
            vers = int(self.conf.get('core', 'repositoryformatversion'))
            if vers != 0 and not force:
                raise Exception(f'Unsupported repositoryformatversion {vers}')

def repo_path(repo: GitRepository, *path: str) -> Path:
    """
    Compute path under repo's gitdir.
    """
    return repo.gitdir.joinpath(*path)

def repo_file(repo: GitRepository, *path: str, mkdir: bool = False) -> Path:
    """
    Same as repo_path, but create dirname(*path) if absent.  For
    example, repo_file(r, \"refs\" \"remotes\", \"origin\", \"HEAD\") will create .git/refs/remotes/origin.
    """

    if repo_dir(repo, *path[:-1], mkdir=mkdir):
        return repo_path(repo, *path)

def repo_dir(repo: GitRepository, *path: str, mkdir: bool = False) -> Optional[Path]:
    """
    Same as repo_path, but mkdir *path if absent if mkdir.
    """

    path = repo_path(repo, *path)

    if path.exists():
        if path.is_dir():
            return path
        else:
            raise Exception(f'Not a directory {path}')

    if mkdir:
        path.mkdir(parents=True)
        return path
    else:
        return None

def repo_create(path: Path) -> GitRepository:
    """
    Create a new repository at path.
    """

    repo: GitRepository = GitRepository(path, True)

    if repo.worktree.exists():
        if not repo.worktree.is_dir():
            raise Exception(f'{path} is not a directory!')
        if [f for f in repo.worktree.glob('*')]:
            raise Exception(f'{path} is not empty!')
    else:
        repo.worktree.mkdir()

    assert (repo_dir(repo, "branches", mkdir=True))
    assert (repo_dir(repo, "objects", mkdir=True))
    assert (repo_dir(repo, "refs", "tags", mkdir=True))
    assert (repo_dir(repo, "refs", "heads", mkdir=True))

    # .git/description
    with repo_file(repo, "description").open(mode='w') as f:
        f.write("Unnamed repository; edit this file 'description' to name the repository.\n")

    # .git/HEAD
    with repo_file(repo, "HEAD").open(mode='w') as f:
        f.write("ref: refs/heads/master\n")

    with repo_file(repo, "config").open(mode='w') as f:
        config = repo_default_config()
        config.write(f)

    return repo

def repo_default_config() -> configparser.ConfigParser:
    ret = configparser.ConfigParser()

    ret.add_section("core")
    ret.set("core", "repositoryformatversion", "0")
    ret.set("core", "filemode", "false")
    ret.set("core", "bare", "false")

    return ret

def repo_find(path: Path = Path.cwd(), required: bool = True) -> Optional[GitRepository]:
    if (path / '.git').is_dir():
        return GitRepository(path)

    parent = path.parent

    if parent == path:
        if required:
            raise Exception("No git directory.")
        else:
            return None

    # Recursive case
    return repo_find(parent, required)


# -*- coding: utf-8 -*-
# © 2012-2015 KMEE (http://www.kmee.com.br)
# @author Luis Felipe Miléo <mileo@kmee.com.br>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from odoo import models
from odoo.exceptions import UserError
from ..boleto.document import Boleto

class IrActionsReport(models.Model):
    _inherit = 'ir.actions.report'

    def render_qweb_html(self, res_ids, data=None):
        if self.name == 'Boleto':
            return
        return super(IrActionsReport, self).render_qweb_html(
            res_ids, data=data)

    def render_qweb_pdf(self, res_ids, data=None):
        if not self.name == 'Boleto':
            return super(IrActionsReport, self).render_qweb_pdf(
                res_ids, data=data)

        move_line_ids = self.env['account.move.line'].browse()
        if self.model == 'account.invoice':
            ai_obj = self.env['account.invoice']
            for account_invoice in ai_obj.browse(res_ids):
                for move_line in account_invoice.receivable_move_line_ids:
                    move_line_ids |= move_line
        elif self.model == 'account.move.line':
            move_line_ids = self.env['account.move.line'].browse(res_ids)
        else:
            raise UserError(u'Parâmetros inválidos')
        move_line_ids = move_line_ids.filtered(
            lambda x: x.payment_mode_id.boleto)
        order_line_ids = self.env['payment.order.line'].action_register_boleto(
            move_line_ids)
        boleto_list = order_line_ids.generate_boleto_list()
        if not boleto_list:
            if self.env.context.get('ignore_empty_boleto'):
                return None, 'pdf'
            raise UserError('Nenhum boleto a ser emitido!')
        pdf_string = Boleto.get_pdfs(boleto_list)
        return pdf_string, 'pdf'


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

"""
main algorithm support bot
"""

import logging
from config import BotConfig
from telegram import (ReplyKeyboardMarkup, Bot)
from telegram.ext import (Updater, CommandHandler, MessageHandler, Filters, RegexHandler,
                          ConversationHandler)
import datetime
import random
import os
from django.conf import settings
from django.apps import apps
import similarity

conf = {
    'INSTALLED_APPS': [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'support',
    ],
    'DATABASES': {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join('.', 'db.sqlite3'),
        }
    }
}

settings.configure(**conf)
apps.populate(settings.INSTALLED_APPS)

print(BotConfig.bot_token)
bot = Bot(token=BotConfig.bot_token,  # "1239525175:e523a3ce66aae472c159d110ca4a24541f129a51",
          base_url=BotConfig.base_url,  # "https://tapi.bale.ai/",
          base_file_url="https://tapi.bale.ai/file/")
updater = Updater(bot=bot)

dp = updater.dispatcher

from support.models import QA, Pepole, Ticket

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.DEBUG)

logger = logging.getLogger()

MMENUE, MOTADAVEL, RECOM, SEND, ANSWER = range(5)

supp = "پشتیبانی و رفع مشکل"
ques = "سوالات متداول"
tecn = "لیست متخصصین"

def start(bot, update):
    # reply_keyboard = [['سوالات متداول', 'پشتیبانی و رفع مشکل']]
    reply_keyboard = [[supp, ques, tecn]]
    logger.info("شروع بات")
    dp.user_data['tecn_id'] = 0
    dp.user_data['tecn_baleid'] = 0
    current_user = update.message.chat_id
    # current_user = list(Pepole.objects.filter(user_id=update.message.chat_id).filter(user_type=2).values_list('id'))[0][
    #     0]
    if current_user > 0:
        update.message.reply_text('شما در سیستم به عنوان کارشناس تعریف شده اید سوالها برای شما ارسال میگردد'
                                  ,
                                  reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard)
                                  )
        return ANSWER
    else:
        update.message.reply_text(
            'لطفا ابتدا «سوالات متداول» را مطالعه فرمایید. در این بخش پرتکرار‌ترین سوالات به صورت کامل پاسخ داده شده‌اند.' +
            'در صورتی که پاسخ به سوال خود را در این بخش نیافتید و یا در فرایند ثبت‌نام خود با مشکل مواجه هستید، «درخواست پشتیبانی» را انتخاب نمایید.'
            ,
            reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard))

    return MMENUE

def mainmenue(bot, update):
    logger.info("main menue")
    user = update.message.from_user
    logger.info("main menue  %s: %s", user.first_name, update.message.text)
    update.message.reply_text('سوال خود را وارد کنید.')
    return RECOM

def recommendation(bot, update):
    logger.info("recommendation")
    reply_keyboard = [[]]
    faq = list(QA.objects.all().values_list('title'))

    candidate_questions = []
    for l in faq:
        candidate_questions.append(l[0])

    update_question = update.message.text
    dp.user_data['question'] = update.message.text
    dp.user_data['user_id'] = update.message.chat_id
    similar_questions = similarity.get_top_similarity(update_question, candidate_questions, 2)
    if len(similar_questions) != 0:
        print('similar_questions:', similar_questions)
        reply_keyboard[0] = similar_questions
        reply_keyboard[0].append('خیر')
        reply_keyboard[0].append("بازگشت")
        user = update.message.from_user
        logger.info("main menue  %s: %s", user.first_name, update.message.text)
        update.message.reply_text('آیا سوال شما شبیه یکی از موارد هست؟ روی آن کلیک کنید',

                                  reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard))
        return MOTADAVEL
    else:
        # print("not similar")
        # return SEND
        sendsend(bot, update)

def answer(bot, update):
    list1 = list(Ticket.objects.filter(tecn_id=update.message.chat_id).values_list('user_id_id', 'id'))
    dp.user_data['uswer_id'] = list1[0][0]

    bot.send_message(chat_id=dp.user_data['user_id'], text=update.message.text)
    # update.message.reply_text('به کارشناس {}ارسال شد'.format(tecnic_id[1]))

def sendsend(bot, update):
    if dp.user_data['tecn_id'] == 0:
        list1 = list(Pepole.objects.filter(user_type=2).values_list('user_id', 'id'))
        tecnic_id = random.choice(list1)
        dp.user_data['tecn_id'] = tecnic_id[1]
        dp.user_data['tecn_baleid'] = tecnic_id[0]
        list1 = list(Pepole.objects.filter(user_id=dp.user_data['user_id']).values_list('id'))
        print(dp.user_data['tecn_id'])
        print(dp.user_data['tecn_baleid'])
        current_time = datetime.datetime.now()
        t = Ticket(user_id_id=list1[0][0], tecn_id=dp.user_data['tecn_id'], qa_id_id=1, create_date=current_time)
        t.save()

    bot.send_message(chat_id=dp.user_data['tecn_baleid'],
                     text='کاربر :' + str(dp.user_data['tecn_baleid']) + ' متن سوال :' + dp.user_data['question'])
    update.message.reply_text('به کارشناس {}ارسال شد'.format(dp.user_data['tecn_id']))

def tecnic(bot, update):
    logger.info("tecnic")
    reply_keyboard = [[]]
    list1 = list(Pepole.objects.all().values_list('last_name'))
    print(list1)
    for l in list1:
        print(l[0])
        reply_keyboard[0].append(l[0])

    reply_keyboard[0].append("بازگشت")
    reply_keyboard[0].append("بازگشت به منو قبل")
    update.message.reply_text('یکی از متخصصین را انتخاب کنید',
                              reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard))
    return MOTADAVEL

def motadavel(bot, update):
    logger.info("متداول")
    reply_keyboard = [[]]
    list1 = list(QA.objects.all().values_list('title'))
    for l in list1:
        reply_keyboard[0].append(l[0])

    user = update.message.from_user
    logger.info("سولات متداول  %s: %s", user.first_name, update.message.text)

    update.message.reply_text('یکی از موارد زیر را انتخاب کنید.',
                              reply_markup=ReplyKeyboardMarkup(keyboard=reply_keyboard))
    return MMENUE

def cancel(bot, update):
    user = update.message.from_user
    logger.info("User %s canceled the conversation.", user.first_name)
    update.message.reply_text('Bye! I hope we can talk again some day.')

    return ConversationHandler.END

def error(bot, update):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, update.message)

if __name__ == '__main__':
    conv_handler = ConversationHandler(
        entry_points=[CommandHandler('start', start)],

        states={
            MMENUE: [RegexHandler(pattern='^({})$'.format(supp), callback=mainmenue),
                     RegexHandler(pattern='^({})$'.format(ques), callback=motadavel),
                     RegexHandler(pattern='^({})$'.format(tecn), callback=tecnic)],

            MOTADAVEL: [RegexHandler(pattern='^(aa)$', callback=motadavel),
                        RegexHandler(pattern='^({})$'.format('خیر'), callback=sendsend)],

            RECOM: [MessageHandler(Filters.text, recommendation)],

            SEND: [MessageHandler(Filters.text, sendsend)],
            ANSWER: [RegexHandler(pattern='^({})$'.format(supp), callback=mainmenue),
                     RegexHandler(pattern='^({})$'.format(ques), callback=motadavel),
                     RegexHandler(pattern='^({})$'.format(tecn), callback=tecnic),
                     MessageHandler(Filters.text, answer)],

        },

        fallbacks=[RegexHandler(pattern='^({})$'.format('بازگشت'), callback=start)]
    )

    dp.add_handler(conv_handler)

    # log all errors
    dp.add_error_handler(error)

    # dispatcher.add_error_handler(error)
    # dispatcher.add_handler(conv_handler)

    updater.start_polling(poll_interval=1)
    updater.idle()
    run()


from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np

Fmnist = input_data.read_data_sets("FMNIST/", one_hot=True)

x = tf.compat.v1.placeholder("float", [None, 784])
W2 = tf.Variable(tf.zeros([784, 10]))
b2 = tf.Variable(tf.zeros([10]))
y = tf.compat.v1.nn.softmax(tf.matmul(x, W2) + b2)
y_ = tf.compat.v1.placeholder("float", [None, 10])
"""
3 choices for cost function, but L2 norm works not so well
"""
cross_entropy = -tf.reduce_sum(y_ * tf.math.log(y))
# best learning rate = 0.001 acc: 85%
softmax_cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_))
# best learning rate = 0.25 acc: 80%
square_cost = tf.reduce_mean(tf.squared_difference(y_, y))
# not working well acc: 50%

train_step = tf.compat.v1.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)
init = tf.compat.v1.global_variables_initializer()
sess = tf.compat.v1.Session()
sess.run(init)

for i in range(5000):
    batch_xs, batch_ys = Fmnist.train.next_batch(100)
    if i % 500 == 0:
        print("Epoch: %d" % i, end=", Loss:")
        print(sess.run(square_cost, feed_dict={x: batch_xs, y_: batch_ys}))
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
print("test accuracy %g" % sess.run(accuracy, feed_dict={x: Fmnist.test.images, y_: Fmnist.test.labels}))


import datetime

date_and_prod = {
    str(datetime.date(2022, 12, 1)): 'banana apple bread',
    str(datetime.date(2022, 12, 2)): 'milk snikers tea',
    str(datetime.date(2022, 12, 3)): 'meat cheese actimel',
    str(datetime.date(2022, 12, 4)): 'meat apple',
    str(datetime.date(2022, 12, 5)): 'tea sugar',
    str(datetime.date(2022, 12, 6)): 'water bread',
}
prod_and_price = {
    'milk': 68,
    'banana': 49,
    'bread': 25,
    'apple': 37,
    'snikers': 40,
    'water': 18,
    'tea': 350,
    'sugar': 28,
    'actimel': 37,
    'meat': 450,
    'cheese': 278,
}

def year_pr():
    year = input('Введите год покупки: ')
    while not (year.isdigit()):
        year = input('Введите год покупки правильно: ')
    year = int(year)
    while year > 2023 or year < 1900:
        year = input('Введите год покупки правильно: ')
        while not (year.isdigit()):
            year = input('Введите год покупки правильно: ')
        year = int(year)
    return year

def month_pr():
    month = input('Введите месяц покупки: ')
    while not (month.isdigit()):
        month = input('Введите месяц покупки правильно: ')
    month = int(month)
    while month > 12 or month < 1:
        month = input('Введите месяц покупки правильно: ')
        while not (month.isdigit()):
            month = input('Введите месяц покупки правильно: ')
        month = int(month)
    return month

def day_pr(months, month):
    day = input('Введите день покупки: ')
    while not (day.isdigit()):
        day = input('Введите день покупки правильно : ')
    day = int(day)
    while day > months[month - 1] or day < 1:
        day = input('Введите день покупки правильно : ')
        while not (day.isdigit()):
            day = input('Введите день покупки правильно: ')
        day = int(day)
    return day

def date_prod_upd():
    year = year_pr()
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    else:
        months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    month = month_pr()
    day = day_pr(months, month)
    ans = input('Вы покупали продукты, которых раньше не было? \nY/N \n')
    while not (ans in ['Y', 'N']):
        ans = input('Ввод неверный, Вы покупали продукты, которых раньше не было? \nY/N \n')
    while ans == 'Y':
        new_prod = input('Введите название продукта: ')
        price_new_prod = 0
        while price_new_prod <= 0:
            price_new_prod = input('Введите цену продукта больше 0: ')
            while not (price_new_prod.isdigit()):
                price_new_prod = input('Введите цену товара числом: ')
            price_new_prod = float(price_new_prod)
        prod_and_price[new_prod] = price_new_prod
        ans = input('Есть ли ещё новые продукты? \nY/N \n')
        while not (ans in ['Y', 'N']):
            ans = input('Ввод неверный, есть ли ещё новые продукты? \nY/N \n')
    product_sp = input('Введите список продуктов через пробел: ')
    flag = 0
    while flag == 0 or product_sp == '':
        k=1
        while product_sp == '':
            product_sp = input('Ввод пустой, введите список продуктов: ')
        mas_pr = product_sp.split()
        for i in range(len(mas_pr)):
            if not (mas_pr[i] in list(prod_and_price.keys())):
                k=0
                product_sp = input('Ввод неверный, введите список продуктов из БАЗЫ: ')
                break
        if k==1:
            flag=1
    date_and_prod[str(datetime.date(year, month, day))] = product_sp
    print('Запись добавлена')

def delete_date_prod_price():
    ans = input('Запись по какому ключу Вы хотите удалить? \n1)Дата \n2)Наименование товара \n')
    while not (ans in ['1', '2']):
        ans = input('Ввод неверный, запись по какому ключу Вы хотите удалить? \n1)Дата \n2)Наименование товара \n')

    if ans == '1':
        year = year_pr()
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
            months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        else:
            months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        month = month_pr()
        day = day_pr(months, month)
        while not str(datetime.date(year, month, day)) in date_and_prod.keys():
            print('Введите данные из базы: ')
            year = year_pr()
            if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
                months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            else:
                months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
            month = month_pr()
            day = day_pr(months, month)
        date_and_prod.pop(str(datetime.date(year, month, day)))
    if ans == '2':
        name = input('Введите наименование товара: ')
        while not name in prod_and_price.keys():
            name = input('Введите наименование товара из БАЗЫ: ')
        prod_and_price.pop(name)
    print('Запись удалена')

def date_prosmotr():
    year = year_pr()
    month = month_pr()
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    else:
        months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    day = day_pr(months, month)
    while not (str(datetime.date(year, month, day)) in list(date_and_prod.keys())):
        print('Ввод неверный, попробуйте ещё раз: ')
        year = year_pr()
        month = month_pr()
        if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
            months = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        else:
            months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        day = day_pr(months, month)
    print(date_and_prod[str(datetime.date(year, month, day))])

def price_prosmotr():
    name = input('Введите наименование товара: ')
    while not (name in list(prod_and_price.keys())):
        name = input('Введите наименование товара из БАЗЫ: ')
    print(prod_and_price[name])

def sort_key(m):
    return m[1]

def price_sp():
    print(sorted(prod_and_price.items(), key=sort_key))

while True:
    ans_start = input(
        'Здравствуйте, что Вы хотите сделать? \n1)Добавить покупку \n2)Посмотреть покупки по дате \n3)Посмотреть цену товара '
        '\n4)Просмотреть товары по стоимости \n5)Удалить записи \n6)Выйти из программы \n')
    while ans_start not in ['1', '2', '3', '4', '5', '6']:
        ans_start = input('Ввод неверный, попробуйте ещё раз: ')
    if ans_start == '1':
        date_prod_upd()
        print(date_and_prod.items())
        print(prod_and_price.items())
    elif ans_start == '2':
        date_prosmotr()
        print(date_and_prod.items())
        print(prod_and_price.items())
    elif ans_start == '3':
        price_prosmotr()
        print(date_and_prod.items())
        print(prod_and_price.items())
    elif ans_start == '4':
        price_sp()
        print(date_and_prod.items())
        print(prod_and_price.items())
    elif ans_start == '5':
        delete_date_prod_price()
        print(date_and_prod.items())
        print(prod_and_price.items())
    else:
        break

Проект по программированию.py

Проект по программированию.py


from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
from escpos import *
from fastapi.responses import JSONResponse
from typing import Optional

app = FastAPI()

origins = ['*']
p = printer.Serial("COM5")

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"]
)

class PrintData(BaseModel):
    phone: Optional[str]
    note: Optional[str]
    code: Optional[str]
    name: Optional[str]
    collective: Optional[str]
    collective_name: Optional[str]
    identifier: Optional[str]
    status: Optional[str]
    email: Optional[str]

@app.post("/print")
def info_to_print(data: PrintData):

    if(p == None or p == ""):
        return JSONResponse(
        status_code=404,
        content={"context": "no_printer_found"},
        )

    p.magic.force_encoding("CP858")

    p.set(align="center", custom_size=True, width=2, height=2)
    p.text(data.collective_name)
    p.ln()
    p.ln()
    p.set(align="center", custom_size=True, width=2, height=2)
    p.text(data.phone)
    p.ln()
    p.ln()
    p.set(align="center", custom_size=True, width=1, height=1)
    p.qr(data.code, size=8)
    p.ln()
    p.ln()
    p.set(align="center", custom_size=True, width=2, height=2)
    p.text(data.note)
    p.ln()
    p.cut()

    return JSONResponse(
        status_code=200,
        content={"context": "printing_ticket"},
        )


import pandas
teploty = pandas.read_csv("temperature.csv")
import pytemperature
import matplotlib.pyplot as plt

# na stupně Celsia
teploty["AvgTemperatureC"] = pytemperature.f2c(teploty["AvgTemperature"])

mihelto = teploty[(teploty["City"] == "Miami Beach") | (teploty["City"] == "Helsinki") | (teploty["City"] == "Tokyo")]
# šlo použít i isin
mihelto = mihelto[["City", "AvgTemperatureC"]]

ax = mihelto.boxplot(by="City", whis=[0, 100])
ax.set_ylabel("Teploty ve stupních Celsia")
ax.set_xlabel("Město")
ax.set_title("Porovnání teplot Miami - Helsinki - Tokyo")
plt.show()


# https://www.acmicpc.net/problem/2836 문제 제목 : 수상 택시 , 언어 : Python, 날짜 : 2020-05-08, 결과 : 성공
"""
    회고:
    아이디어를 구상하는데에는 그렇게 오래 걸리지 않았는데 코드를 구현하다 잠깐씩 생각하는 시간이 많았다..
    우선 이 문제의 입력중 a < b인 경우는 생각을 안해줘도 된다. 어차피 택시는 M으로 가야하니깐 말이다.
    그래서 나는 b > a인 경우일때만 배열에 추가하고 정렬을 해 주 었다. 그리고 이어져 있는(?) 모든 범위들의 길이를 결과값어 더해주면된다.
    이때 더해주는 값은 *2를 해줘야 한다. 갔다가 다시 방향을 틀어서 돌아와야 하니깐 말이다.

    사실 내일 소마 면접이다. 다른 분들처럼 스펙이 있는게 아니라 붙기는 힘들겠지만 동기부여를 받고 와야겠다.
"""
import sys

N, M = map(int, sys.stdin.readline().split())
list_graph = []
check = set()
for i in range(N):
    a, b = map(int, sys.stdin.readline().split())
    if a > b:
        list_graph.append([a, i])
        list_graph.append([b, i])
list_graph.sort()
start = list_graph[0][0]
result = M
for now, num in list_graph:
    if num in check:
        check.remove(num)
        if not check:
            result += (now - start)*2
    else:
        if not check:
            start = now
        check.add(num)
print(result)

"""
for now, num in list_graph:
    print(now, num, start)
    if num in check:
        check.remove(num)
        if not check:
            if not start == -1:
                result+=(now-start)*2
    else:
        check.add(num)
        start = now
        """

"""
3 10
3 1
4 2
8 6

6 10
0 2
3 1
4 2
4 9
7 10
8 6
"""


def range_of_motion_of_robert(board):
    if not board:
        return None
    row_len, col_len, num, k = len(board), len(board), set(), 13
    """可以用ans存储所有的路径，然后将里面的格子并集，就得到了所有的范围"""
    def check_point(row, col):
        sum_row, sum_col = 0, 0
        while (row):
            sum_row += row % 10
            row = row // 10
        while (col):
            sum_col += col % 10
            col = col // 10
        return sum_row + sum_col

    def backtracking(i, j, visited):
        if not check_point(i, j) < k:
            return
        else:
            #num=num | set([(i, j)])
            """这里很重要的啊，因为，虽然感觉num好像会一直增加，但是其实回溯的时候，num也会回到上一阶段，为什么呢？？？？？
            因为
            num重新赋值了啊，num有了一个新的地址，老的num地址被存储在栈中，然后返回上一级会回到那个老的地址的，这样就造成了
            num的"回溯"。
            正确的方法是直接在地址里改变内容

            原来我定义了一个count计数器，没进入一次就count++，这样是错误的，因为这个思路是当前i,j是(2,2),然后延伸出来(2,3)
            ,(2,4)这一条路，visited中是(2,2),(2,3),(2,4)。然后，count=count+2.然后我回溯，这时候，visited中只有(2,2)了，然后
            新的路径可能会和上一条路径有重复的格子。所以count会多很多
            """
            num.add((i, j))
            for (a, b) in [(a, b) for (a, b) in [(i - 1, j), (i + 1, j), (i, j - 1), (i, j + 1)] if
                           0 <= a < row_len and 0 <= b < col_len and (a, b) not in visited]:
                visited.add((i, j))#！！！！！！！！！！！和平常不一样
                backtracking(a, b, visited)##！！！！！！！！！！！！
                """这里又有一个小技巧，原来的是backtracking(a, b, visited| set([(i,j)]),相当于将所有的路径都求出来了，
                不是相当于2的m*n次方条路径，因为比如九宫格，周围都不是路径的一分子，则中间的不可能是是路径的一分子。
                这样很浪费时间，非常浪费。
                但是将每次迭代遍历过的都保留，这就相当于给格子染上黑色。最终只要是有路径能够到达的地方，都会被染成黑色"""
    backtracking(0, 0, set())
    return len(num)

# if flag==0:#如果flag是0的话，表示已经到头了，退出就可以了
#    return
n=100
board = [[0] * n for _ in range(0, n)]
print(board)
print(range_of_motion_of_robert(board))

机器人的运动范围_13.py


#!/usr/bin/python3

# examples from Python-Essential-Reference-Developers-Library by David Beazley
# with revisions by TK

import time

# returns multiple values using a tuple
def countdown(n):
    print("generator function counting down")
    while n > 0:
        yield n
        n -= 1

# unix like tail function
def tail(f):
    f.seek(0, 2)  # move to EOF
    while True:
        line = f.readline()
        if not line:
            time.sleep(0.1)
            continue
        yield line

def grep(lines, searchtext):
    for line in lines:
        if searchtext in line:
            yield line

# main function
def main():
    for i in countdown(20):
        print(i, "", end="")
    print("")

    print("\nNext this tails input1.txt, displaying output when 'test' is added.")
    print("Either run this program in the background and then run")
    print("'echo test >> input1.txt' in the foreground or append to this")
    print("file from another terminal.  Append 'end test' to terminate")
    tailed = tail(open("input1.txt"))
    grepped = grep(tailed, "test")

    for line in grepped:
        print(line, end="")
        if "end" in line:
            break

# start here
main()


"""
Given: An RNA string s corresponding to a strand of mRNA (of length at most 10 kbp).

Return: The protein string encoded by s.
"""

def rna_to_protein(rna):
    # Code for codon table found at http://www.petercollingridge.co.uk/tutorials/bioinformatics/codon-table/
    bases = "UCAG"
    codons = [a + b + c for a in bases for b in bases for c in bases]
    amino_acids = 'FFLLSSSSYY**CC*WLLLLPPPPHHQQRRRRIIIMTTTTNNKKSSRRVVVVAAAADDEEGGGG'
    codon_table = dict(zip(codons, amino_acids))

    aa_seq = ''
    end = len(rna) % 3
    for i in range(0, len(rna)-end, 3):
        if codon_table[rna[i:i + 3]] == '*':
            break

        aa_seq += codon_table[rna[i:i+3]]

    return aa_seq

if __name__ == '__main__':
    rna = input('Enter an RNA sequence: ')
    print(rna_to_protein(rna))


import time
import requests
import json
#第一步读取八行包内容
# 以下为固定内容
# POST /wisdomprovider/router? HTTP/1.1
# Content-Length: 373
# Host: wisdom.tskjxy.com.cn
# Connection: Keep-Alive
# Accept-Encoding: gzip
# content-type: application/x-www-form-urlencoded;charset=utf8
class Openua:
    config = "123"

    def __init__(self, fielname):
        file = open(fielname, 'r', encoding="UTF-8")
        self.config = file.readline().strip("\n")
        print("成功加载请求体")
        i=True
        while i:
            go = int(self.config[-10:]) - int(time.time())  # 获取开始时间,获取当前时间，得到距离开始时间

            #print("\r距离活动开始报名还有" + str(go) + "秒",end="")
            if(go<2):
                print("\t开始抢活动")
                i=False
            time.sleep(0.5)

# print(Openua("config.txt").config)
# 在这里定义访问
class gogogo:
    def __init__(self,data):
        url="http://wisdom.tskjxy.com.cn/wisdomprovider/router?"
        headers = {"POST /wisdomprovider/router? HTTP/1.1":"","Content-Length":"373","Host":"wisdom.tskjxy.com.cn","Connection":"Keep-Alive","Accept-Encoding":"gzip","content-type":"application/x-www-form-urlencoded;charset=utf8"}
        # 无限循环抢活动开始
        # 无限循环抢活动开始
        i = True
        t=0
        while i:
            t=t+1
            re = requests.post(url,headers=headers, data=data)
            re=json.loads(re.text)
            print("\r"+str(t)+"次",end="")
            # {"msg": "很抱歉，与您报名“五汶决策锻造计划第三期“普法进校园””活动有时间冲突", "code": "-1", "detailCode": "145"}
            # temp=re.text=="{\"code\":\"-1\",\"detailCode\":\"999999\"}"
            # if(re["code"]=='-1' and len(re["msg"])>5):
            #     print("抢课失败："+re["msg"])
            #     i=False
            # elif(re["code"]=='-1'):
            #     print("\r抢课未成功-第"+str(t)+"次",end="")
            # elif(re["code"]!='-1'):
            #     print(str(t)+"次抢课成功")
            #     i=False
            time.sleep(0.01)
            if (re["code"] != '-1'):
             print(str(t)+"次抢课成功")
             i=False

print(gogogo(Openua("config.txt").config))

# print(gogogo("anonymousId=53e9c2e2-36cf-466a-9be0-b06e13e28914&method=wisdom.extra.activity.signUpPersonalInit&roleId=51e34772-7993-435c-9079-fd291365cda8&format=json&sign=4973381D3014B12F31EC68C9676A897583A58DA5&tenantCode=tskjxy&userId=53e9c2e2-36cf-466a-9be0-b06e13e28914&deviceId=218d5804335dede9&v=2.0&appKey=00000001&taskId=a580513c-93f1-4a7e-99b1-816280907441&timestamp=1663113600"))


import json
from multiprocessing import Pool

import requests

from . import celery
from .libs.db import get_db
from .libs.models import Model, Order, User
from .libs.utils import submit_data, submit_train_task, error_response

@celery.task
def infer_task(url, data_sql, model_params, attributes, unique_id, order_id):
    # Get current job
    db = get_db()
    order = db.query(Order).filter(Order.id == order_id).first()
    job_info = json.loads(order.job_info)

    data = {'data_sql': data_sql, 'model_params': model_params,
            'attributes': attributes, 'unique_id': unique_id}
    print(data)
    response = requests.post(url, json=data)
    if response.status_code != 200:
        job_info['infer_status'] = 'failed'
        job_info['debug_info'] = json.dumps(response.text)
        job_info['result'] = None

    try:
        job_info['result'] = json.loads(response.text)['data']
        # Return result
        import numpy as np
        import hashlib
        for result in job_info['result']:
            uid = result[data['unique_id']].encode('utf-8')
            print(uid)
            seed = int(hashlib.md5(uid).hexdigest()[:8], 16)
            np.random.seed(seed)
            result['label'] = np.around(np.clip(np.random.normal(loc=0.1, scale=0.1), 0, 1), decimals=4)
        job_info['infer_status'] = 'finished'
    except Exception as e:
        job_info['infer_status'] = 'failed'
        job_info['debug_info'] = json.dumps({"exception info": str(e)})
        job_info['result'] = None

    order.job_info = json.dumps(job_info)

    db.add(order)
    db.commit()

    return job_info

@celery.task
def train_task(data, train_conf_template, dsl_template, order_id, model_id):
    user_id = data.get('user_id')
    model_type = data.get('model_type')
    model_param = data.get('model_params')
    party_id = data.get('party_id')
    data_info = data.get('data_info')
    attributes = data.get('attributes')
    label_name = data.get('label_name')
    original_attr = attributes
    unique_id = data.get('unique_id')
    attributes = [unique_id] + attributes + [label_name]
    label_value = data.get('label_value')

    # Reading database
    db = get_db()
    initiator = db.query(User).filter(User.id == user_id).first()
    hosts = [db.query(User).filter(User.id == uid).first() for uid in party_id]
    order = db.query(Order).filter(Order.id == order_id).first()
    model = db.query(Model).filter(Model.id == model_id).first()

    # Prewrite order info
    order.job_info = json.dumps({'train_status': 'reading data'})
    db.add(order)
    db.commit()

    # Submit reading data task to clients
    id_map = {user.party_id: user.id for user in [initiator] + hosts}
    responses = {}
    p = Pool(len(data_info))
    for k, v in data_info.items():
        user = db.query(User).filter(User.id == k).first()
        url = user.client_url + "/api/read_data"
        responses[user.party_id] = p.apply_async(
            submit_data, args=(url, v, attributes, label_value, ))
    p.close()
    p.join()

    # Generate config file
    with open(train_conf_template, 'r', encoding='utf-8') as f:
        conf_dict = json.loads(f.read())

    conf_dict['initiator']['party_id'] = initiator.party_id
    conf_dict['initiator']['role'] = 'guest'

    conf_dict['role']['guest'] = [initiator.party_id]
    conf_dict['role']['host'] = [host.party_id for host in hosts]
    conf_dict['role']['arbiter'] = [10000]

    # DO NOT CHANGE
    conf_dict['role_parameters']['guest']['args']['data']['train_data'] = [{'namespace': json.loads(responses[pid].get(
    ).text)['data']['data']['namespace'], 'name': json.loads(responses[pid].get().text)['data']['data']['table_name']} for pid in conf_dict['role']['guest']]
    conf_dict['role_parameters']['host']['args']['data']['train_data'] = [{'namespace': json.loads(responses[pid].get(
    ).text)['data']['data']['namespace'], 'name': json.loads(responses[pid].get().text)['data']['data']['table_name']} for pid in conf_dict['role']['host']]

    conf_dict['algorithm_parameters']['homo_lr_0'] = model_param

    conf_dict['algorithm_parameters']['dataio_0']['label_name'] = label_name

    # Read DSL file
    with open(dsl_template, 'r', encoding='utf-8') as f:
        dsl_dict = json.loads(f.read())

    # Add information
    data_volum = dict()
    for pid in id_map.keys():
        response = json.loads(responses[pid].get().text)
        if response['code'] != 200:
            return error_response(message=response)
        data_volum[id_map[pid]] = response['info']['data_volum']

    # Submit train task
    response = submit_train_task(
        initiator.client_url+'/api/training_task', conf_dict, dsl_dict)

    model_info = json.loads(response.text)['data']['data']['model_info']

    model_param['attributes'] = original_attr
    model_param['unique_id'] = unique_id
    model_param['label_name'] = label_name
    model_param['data_volum'] = data_volum

    # Update model info
    model.fate_id = model_info['model_id']
    model.fate_version = model_info['model_version']
    model.info = json.dumps(model_param)

    # Update order info
    order.fate_job_id = model.fate_version
    order.order_info = json.dumps(data)
    order.job_info = json.dumps(conf_dict)

    initiator.models.append(model)
    order.model = model
    db.add(model)
    db.add(order)
    db.commit()

    return model.info, model_param


"""
Jumbotron Calibration.
Figures out how the markers found by artoolkit map to the jumbotron screen.
"""
from __future__ import print_function
import logging
import math
import operator
from PIL import Image, ImageDraw
from PIL.ExifTags import TAGS
import artoolkit
from vectypes import Mat4, Vec3

# ----------------------------------------------------------------------

def _get_camera_xform(image):
    """Return the xform that maps world coordinates to image
    coordinates. Uses the Iphone's lens characteristics."""
    film_size    = 6.35 # Iphone sensor size, in mm
    focal_length = 3.85 # Iphone focal length, in mm
    width, height = image.size
    aspect = float(width) / height
    fov_y = 2 * math.atan2(film_size/aspect, 2 * focal_length)
    xform = Mat4.new_translate(width/2.0,  height/2.0, 0)
    xform.scale(-width/2.0, -height/2.0, 1)
    xform *= Mat4.new_perspective(fov_y, aspect, 1, 10)
    return xform

def _get_change_basis_xform(center, up, normal):
    """Return a matrix that changes from the given basis to the x-y-z
    basis. Basically, this 'straightens' out the plane described by
    the basis. The 'right' axis is calculated from the up and normal."""
    normal = normal.normalized()
    right = up.cross(normal).normalize()
    up    = normal.cross(right).normalize()

    xform = Mat4.new_translate(*center)
    xform *= Mat4.new_change_basis(right, up, normal, center).inverse()
    return xform

def _find_best_change_basis_xform(markers):
    """Find the plane that best fits the markers, and return the
    matrix that transforms this plane to the x-y-z plane."""
    centers = (marker.world_center for marker in markers)
    ups     = (marker.world_up     for marker in markers)
    normals = (marker.world_normal for marker in markers)
    avg_center = reduce(operator.add, centers) / len(markers)
    avg_up     = reduce(operator.add, ups    ) / len(markers)
    avg_normal = reduce(operator.add, normals) / len(markers)
    return _get_change_basis_xform(avg_center, avg_up, avg_normal)

def _align_markers(markers):
    """Project the markers along the camera view onto the same plane"""

    # Calculate 'average' plane defined by the markers
    centers = (marker.world_center for marker in markers)
    normals = (marker.world_normal for marker in markers)
    avg_center = reduce(operator.add, centers) / len(markers)
    avg_normal = (reduce(operator.add, normals) / len(markers)).normalize()
    planen = avg_normal
    planed = -avg_normal.dot(avg_center)  # Could use a constant as well

    # Determine where the ray from the origin (camera center) to each
    # marker vertex intersects the 'average' plane
    for marker in markers:
        ray =  marker.world_center
        norm = -planed / planen.dot(ray)
        marker.world_center = ray * norm
        marker.world_vertices = [vertex * norm for vertex in marker.world_vertices]

    centers = (marker.world_center for marker in markers)
    avg_center = reduce(operator.add, centers) / len(markers)

def _find_display_coords(marker, marker_vertices, display):
    """Calculate the display corners from the marker corners. For now,
    assume everything is orthogonal."""

    # Get bounding box
    minv = Vec3.min(*marker_vertices)
    maxv = Vec3.max(*marker_vertices)
    size = maxv - minv

    # Stretch to account for white border
    minv -= size / 8.0
    maxv += size / 8.0
    size = maxv - minv

    # Stretch to display aspect ratio
    direction = marker.world_direction
    dar = display.aspectRatio
    if direction == 1 or direction == 3 :
        dar = 1.0 / dar

    if dar > 1:
        # The display is bigger horizontally than vertically.
        width = size.y * dar
        stretch = (width - size.x) / 2.0
        # The image is centered, so stretch in both directions.
        minv.x -= stretch
        maxv.x += stretch

    else:
        # The display is bigger vertically than horizontally.
        height = size.x / dar
        stretch = (height - size.y) / 2.0
        # The image is centered, so stretch in both directions.
        minv.y -= stretch
        maxv.y += stretch

    # Done
    return [minv, maxv]

def _draw_vertices(draw, vertices, color="white", width=5):
    """Draw a polygon"""
    # Convert to 2d tuples
    vertices = [(v.x, v.y) for v in vertices]
    if width:
        vertices.append(vertices[0])
        for u, v in zip(vertices[:-1], vertices[1:]):
            draw.line((u, v), color, width)
    else:
        draw.polygon(vertices, color)

def _draw_rectangle(draw, minv, maxv, color="white", width=5):
    """Draw a rectangle"""
    # Convert to 2d tuples
    vertices = [minv, Vec3(minv.x, maxv.y), maxv, Vec3(maxv.x, minv.y)]
    _draw_vertices(draw, vertices, color, width)

def _debug(**kwargs):
    """Log a list of keyword/value pairs"""
    for key, value in kwargs.items():
        logging.debug("%s\t: %s", key, str(value))

def _debug_image(draw, coords, xform, plane_xform, cam_xform):
    """Draw debugging info on the calibration image"""
    minv, maxv = coords
    ixform = xform.inverse()
    iplane_xform = plane_xform.inverse()
    icam_xform = cam_xform.inverse()
    vertices = (Vec3(maxv.x, minv.y, minv.z),
                Vec3(maxv.x, maxv.y, minv.z),
                Vec3(minv.x, maxv.y, minv.z),
                Vec3(minv.x, minv.y, minv.z))
    _draw_vertices(draw, vertices, (255, 0, 0, 255), width=7)

    vertices = [icam_xform.transform(vertex) for vertex in vertices]
    vertices = [ixform.transform(vertex) for vertex in vertices]
    vertices1 = (cam_xform.transform(vertex) for vertex in vertices)
    _draw_vertices(draw, vertices1, (0, 255, 0, 200), width=5)

    vertices = [iplane_xform.transform(vertex) for vertex in vertices]
    vertices1 = (cam_xform.transform(vertex) for vertex in vertices)
    _draw_vertices(draw, vertices1, (0, 0, 255, 200), width=3)

def _reorient_image(image):
    """Reorient the image based on exif tags in the jpg file"""
    try:
        exif = image._getexif()
        if exif:
            for tag, value in exif.items():
                decoded = TAGS.get(tag, tag)
                if decoded == 'Orientation':
                    if   value == 3:
                        image = image.rotate(180)
                    elif value == 6:
                        image = image.rotate(270)
                    elif value == 8:
                        image = image.rotate(90)
                    break
    except KeyError as ke:
        logging.error("KeyError in reorient_image: " + str(ke))
        # The version of PIL on the server is OLD and throws key
        # errors if the exif isn't found
        pass
    except AttributeError:
        # No exif tags
        pass
    return image

def _calibrate(jumbotron, displays, image, debug=False, debug_image=False):
    """Calibrate a jumbotron with a calibration images."""
    if debug_image:
        draw = ImageDraw.Draw(image, "RGBA")

    # Initialize display viewports
    for display in displays.values():
        display.viewport = None

    # Find markers
    found_markers = artoolkit.detect(image, confidence_threshold=0.5,
                                     debug=False, debug_image=debug_image)

    # Throw out unknown markers
    markers = [marker for marker in found_markers if marker.id in displays]
    if not markers:
        return 0
    if len(markers) < len(found_markers):
        # TODO: get this info to node.js
        #logging.warn("Found unknown markers in jumbotron %s", jumbotron.name)
        pass

    # The method used here has problems when combining very small
    # displays with very large displays. The small displays will seem
    # to be very far away, so any vertical or horizontal separation
    # between them and the larger display will be amplified. An
    # alternative might be to use the screen coordinates of each
    # marker. Needs more thought if this becomes an issue.

    # Get camera xform
    cam_xform = _get_camera_xform(image)

    # Align markers as best we can
    _align_markers(markers)

    # Find best fitting plane
    plane_xform = _find_best_change_basis_xform(markers)

    # Project each marker to x-y plane and stretch to display size
    coords = []
    for marker in markers:
        idx = marker.id

        # Rotate from the best-fitting plane to the x-y plane.
        rot_vertices = [plane_xform.transform(vertex)
                        for vertex in marker.world_vertices]

        # Then rotate about the marker's center to the x-y plane
        center = plane_xform.transform(marker.world_center)
        normal = plane_xform.transform_vector(marker.world_normal).normalize()
        up     = plane_xform.transform_vector(marker.world_up).normalize()
        xform = _get_change_basis_xform(center, up, normal)
        xy_vertices = [xform.transform(vertex) for vertex in rot_vertices]

        # Use the camera transform to project to the screen
        screen_vertices = [cam_xform.transform(vertex)
                           for vertex in xy_vertices]

        # Finally, stretch to the display corners
        coord = _find_display_coords(marker, screen_vertices, displays[idx])
        coords.append(coord)

        if debug:
            _debug(Display=marker.id,
                   world=marker.world_vertices, plane=rot_vertices,
                   xyplane=xy_vertices, cam=screen_vertices, bbox=coord)
        if debug_image:
            _debug_image(draw, coords[idx], xform, plane_xform, cam_xform)

    # Find the bounding box of all the markers
    allminv = Vec3.min(*(coord[0] for coord in coords))
    allmaxv = Vec3.max(*(coord[1] for coord in coords))
    allsize = allmaxv - allminv
    if debug_image:
        _draw_rectangle(draw, allminv, allmaxv, "white", width=1)
    jumbotron.aspectRatio = allsize.x / allsize.y

    # Normalize viewports and set in displays
    for marker, coord in zip(markers, coords):
        idx = marker.id
        minv = (coord[0] - allminv)
        maxv = (coord[1] - allminv)
        size = maxv - minv

        displays[idx].viewport = dict(x=minv.x / allsize.x,
                                      y=minv.y / allsize.y,
                                      width=size.x / allsize.x,
                                      height=size.y / allsize.y,
                                      rotation=marker.world_direction)

    if debug:
        logging.debug("Final displays:")
        for marker, coord in zip(markers, coords):
            logging.debug("display {0} {1}".format(marker.id, coord))

    if debug_image:
        image.save("calibrate_out.jpg")

    return len(markers)

# ----------------------------------------------------------------------

def main(argv):
    """Perform calibration from the command line. Doesn't actually
    change the database, just prints lots of debugging info.
    Usage: python calibrate.py [db_file] <jumbotron_name> <image_name>"""

    import json

    class attrdict(dict):
        def __init__(self, *args, **kwargs):
            dict.__init__(self, *args, **kwargs)
            self.__dict__ = self

    # parse jumbotron info argv
    image_name = argv[1]
    jumbotron = attrdict(json.loads(argv[2]))

    # Convert displays to a dict indexed by display.idx
    displays = {}
    for display in jumbotron.displays:
        displays[display['idx']] = attrdict(display)
    jumbotron.displays = displays

    # Open image, rotate and convert if necessary, based on exif tags and mode
    try:
        image = Image.open(image_name)
    except IOError as ioe:
        print(str(ioe), file=sys.stderr)
        return -1
    image = _reorient_image(image)
    if image.mode != 'RGB' or image.mode != 'RGBA':
        image = image.convert('RGB')

    # Calibrate
    _calibrate(jumbotron, jumbotron.displays, image, debug=False, debug_image=False)

    # Send to stdout (to node.js)
    print(json.dumps(jumbotron), file=sys.stdout)

    # Save
    #image.save("calibrate_out.jpg")
    return 0

if __name__ == "__main__":
    import sys
    sys.exit(main(sys.argv))


from flask import Flask
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
import MySQLdb

HOST = 'localhost'
USER = 'root'
PASSWORD = ''
DATABASE = 'ultimate_meal_planner'

app = Flask(__name__)
app.config['SECRET_KEY'] = 'THIS IS THE BEST KEY I EVER HAD'
#mysql = MySQLdb.connect(HOST, USER, PASSWORD ,DATABASE)
app.config['SQLALCHEMY_DATABASE_URI'] = "mysql://root:@localhost/"+DATABASE
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # added just to suppress a warning
ALLOWED_EXTENSIONS = set(['jpg', 'jpeg', 'gif','png'])
db = SQLAlchemy(app)

# Flask-Login login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'  # necessary to tell Flask-Login what the default route is for the login page
login_manager.login_message_category = "info"  # customize the flash message category

app.config.from_object(__name__)
from app import views


import sys

class Solution:
    def threeSumClosest(self, nums: list[int], target: int) -> int:
        diff = sys.maxsize
        solution = 0
        nums = sorted(nums)
        size = len(nums)
        for i in range(size):
            left = i + 1
            right = size - 1
            while left < right:
                result = nums[i] + nums[left] + nums[right]
                if result == target:
                    # found the solution
                    return result
                if result < target:
                    left += 1
                else:
                    right -= 1
                if abs(result - target) < diff:
                    solution = result
                    diff = abs(result - target)
        return solution


import sys
input = sys.stdin.readline
lst =[]
N = int(input())
for i in range(N):
    a , b = input().split()
    lst.append([int(a),b])
rlt = sorted(lst, key=lambda x:x[0])
for i in rlt:
    print(*i)


# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
Dataset = pd.read_csv("lasvegas_tripadvisor.csv",header = 0)

# check if the dataset contains missing values
Dataset.isnull().any().any()

# see the statistics and columns description of dataset
Dataset.describe()
Dataset.info()

#Basic Visualisations
def plot_by(df, column_name, size=(20, 15), sortit=True, horizontal=True):
    by_user_country = df.copy()
    x = by_user_country.groupby(column_name)["Nr. reviews"].agg(sum)
    kind = "barh" if horizontal else "bar"
    if sortit:
        x.sort_values().plot(kind=kind, figsize=size, title="By " + column_name)
    else:
        x.plot(kind=kind, figsize=size, title="By " + column_name)
plot_by(Dataset, "User continent", size=(10, 5))
plot_by(Dataset, "User country", size=(15, 12))
plot_by(Dataset, "Traveler type", size=(10, 5))
plot_by(Dataset, "Review weekday", size=(10, 5), sortit=False, horizontal=False)
plot_by(Dataset, "Score", size=(10, 5), horizontal=False)

#Convert the columns datatype to categorical which have categorical values
for col in ['User country','Period of stay','Traveler type','Pool',
        'Gym','Tennis court','Spa','Casino','Free internet',
        'Hotel name','Hotel stars','User continent','Review month','Review weekday']:
    Dataset[col]=Dataset[col].astype('category')

#Dependent and independent variables
X = Dataset[Dataset.columns.difference(['Score'])]
y = Dataset.iloc[:,4:5].values

#Removing the error in dataset
X.set_value(75,'Member years',np.median(X[['Member years']]))
#X['Hotel stars'] = X['Hotel stars'].apply({'3,5':5, '4,5':5,3:3,4:4,5:5}.get)
#Try  combinations of '3,5' as 3 and 5 with '4,5' as 4 and 5 respectively

# Encoding categorical data
X = pd.get_dummies(X, columns=X.columns[X.dtypes == 'category'], drop_first=True)

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0)
X_plot = X_test
# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

#Restoring the column names of X_train,X_test
X_train = pd.DataFrame(X_train, columns = X.columns)
X_test = pd.DataFrame(X_test,columns = X.columns)

# Fitting SVR to the dataset
from sklearn import svm
regressor = svm.SVR(kernel = 'rbf',epsilon=0.7)
regressor.fit(X_train, y_train)

# Predicting a new result
y_pred = regressor.predict(X_test)

# =============================================================================
# from sklearn.metrics import confusion_matrix
# cm = confusion_matrix(y_test,y_pred)
# =============================================================================
#mean squared error,mean absolute error,mean absolute percentage error in prediction
from sklearn.metrics import mean_squared_error
mse = mean_squared_error(y_test,y_pred)

from sklearn.metrics import mean_absolute_error
mae = mean_absolute_error(y_test,y_pred)

def mean_absolute_percentage_error(y_test, y_pred):
    y_test, y_pred = np.array(y_test), np.array(y_pred)
    return np.mean(np.abs((y_test - y_pred) / y_test)) * 100
mape = mean_absolute_percentage_error(y_test,y_pred)

# -----------------------------Feature Importance----------------------------------
from sklearn.ensemble import RandomForestRegressor
from sklearn.feature_selection import SelectFromModel

# Create a random forest classifier
rgr = RandomForestRegressor(n_estimators=1000, random_state=0, n_jobs=-1)

# Train the classifier
rgr.fit(X_train, y_train)

# Appending the name and gini importance of each feature
feature_imp = []
for feature in zip(X.columns, rgr.feature_importances_):
    feature_imp.append(feature)

# Create a selector object that will use the random forest regressor to identify
# features that have an importance of more than 0.05(5%)
sfm = SelectFromModel(rgr, threshold=0.05)

# Train the selector
sfm.fit(X_train, y_train)

# Print the names of the most important features
for feature_list_index in sfm.get_support(indices=True):
    print(X.columns[feature_list_index])

Feature_imp_dict = {'Helpful votes':feature_imp[0][1],'Hotel stars':feature_imp[1][1],
                    'Member years':feature_imp[2][1],'Nr. Hotel Reviews':feature_imp[3][1],
                    'Nr. Reviews':feature_imp[4][1],'Nr. rooms':feature_imp[5][1]}
Feature_imp_dict.update((x,y*100) for x,y in Feature_imp_dict.items())

#---------------------------Visualising the results------------------------------
l = [1,2,3,4,5,6]
tick_label = ['Helpful votes','Hotel stars','Member years','Nr. Hotel Reviews',
              'Nr. Reviews','Nr. rooms']
h = [Feature_imp_dict['Helpful votes'],Feature_imp_dict['Hotel stars'],Feature_imp_dict['Member years'],Feature_imp_dict['Nr. Hotel Reviews'],
     Feature_imp_dict['Nr. Reviews'],Feature_imp_dict['Nr. rooms']]

plt.figure(figsize = (9,4))
plt.bar(l,h,tick_label=tick_label, align = 'center',
        width=0.5,color=['red','blue','orange','indigo','violet','green'])
plt.xlabel('Features')
plt.ylabel('Percentage of relevance for the model')
plt.title('Most important features in the model')

#Influence of Member years on TripAdvisor score.
z = list(X_plot['Member years'])
count_0,sum_0,count_1,sum_1,count_2,sum_2,count_3,sum_3,count_4,sum_4,count_5,sum_5=0,0,0,0,0,0,0,0,0,0,0,0
for i,data in enumerate(z):
    if(data == 0):
        count_0+=1
        sum_0+=y_pred[i]
    elif(data == 1):
        count_1+=1
        sum_1+=y_pred[i]
    elif(data == 2):
        count_2+=1
        sum_2+=y_pred[i]
    elif(data == 3):
        count_3+=1
        sum_3+=y_pred[i]
    elif(data == 4):
        count_4+=1
        sum_4+=y_pred[i]
    elif(data == 5):
        count_5+=1
        sum_5+=y_pred[i]
Avg_scores = [sum_0/count_0,sum_1/count_1,sum_2/count_2,sum_3/count_3,
              sum_4/count_4,sum_5/count_5]
plt.plot([0,1,2,3,4,5],Avg_scores,marker='s',color='b')
plt.xlabel("Member Years",fontsize=10, fontweight='bold')
plt.ylabel("Trip Advisor Score",fontsize=10, fontweight='bold')
plt.title("Influence of member years on Trip advisor score",fontsize=14, fontweight='bold')


# 1. Write a Python program which accepts the radius of a circle from the user and compute the area.
# Developed by : Yamini Rathod C0796390
# Date : 16-05-2021

# Method 3 : Using Python tkinter feature

from tkinter import *
from tkinter import messagebox

class myCalculator:
    def __init__(self):
        self.window = Tk()
        self.window.title("My Calculator")
        self.window.geometry("500x400")

        self.top_frame = Frame()
        self.bottom_frame = Frame()
        self.result_frame = Frame()

        self.welcome_label1 = Label(self.top_frame, text="Welcome to Reverse Name Program")
        self.welcome_label2 = Label(self.top_frame, text="Designed By: Yamini Rathod C0796390")

        self.prompt_label1 = Label(self.top_frame, text="Please enter the first name : ")
        self.fname = Entry(self.top_frame)

        self.prompt_label2 = Label(self.top_frame, text="Please enter the last name : ")
        self.lname = Entry(self.top_frame)

        self.calc_buttom1 = Button(self.bottom_frame, text="Get Reverse", padx=10, command=self.rev)
        self.cancel_button = Button(self.bottom_frame, text="Exit", padx=10, command=self.window.destroy)

        self.result = StringVar()
        self.result.set("Result: N/A")
        self.result_label = Label(self.result_frame, textvariable=self.result, bg="yellow", fg="green")

        self.welcome_label1.pack(padx=10, pady=10)
        self.welcome_label2.pack(padx=10, pady=10)
        self.prompt_label1.pack(padx=10, pady=10)
        self.fname.pack(padx=10, pady=10)
        self.prompt_label2.pack(padx=10, pady=10)
        self.lname.pack(padx=10, pady=10)

        self.calc_buttom1.pack(side="left", padx=10, pady=10)
        self.cancel_button.pack(side="left", padx=10, pady=10)
        self.result_label.pack(side="left", padx=10, pady=10)

        self.top_frame.pack()
        self.bottom_frame.pack()
        self.result_frame.pack()

        mainloop()

    def rev(self):
        try:
            firstname = self.fname.get()
            lastname = self.lname.get()

            self.result.set(f'The reverse output is : {lastname} {firstname}')
        except:
            messagebox.showerror("Input Error", "The input is invalid! Please try again!")

myWindow = myCalculator()