import sys
from datetime import date
from os import system

sys.path.append('./classes')

from classes.Card import Card
from classes.Person import Person
from classes.bankomat import ATM
from loader import load

if __name__ =='__main__':
    karta=Card(input("Karta nomi:"),int(input("Balansi:")),int(input("Parol o'ylang:")))
    odam=Person(input("Ismingiz:"),karta,int(input("Naxt pulingiz qancha:")))
    bank1=ATM(1400000,'NBU')
    bank1.parol_tekshir(odam)
    load()
    print('''[1]--> Balansni tekshirish
[2]--> Naqd pul yechish
[3]--> Parolni o'zgartirish
[4]--> Kartaga pul o'tkazish
[5]--> Naqd pul balansi
[6]--> Chiqish''')
    while True:
        tanlov=int(input(">>>"))
        if tanlov ==1:
            print(karta.get_balans())
        elif tanlov==2:
            qancha=int(input("Qancha pul yechasiz:"))
            if qancha <=karta.get_balans() and qancha<=bank1.get_naxt_pul():
                karta.set_balans_minus(qancha)
                bank1.naxt_pul_minus(qancha)
                odam.karmon_plus(qancha)
                print(f'''           Chek
    Pul yechilgan sana:{date.today()}
    {qancha} pul yechildi
    Balans:{karta.get_balans()} so'm''')
            else:
                print("Mablag' yetarli emas")
        elif tanlov==3:
            karta.set_parol(input("Yangi parol:"))

        elif tanlov==4:
            qiymat=int(input('Qancha pul tashlamoqchisiz:'))
            if qiymat<=odam.karmon:
                bank1.naxt_pul_plus(qiymat)
                odam.karmon_minus(qiymat)
                karta.set_balans_plus(qiymat)
            else:
                print("Mablag' yetarli emas")
        elif tanlov==5:
            print(odam.karmon)
        elif tanlov==6:
            system('clear')
            exit()
        else:
            print("Tushunarsiz buyruq!!")


from database import connect, getRecentRun, getRandomExample, processExample
from model import getModel, getParameters, getGraph, getActivations
from classes import classToCode
import tensorflow as tf

def predict(image):
  data = getRecentRun()

  predictions, x, y, keep_prob = getModel()
  graph = getGraph()
  conv1_activations = getActivations()
  W_conv1, b_conv1, W_conv2, b_conv2, W_fc1, b_fc1, W_fc2, b_fc2 = getParameters()

  feed = {
    x: [image],
    keep_prob: 1.0,
    W_conv1: data['parameters']['W_conv1'],
    b_conv1: data['parameters']['b_conv1'],
    W_conv2: data['parameters']['W_conv2'],
    b_conv2: data['parameters']['b_conv2'],
    W_fc1: data['parameters']['W_fc1'],
    b_fc1: data['parameters']['b_fc1'],
    W_fc2: data['parameters']['W_fc2'],
    b_fc2: data['parameters']['b_fc2'],
  }

  T_y_probs = tf.nn.softmax(predictions)

  # Get all predictions in order of probability
  T_top_predictions = tf.nn.top_k(T_y_probs, 62)

  with tf.Session(graph=graph) as session:
    y_probs, top, activations = session.run(
      [T_y_probs, T_top_predictions, conv1_activations],
      feed_dict=feed
    )
    values, indices = top

    result = []
    for confidence, index in zip(values[0], indices[0]):
      result.append({
        'charcode': classToCode[index],
        'confidence': str(confidence)
      })

    session.close()

    return result, activations.tolist()[0]


import sys

fruit_list = [[0] * 50 for i in range(40)]

N = int(sys.stdin.readline().strip())
for i in range(N):
    # 读取每一行
    line = sys.stdin.readline().strip()
    # 把每一行的数字分隔后转化成int列表
    point = list(map(int, line.split()))
    fruit_list[point[0]][point[1]] = 1


from django.urls import path

from . import views     # it means - 'from all import views'

urlpatterns = [
    path('',views.index, name='index'),
    path('add',views.addition, name='add'),
    path("register", views.register_request, name="register"),
    path("login", views.login_request, name="login"),
    path("logout", views.logout_request, name= "logout"),

]

# whenever 'localhost:8000' will be called, function named 'index' will be called that is present in 'views.py' file
# This will happen for all other routes as well


# Escreva uma função em Python que receba a base e a altura de um triângulo e retorne sua área (A = (base x altura) / 2). A função deve receber dois parâmetros do tipo float e retornar a área com o tipo float.

base = float(input("Informe a base: "))
altura = float(input("Informe a base: "))

def areaTriangulo(base, altura):
    A = base * altura / 2
    return A

valor_soma = areaTriangulo(base, altura)
print("A área do triângulo é:%.2f" % (valor_soma))


import io
import pickle

import numpy as np
import os.path
import sqlite3
from sqlite3 import Connection
from typing import Generator, Optional

from galleries import files_utils
from galleries.collections.stream_dictionary import StreamDictionary
from galleries.data_read_write.idata_reader_writer import IDataReaderWriter
from galleries.data_read_write.utils_file_data_readers_writers import *

def adapt_array(arr):
    """
    https://stackoverflow.com/a/18622264/9464297
    """
    out = io.BytesIO()
    np.save(out, arr)
    out.seek(0)
    return sqlite3.Binary(out.read())

def convert_array(text):
    out = io.BytesIO(text)
    out.seek(0)
    return np.load(out)

# Converts np.array to TEXT when inserting
sqlite3.register_adapter(np.ndarray, adapt_array)
# Converts TEXT to np.array when selecting
sqlite3.register_converter("array", convert_array)

class SqliteDataReaderWriter(IDataReaderWriter):
    TABLE_NAME = "Data"

    def __init__(self, data_identifier, root_folder: str, file_path: str = None, batch_size=100000):
        super().__init__(data_identifier)
        self._root_folder = root_folder
        if file_path is None:
            self.set_data_identifier(data_identifier)
        else:
            self._file_path = file_path

        self._batch_size = batch_size
        self._connection: Optional[Connection] = None

    def set_data_identifier(self, data_identifier: DataIdentifier):
        indices = read_index_list(self._root_folder, self._data_identifier)
        add_generator_to_indices_if_not_exists(self._data_identifier, indices)
        write_indices(self._root_folder, self._data_identifier, indices)
        file_path = get_data_path(self._root_folder, self._data_identifier, indices)
        files_utils.create_file_if_doesnt_exist(file_path)
        self._file_path = file_path

    def read_all_data(self) -> Generator:
        self.release()
        self._connect(self._file_path)
        cur = self._connection.cursor()
        try:
            data = cur.execute("SELECT * FROM Data")
            for d in data:
                yield pickle.loads(d[0])
        except:
            pass
        finally:
            self.release()

    def read_data(self, indices) -> Generator:
        sd = StreamDictionary(self.read_all_data, self._batch_size)
        for index in indices:
            data, success = sd.try_get_item(index)
            yield index, data

    def write_data(self, data: Generator, notify_function=None, notify_rate=100):
        self.release()
        exists = os.path.exists(self._file_path)
        if not exists:
            files_utils.create_dir_of_file(self._file_path)

        try:
            self._connect(self._file_path)
            cur = self._connection.cursor()
            exists_table = False
            try:
                tables = cur.execute("""SELECT name FROM sqlite_master WHERE type='table' AND name='Data'; """).fetchall()
                exists_table = tables != []
            except sqlite3.OperationalError:
                pass
            if not exists_table:
                cur.execute("CREATE TABLE Data (data BLOB)")

            def write(d):
                bd = pickle.dumps(d)
                cur.execute("INSERT INTO Data (data) VALUES(?)", [bd])
            self.write_data_with_notifications(data, write, notify_function, notify_rate)

            self._connection.commit()
        finally:
            self.release()

    def clear_data(self):
        self._connect(self._file_path)
        cur = self._connection.cursor()
        cur.execute("DELETE FROM Data")

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

    def _connect(self, file_path):
        self.release()
        self._connection = sqlite3.connect(file_path, detect_types=sqlite3.PARSE_DECLTYPES)


#!/usr/bin/env python3

import click
import json

def get_conversations(data):
    """Return dict of unique conversation IDs and their participants."""

    convos = {}
    for conversation in data["conversation_state"]:
        conversation_id = conversation["conversation_id"]["id"]
        convo_participants = []
        for participant in conversation["conversation_state"]["conversation"][
            "participant_data"
        ]:
            try:
                convo_participants.append(participant["fallback_name"])
            except KeyError:
                pass
        convos[conversation_id] = convo_participants

    return convos

def generate_corpus(data, convo_id):
    """Return list containing all of the messages for the supplied conversation ID."""
    corpus = []
    states = data["conversation_state"]
    for state in states:
        conversation_state = state["conversation_state"]
        if "event" in conversation_state:
            conversations = conversation_state["event"]
            for conversation in conversations:
                if "chat_message" in conversation:
                    message_content = conversation["chat_message"]["message_content"]
                    if "segment" in message_content:
                        segment = message_content["segment"]
                        for line in segment:
                            conversation_id = conversation["conversation_id"]["id"]
                            if conversation_id == convo_id:
                                # timestamp_us = int(conversation['timestamp'])  # epoch time in microseconds
                                # timestamp = dt.datetime.fromtimestamp(timestamp_us/1000000)  # convert to epoch secs
                                # timestamp_str = timestamp.strftime("%Y%m%d_%Hh%Mm%Ss.%f")
                                if "text" in line:
                                    message_text = line["text"].strip()
                                    # If empty message then skip this pass of the loop
                                    if not message_text:
                                        continue
                                    # Append period if sentence is not otherwise punctuated
                                    if not message_text.endswith((".", "!", "?")):
                                        message_text += "."
                                    # Capitalise first letter
                                    message_text = (
                                        message_text[0].upper() + message_text[1:]
                                    )
                                    corpus.append(message_text)
    return corpus

@click.command()
@click.argument("jsonfile", type=click.Path(exists=True))
def main(jsonfile):
    """Extracts a specific conversation from Hangouts data exported from Google Takeout, and readies it for use by Wynbot."""
    with open(jsonfile, "rb") as file:
        data = json.load(file)

    # Get list of conversations and choose which one to use for data extraction. This may take some time.
    convos = get_conversations(data)
    selection_choices = {}
    print("{:<3} {:<35} {:<50}".format("No.", "Convo ID", "Participants"))
    for index, (key, value) in enumerate(convos.items(), start=1):
        print(
            "{num:<3} {convo_id:<35} {participants}".format(
                num=index, convo_id=key, participants=", ".join(value)
            )
        )
        selection_choices[index] = key
    selection = int(input("Enter no. of conversation to use: "))
    selected_convo_id = selection_choices[selection]

    # Generate corpus of message text using the chosen conversation
    corpus = generate_corpus(data, selected_convo_id)

    # Output text file with each message on a new line.
    with open("corpus.txt", "w", encoding="utf-8") as file:
        for line in corpus:
            file.write("{0}\n".format(line))

    print('Corpus extracted to "corpus.txt".')

if __name__ == "__main__":
    main()


# coding=utf-8

'''
对二叉树的节点来说，有本身的值域，有指向左孩子和右孩子的两个指针；
对双向链表的节点来说，有本身的值域，有指向上一个节点和下一个节点的指针；
在结构上，两种结构有相似性。
现在有一颗搜索二叉树，请将其转换为一个有序的双向链表
示例树：
          6
    4           7
  2    5            9
1   3           8
'''
class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left, self.right = None, None

def inOrder(root):
    if not root:
        return []
    stack = []
    nodes = []
    node = root
    while node or stack:
        if node:
            stack.append(node)
            node = node.left
        else:
            node = stack.pop(-1)
            nodes.append(node)
            node = node.right
    return nodes

def convert(root):
    nodes = inOrder(root)
    if not nodes:
        return root

    head = nodes.pop(0)
    pre = head
    pre.left = None

    while nodes:
        cur = nodes.pop(0)
        pre.right = cur
        cur.left = pre
        pre = cur

    pre.right = None
    return head

if __name__ == '__main__':
    node1 = TreeNode(1)
    node2 = TreeNode(2)
    node3 = TreeNode(3)
    node4 = TreeNode(4)
    node5 = TreeNode(5)
    node6 = TreeNode(6)
    node7 = TreeNode(7)
    node8 = TreeNode(8)
    node9 = TreeNode(9)
    node6.left = node4
    node6.right = node7
    node4.left = node2
    node2.right = node5
    node2.left = node1
    node2.right = node3
    node7.right = node9
    node9.left = node8
    head = convert(node6)
    while head:
        print(head.val, end='\t')
        head = head.right

程序员面试指南/第二章-链表/15-将搜索二叉树转换成双向链表.py

15-将搜索二叉树转换成双向链表.py


import json
from flask import Flask, request
from database.tables import AbstractTable

app = Flask(__name__)

@app.route('/', methods=['POST', 'GET'])
def run_post():
    try:
        data = json.loads(request.get_data(as_text=True))

        table_data = AbstractTable().transaction(data['request'], data['table'], data['data'])

        return json.dumps(dict({
                'table': data['table'],
                'data': table_data
            }))

    except Exception as e:
        print(e)
        return e.__str__()

if __name__ == '__main__':
    app.run(host='0.0.0.0',
            port=8080)


#Order of execution: #10
def evaluate_arrays(a1, a2):

    K = set(np.asarray(a1))
    GT = set(np.asarray(a2))

    set_intersection = len(list(K.intersection(GT)))
    denominator = len(list(K))
    if denominator > 0:
        precision = set_intersection / len(list(K))
    else:
        precision = 0
    # print(precision)
    denominator = len(list(GT))
    if denominator > 0:
        recall = set_intersection / len(list(GT))
    else:
        recall = 0
    # print(recall)

    accuracy = 0
    if set_intersection > 0:
        accuracy = 1
    # print(accuracy)
    return [precision, recall, accuracy]

import numpy as np
actual = np.load('../Features/HashtagsLabels.bin.npy')
import random
random.seed(4321)
my_random_sample = random.sample(range(actual.shape[0]), 5000)

actual = actual[my_random_sample,:]

res_files = ['results_02_bin', 'results_3_bin', 'results_5_bin', 'results_75_bin', 'results_95_bin']

import pickle

class myFloat( float ):
    def __str__(self):
        return "%.2f"%self

file_to_save_res = 'evaluation_all_hastags.txt'
for file_id in range(len(res_files)):
    with open('../TransferLearning/' + res_files[file_id], "rb") as fp:  # Unpickling
        print(res_files[file_id])
        result = pickle.load(fp)
    for how_much_res in [1,2,3,4,5,100]:
        precision5 = 0
        recall5 = 0
        accuracy5 = 0
        print(how_much_res)
        for my_id in range(actual.shape[0]):
            my_res = np.asarray(result[my_id])
            my_res = my_res[0:how_much_res]

            my_y = actual[my_id]
            my_y = np.nonzero(my_y)[0]
            evaluate_res = evaluate_arrays(my_res, my_y)

            precision5 = precision5 + evaluate_res[0]
            recall5 = recall5 + evaluate_res[1]
            accuracy5 = accuracy5 + evaluate_res[2]

        precision5 = precision5 / actual.shape[0]
        recall5 = recall5 / actual.shape[0]
        accuracy5 = accuracy5 / actual.shape[0]
        f1 = 2 * precision5 * recall5 / (precision5 + recall5)

        precision5 = str(myFloat(precision5 * 100))
        recall5 = str(myFloat(recall5 * 100))
        accuracy5 = str(myFloat(accuracy5 * 100))
        f1 = str(myFloat(f1 * 100))

        file_object = open(file_to_save_res, 'a')
        file_object.write('No more than ' + str(how_much_res) + "&" + precision5 + "&" + recall5 + "&" + accuracy5 + "&" + f1 + "\\\\" + '\n')


from heapq import heappop, heapify, heappush

class MyKey:
    def __init__(self, num, word):
        self.num = num
        self.word = word

    def __lt__(self, other):
        return self.num > other.num or (self.num == other.num and self.word < other.word)

class MyKey2:
    def __init__(self, num, word):
        self.num = num
        self.word = word

    def __lt__(self, other):
        return self.num < other.num or (self.num == other.num and self.word > other.word)

def topKFrequent(words, k):
    score = dict()
    for i in range(len(words)):
        if words[i] not in score:
            score[words[i]] = 1
        else:
            score[words[i]] += 1
    heap = []
    heapify(heap)
    for x in score:
        if len(heap) < k:
            heappush(heap, (score[x], x))
        else:
            heap.sort(key=lambda pair: MyKey2(pair[0], pair[1]))
            curr = heappop(heap)
            if curr[0] > score[x] or (curr[0] == score[x] and curr[1] < x):
                heappush(heap, curr)
            else:
                heappush(heap, (score[x], x))
    heap.sort(key=lambda pair: MyKey(pair[0], pair[1]))
    for i in range(len(heap)):
        heap[i] = heap[i][1]
    return heap

# words = ["aaa","aa","a"]
# k = 2

words = ["the", "day", "is", "sunny", "the", "the", "the", "sunny", "is", "is"]
k = 4
print(topKFrequent(words, k))
# heap = [(1, 'aa'), (1, 'aaa')]
# heap.sort(key=lambda pair: MyKey2(pair[0], pair[1]))
# print(heap)


import sys
import os
from PIL import Image

img_folder = sys.argv[1]
op_folder = sys.argv[2]

def jpg2png(a, b):
    if not os.path.exists(b):
        os.makedirs(b)

    for filename in os.listdir(a):
        img = Image.open(f'{a}/{filename}')
        name = os.path.splitext()[0]
        img.save(f'{b}/{name}.png', 'png')

    return 'all done!'

# Run Module
print(jpg2png(img_folder, op_folder))


import unittest
import os
from appium import webdriver
from time import sleep

PATH = lambda p: os.path.abspath(
    os.path.dirname(__file__), p)

class test_leroy(unittest.TestCase):

    def setUp(self):
        desired_caps = {}
        desired_caps['platformName'] = 'Android'
        desired_caps['deviceName'] = 'LG K50'
        # desired_caps['app'] = PATH('leroymerlin.apk')
        desired_caps['udid'] = 'LMX5209PCAB6S8R8BA'
        desired_caps['appPackage'] = 'com.mec.leroy'
        desired_caps['appActivity'] = 'com.mec.leroy.MainActivity'

        self.driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
        self.driver.implicitly_wait(5)

    def tearDown(self):
        self.driver.quit()

    def testApp1(self):
        # getting to item site
        driver = self.driver
        button = driver.find_element_by_xpath(
                    "//android.widget.TextView[@bounds='[91,54][182,128]']")
        button.click()
        sleep(3)
        search = driver.find_element_by_xpath("//*[@text='Szukaj']")
        search.send_keys("beton architektoniczny")
        driver.find_element_by_xpath(
            "//android.widget.TextView[@bounds='[28,153][95,222]']").click()
        sleep(3)
        driver.find_element_by_xpath(
            "//android.widget.ImageView[@bounds='[18,508][193,683]']").click()
        sleep(3)

        # getting price of an item
        priceField = driver.find_element_by_xpath(
            "//android.widget.TextView[@bounds='[28,891][312,985]']")
        price = priceField.text
        print(price)

        # Assert
        self.assertEqual("119 zł/opak. ", price)

if __name__ == 'main':
    suite = unittest.TestLoader().loadTestsFromTestCase(test_leroy)
    unittest.TextTestRunner(verbosity=2).run(suite)


#!/usr/bin/python3

import gi
from Model import Model
gi.require_version('Gtk', '3.0')

from gi.repository import Gtk, GObject
from TCP.client import Client
from codes import *
import sys
from threading import Thread
from server import server

class Controller(object):

    def __init__(self, model):
        """
        Initialites the whole app
        :param model: Instance of the desired model
        """
        self._model = model
        self._client = None
        self.username = ""

        self._model.view.connect('send', self.send)
        self._model.view.connect('destroy', Gtk.main_quit)

        self._model.view.show_all()
        try:
            if sys.argv[1] == "-s":
                self._model.set_is_server(True)
                def _target():
                    try:
                        s = server()
                        s.run()
                    except:
                        self._model.set_is_server(False)
                thread = Thread(target=_target)
                thread.daemon = True
                thread.start()
        except:
            print("Server could not be lauched")

    def send(self, *args):
        """
        Parses the typed command typed on the send entry.
        :param args:
        :return:
        """
        args = args[1]
        if args[0] == COMAND_SCAPE_CHAR:

            command = args[1:].split(' ')
            if len(command) > 1:
                arguments = command[1]
            command = command[0]

            if command == "open":
                try:
                    self.username = arguments.split('@')[0]
                    ip = arguments.split('@')[1].split(':')[0]
                    port = int(arguments.split('@')[1].split(':')[1])

                    self._client = Client(self.username, ip, port)
                    self._client.start(self._model.add_output)
                    self._client.listen(self.receive, self._model.add_output)
                except:
                    self._model.add_err_output("Error while connecting to the server.")

            elif command == "help":
                try:
                    with open("/usr/share/PyChat/var/help.outpt", 'r') as fp:
                        text=fp.read()
                    self._model.add_output(text)
                except:
                    self._model.add_err_output("Error while reading help file")
            elif command == "server":
                self._model.add_output(str(self._model.is_server))
            elif command == "close":
                self.close()
            elif command == "save":
                self._save_conver(path=arguments)
            else:
                self._model.add_err_output("Command not found.")

        else:
            self._client.send_message(args)
            self._model.add_message(self.username, args)

    def receive(self, username, message):
        """
        Saves the received message to the model
        :param username: Str with the uname of the src
        :param message: Str with the actual message
        :return:
        """
        self._model.add_message(username, message)

    def _save_conver(self, path="./history.txt"):
        """
        Saves the conversation to the given path. It will overwrite!
        :param path: str cintaining the full or relative path to the file.
        :return:
        """
        try:
            with open(path, 'w') as fp:
                fp.write(self._model.report_messages())
            self._model.add_output("Conversation saved succesfuly")
        except:
            self._model.add_err_output("Error while saving the conversation")

    def close(self):
        """
        If open, closes the TCP connection and clears its variables.
        :return:
        """
        if self._client is not None:
            self._client.disconnect(self._model.add_output)
            self._client = None
            self.username = ""

if __name__ == '__main__':

    app = Controller(Model())
    Gtk.main()
    app.close()


import pytest

@pytest.mark.math
def test():
    a = 1
    b = 2
    c = 3
    assert a+b == c

@pytest.mark.math
def test1():
    a = 1
    b = 2
    c = 3
    assert a+b == c

@pytest.mark.math
def test_devide_by_zero():
    with pytest.raises(ZeroDivisionError) as e:
        num = 1/0
    assert 'division by zero' in str(e.value)

#         Parametrize test functions
product = [
    (2,3,6),
    (1,99,99),
    (0,99,0),
    (3,-2,-6),
    (-2,-2,4),
    (2,2,4)
]

@pytest.mark.math
@pytest.mark.parametrize('a,b,product',product)
def test_parameterize_func(a,b,product):
    assert a*b == product

@pytest.mark.parametrize("a,b,add",([(1,2,3),(2,1,3)]))
def test_parametrize_add(a,b,add):
    assert a+b == add

def test_divide_by_zero():
  with pytest.raises(ZeroDivisionError) as e:
    num = 1 / 0
  assert 'division by zero' in str(e.value)


import random

import drum_constants
import chord_classes
import mido_constants
import scale_constants
import errors

from mido_constants import *

CHORD_LENGTHS = [HALF_NOTE_LENGTH, WHOLE_NOTE_LENGTH]

class MetaDataGenerator:
	def __init__(self):
		self.key = self._generate_key()
		self.tempo = self._generate_tempo()
		self.time_signature = (4, 4)

	def _generate_key(self):
		key = scale_constants.KEYS[random.randrange(len(scale_constants.KEYS))]

		if key in ("B", "E"):
			return key + "m"

		if key in ("F"):
			return key

		mode = scale_constants.MODES[random.randrange(len(scale_constants.MODES))]

		return key + mode

	def _generate_tempo(self):
		tempo_range = list(range(60, 140)) + list(range(80, 120))

		return tempo_range[random.randrange(len(tempo_range))]

class DataGenerator:
	def __init__(self, meta_data, nb_of_bars):
		self.meta_data = meta_data
		self.tick_length = TICK_SIZE * meta_data.time_signature[0] * nb_of_bars
		self.tick_length_left = self.tick_length

class ChordProgressionGenerator(DataGenerator):
	def __init__(self, meta_data, nb_of_bars=4):
		super().__init__(meta_data, nb_of_bars)

		self.scale = scale_constants.SCALES[meta_data.key]
		self.scale_notes = [note for note in self.scale]

		self.previous_note = None
		self.chord_progression = self._get_chord_progression()

	def get_chord_progression(self):
		return self.chord_progression

	def _get_chord_progression(self):
		chord_progression = []

		while self.tick_length_left > 0:
			chord_progression.append(self._get_chord(len(chord_progression) == 0))

		if self.scale_notes[4] in chord_progression[-1][0] and "m" in chord_progression[-1][0]:
			chord_progression[-1][0] = self.scale_notes[4]

		return chord_progression

	def _get_chord(self, is_first_chord):
		note = self.scale_notes[0] if is_first_chord else self._get_random_chord_note()
		chord_attr = self.scale[note]

		while chord_attr == "mb5" or note == self.previous_note:
			note = self._get_random_chord_note()
			chord_attr = self.scale[note]

		self.previous_note = note
		return [note + chord_attr, self._get_random_chord_duration()]

	def _get_random_chord_note(self):
		return self.scale_notes[random.randrange(len(self.scale_notes))]

	def _get_random_chord_duration(self):
		duration = min(CHORD_LENGTHS[random.randrange(len(CHORD_LENGTHS))], self.tick_length_left)
		self.tick_length_left -= duration
		return duration

class DrumPatternGenerator(DataGenerator):
	NOTE_DURATION = EIGHTH_NOTE_LENGTH

	def __init__(self, meta_data, nb_of_bars=4):
		super().__init__(meta_data, nb_of_bars)

		self.current_position = 0
		self.drum_pattern = self._get_drum_pattern()

	def get_drum_pattern(self):
		return self.drum_pattern

	def _get_drum_pattern(self):
		drum_pattern = []

		while self.tick_length_left > 0:
			drum_pattern.append(self._get_hit())
			self.tick_length_left -= self.NOTE_DURATION

		return drum_pattern

	def _get_hit(self):
		if self.meta_data.tempo < 100:
			self.NOTE_DURATION = SIXTEENTH_NOTE_LENGTH

		hit = self._get_hit_func()

		self.current_position += self.NOTE_DURATION
		return (hit, self.NOTE_DURATION)

	def _get_hit_func(self):
		func = self._get_simple_time_hit

		if self.NOTE_DURATION == SIXTEENTH_NOTE_LENGTH:
			func = self._get_double_time_hit

		return func()

	def _get_simple_time_hit(self):
		return self._get_full_hit()

	def _get_double_time_hit(self):
		base_multiplier = 8
		snare_multiplier = 4

		return self._get_full_hit(base_multiplier=base_multiplier, snare_multiplier=snare_multiplier)

	def _get_full_hit(self, base_multiplier=4,  kick_multiplier=0, snare_multiplier=2):
		hit = []

		if self.current_position % (self.NOTE_DURATION * base_multiplier) == self.NOTE_DURATION * kick_multiplier:
			hit.append(drum_constants.KICK)

		if self.current_position % (self.NOTE_DURATION * base_multiplier) == self.NOTE_DURATION * snare_multiplier:
			hit.append(drum_constants.SNARE)

		hit.append(drum_constants.HH_CLOSED)

		return hit

class SimpleMelodyGenerator(DataGenerator):
	def __init__(self, chords, meta_data, nb_of_bars=4):
		super().__init__(meta_data, nb_of_bars)
		self.chords = self._get_chord_dict(chords)
		self.tick_iterator = 0
		print(self.chords)

	def get_melody(self):
		melody = []

		while self.tick_length_left > 0:
			note = self._get_note()
			melody.append(note)
			self.tick_iterator += note[1]
			self.tick_length_left -= note[1]

		print(melody)
		return melody

	def _get_note(self, previous_note=None):
		note = ["".join([char for char in self._get_current_chord() if char != "m"]) + "3"]
		length = self._get_note_length()

		return (note, length)

	def _get_current_chord(self):
		reversed_chords = list(self.chords.items())
		reversed_chords.reverse()
		reversed_chords = {key : value for (key, value) in reversed_chords}

		for i, tick_position in enumerate(reversed_chords):
			if self.tick_iterator >= tick_position or i == len(self.chords):
				print (self.tick_iterator)
				return self.chords[tick_position]

	def _get_note_length(self):
		return mido_constants.QUARTER_NOTE_LENGTH

	def _get_chord_dict(self, chords):
		tick_iterator = 0
		chord_dict = {}

		for chord in chords:
			chord_dict[tick_iterator] = chord[0]
			tick_iterator += chord[1]

		return chord_dict

if __name__ == '__main__':
	meta_data = MetaDataGenerator()
	chord_progression = ChordProgressionGenerator(meta_data)
	print(chord_progression.get_chord_progression())


#********* PROYECTO 1 TIC-TAC-TOE ***********

import random   #libreria para generar numeros aleatorios

def DisplayBoard(board):
#
# la función acepta un parámetro el cual contiene el estado actual del tablero
# y lo muestra en la consola
#
    tablero=board
    for i in range(3):
        print("+-------+-------+-------+")
        for j in range(5):
            if j==2:
                if i==0:
                    print("|  ",tablero[i][i],"  |  ",tablero[i][i+1],"  |  ",tablero[i][i+2],"  |")
                if i==1:
                    print("|  ",tablero[i][i-1],"  |  ",tablero[i][i],"  |  ",tablero[i][i+1],"  |")
                if i==2:
                    print("|  ",tablero[i][i-2],"  |  ",tablero[i][i-1],"  |  ",tablero[i][i],"  |")

            print("|       |       |       |")
    print("+-------+-------+-------+")

def EnterMove(board):
#
# la función acepta el estado actual del tablero y pregunta al usuario acerca de su movimiento,
# verifica la entrada y actualiza el tablero acorde a la decisión del usuario
#
    tablero=board
    num=int(input("¿que casilla quieres tirar?  __"))
    if num==1:
        tablero[0][0]="O"
    elif num==2:
        tablero[0][1]="O"
    elif num==3:
        tablero[0][2]="O"
    elif num==4:
        tablero[1][0]="O"
    elif num==6:
        tablero[1][2]="O"
    elif num==7:
        tablero[2][0]="O"
    elif num==8:
        tablero[2][1]="O"
    elif num==9:
        tablero[2][2]="O"
    return tablero

def MakeListOfFreeFields(board):
#
# la función examina el tablero y construye una lista de todos los cuadros vacíos
# la lista esta compuesta por tuplas, cada tupla es un par de números que indican la fila y columna
#
    tablero=board
    registro=[]
    for i in range(3):
        for j in range(3):
            if tablero[i][j]=="X" or tablero[i][j]=="O":
                continue
            registro.append((i,j))
    return registro

def VictoryFor(board, sign):
#
# la función analiza el estatus del tablero para verificar si
# el jugador que utiliza las 'O's o las 'X's ha ganado el juego
#
    tablero=board
    if sign=="X":
        if ((tablero[0][0]=="X" and tablero[0][1]=="X" and tablero[0][2]=="X") or
            (tablero[1][0]=="X" and tablero[1][1]=="X" and tablero[1][2]=="X") or
            (tablero[2][0]=="X" and tablero[2][1]=="X" and tablero[2][2]=="X") or
            (tablero[0][0]=="X" and tablero[1][0]=="X" and tablero[2][0]=="X") or
            (tablero[0][1]=="X" and tablero[1][1]=="X" and tablero[2][1]=="X") or
            (tablero[0][2]=="X" and tablero[1][2]=="X" and tablero[2][2]=="X") or
            (tablero[0][0]=="X" and tablero[1][1]=="X" and tablero[2][2]=="X") or
            (tablero[0][2]=="X" and tablero[1][1]=="X" and tablero[2][0]=="X")):
            print("HAS PERDIDO")
            return True

    elif sign=="O":
        if ((tablero[0][0]=="O" and tablero[0][1]=="O" and tablero[0][2]=="O") or
            (tablero[1][0]=="O" and tablero[1][1]=="O" and tablero[1][2]=="O") or
            (tablero[2][0]=="O" and tablero[2][1]=="O" and tablero[2][2]=="O") or
            (tablero[0][0]=="O" and tablero[1][0]=="O" and tablero[2][0]=="O") or
            (tablero[0][1]=="O" and tablero[1][1]=="O" and tablero[2][1]=="O") or
            (tablero[0][2]=="O" and tablero[1][2]=="O" and tablero[2][2]=="O") or
            (tablero[0][0]=="O" and tablero[1][1]=="O" and tablero[2][2]=="O") or
            (tablero[0][2]=="O" and tablero[1][1]=="O" and tablero[2][0]=="O")):
            print("HAS GANADO")
            return True
    else:
        return False

def DrawMove(board):
#
# la función dibuja el movimiento de la maquina y actualiza el tablero
#
    tablero=board
    casillalibre=MakeListOfFreeFields(tablero)
    tableroApoyo=[]
    for i,j in casillalibre:
        tableroApoyo.append(tablero[i][j])

    num=random.choice(tableroApoyo)

    if num==1:
        tablero[0][0]="X"
    elif num==2:
        tablero[0][1]="X"
    elif num==3:
        tablero[0][2]="X"
    elif num==4:
        tablero[1][0]="X"
    elif num==6:
        tablero[1][2]="X"
    elif num==7:
        tablero[2][0]="X"
    elif num==8:
        tablero[2][1]="X"
    elif num==9:
        tablero[2][2]="X"
    return tablero

tablero=[1,2,3],[4,"X",6],[7,8,9]
conta=0
a=False
DisplayBoard(tablero)
while a!=True:
    tablero=EnterMove(tablero)
    DisplayBoard(tablero)
    a=VictoryFor(tablero,"O")
    if a==True:
        break
    tablero=DrawMove(tablero)
    DisplayBoard(tablero)
    a=VictoryFor(tablero,"X")
    if a==True:
        break
    conta+=2
    if conta==8:
        a=True
        print("EMPATE")


from numpy import array as npy_array
from numpy import arange as npy_arange
from numpy import frombuffer as npy_frombuffer

import matplotlib.pyplot as plt
from matplotlib import use as plot_backend

plot_backend("Agg")

__all__ = ["Graph"]

class Graph:
    def __init__(self, saveIn="graph.png"):
        self.__figure = plt.figure(figsize=(8, 8))

        self.__ax_1 = self.__figure.add_subplot(label="1")
        self.__ax_2 = self.__figure.add_subplot(label="2", frame_on=False)

        self.__ax_1.set_title("Desempenho do Agente")
        self.__ax_1.set_xlabel("Episódios", color="k")
        self.__ax_1.set_ylabel("Epsilon", color="k")
        self.__ax_1.tick_params(axis="x", colors="k")
        self.__ax_1.tick_params(axis="y", colors="k")

        self.__ax_2.axes.get_xaxis().set_visible(False)
        self.__ax_2.yaxis.tick_right()

        self.__ax_2.set_ylabel("Pontuação", color="k")
        self.__ax_2.yaxis.set_label_position("right")
        self.__ax_2.tick_params(axis="y", colors="k")

        self.__saveIn = saveIn

    @property
    def saveIn(self):
        return self.__saveIn

    def plot(self, x, y1, y2, start=False):
        if not start:
            x = npy_arange(x + 1)

            self.__ax_1.plot(x, npy_array(y1), color="c")
            self.__ax_2.scatter(x, npy_array(y2), color="r")

            img = self.__convertFigToArray()

        else:
            img = self.__convertFigToArray()

        return img

    def __convertFigToArray(self):
        self.__figure.canvas.draw()

        img = npy_frombuffer(self.__figure.canvas.tostring_rgb(), dtype="uint8")
        img = img.reshape(self.__figure.canvas.get_width_height()[::-1] + (3,))

        return img

    def save(self):
        self.__figure.set_figwidth(10)
        self.__figure.set_figheight(8)

        self.__figure.savefig(self.__saveIn)


#loop for:

l = [1,2,3,4,5,6,7,8,9,10]
for num in l:
    print(num)
#verificar par ou impar:
l = [1,2,3,4,5,6,7,8,9,10]
for num in l:
 if num % 2 == 0:
    print(num)
 else:
     print('Número ímpar')

#loop que soma a lista:
list_sum = 0
for num in l:
 list_sum = list_sum + num
 print(list_sum)

#loop de string:

# for letter in 'Esse é um teste de loop com string':
# print(letter)

#loop com tuplas:
tup = (1,2,3,4,5)
for t in tup:
    print(t)
#outro exemplo com tupla(embalando):

l = [(2,4),(6,8),(10,12)]
for tup in l:
    print(tup)

#desembalando:
# for (t1,t2) in l:
# print(t1)

#usando dicionário:
d = {'k1': 1, 'k2':2, 'k3':3}
for item in d:
    print(item)
#iterar através das chaves e valores de um dicionario:
for k,v in d.items():
 print(k)
 print(v)


import os
import torch
import yaml
import numpy as np
import os.path as osp
import pdb
from torchvision import datasets
from utils.transforms import *
from utils.dataset import *
from torch.utils.data.dataloader import DataLoader
from models import models

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--task', default='visda', help='task name')
    args = parser.parse_args()

    config = yaml.load(open("./config/" + args.task + ".yaml", "r"), Loader=yaml.FullLoader)
    device = 'cuda' if torch.cuda.is_available() else 'cpu'
    print(config)
    print(f"Training with: {device}")

    # network
    network = models[config['network']['name']](class_number=config['data']['class_number']).to(device)
    # pretrained_folder = config['network']['fine_tune_from']
    model_name = ['resnet101_source_epoch_1', 'resnet101_source_epoch_2']
    for i in range(len(model_name)):
        pretrained_folder = osp.join('checkpoints/visda', model_name[i] + '.pth')
        if pretrained_folder:
            try:
                load_params = torch.load(pretrained_folder)
                network.load_state_dict(load_params['network_state_dict'], strict=True)
            except FileNotFoundError:
                print("Pre-trained weights not found. Training from scratch.")

        # optim
        if config['optimizer']['name'] == 'SGD':
            optimizer = torch.optim.SGD(list(network.parameters()),
                                        **config['optimizer']['params'])
        else:
            optimizer = torch.optim.Adam(list(network.parameters()),
                                         **config['optimizer']['params'])

        # dataloader
        input_size = config['data_transforms']['input_size']
        batch_size = config['trainer']['batch_size']
        data_transform = simple_transform_test(input_size=input_size, type=config['data'][
            'type'])  # must be test_transform for better clustering
        imagedirs, gt_labels = get_image_dirs(root=config['data']['trainset'])
        train_dataset = base_dataset(imagedirs, labels=gt_labels, transform=data_transform)
        print('trainset {}: {}'.format(config['data']['trainset'], len(train_dataset)))

        test_imagedirs, test_labels = get_image_dirs(root=config['data']['testset'])

        test_dataset = base_dataset(test_imagedirs, test_labels, transform=data_transform)
        test_loader = DataLoader(test_dataset, batch_size=batch_size,
                                 num_workers=config['trainer']['num_workers'], drop_last=False, shuffle=False)
        print('testset {}: {}'.format(config['data']['testset'], len(test_dataset)))

        # trainer
        trainer = ADATrainer(network=network,
                             optimizer=optimizer,
                             device=device,
                             params=config)

        # AdaBN
        train_loader = DataLoader(train_dataset, batch_size=batch_size,
                                  num_workers=config['trainer']['num_workers'], drop_last=False,
                                  shuffle=True)  # must be shuffle
        acc_list, acc = trainer.test_class_wise(test_loader)

        print('model name: {}'.format(model_name[i]))
        for x in acc_list:
            print('before adapt-bn accuracy: {:.4f}'.format(x))
        print('before adapt-bn average accuracy: {:.4f}'.format(acc))

        trainer.update_bn(train_loader)
        acc_list, acc = trainer.test_class_wise(test_loader)
        print('model name: {}'.format(model_name[i]))
        for x in acc_list:
            print('after adapt-bn accuracy: {:.4f}'.format(x))
        print('after adapt-bn average accuracy: {:.4f}'.format(acc))
        trainer.save_model(osp.join('checkpoints/visda', model_name[i] + '_af_adabn.pth'))

if __name__ == '__main__':
    main()


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

codons= {
    'TCA' : 'S',    # Serine
    'TCC' : 'S',    # Serine
    'TCG' : 'S',    # Serine
    'TCT' : 'S',    # Serine
    'TTC' : 'F',    # Phenylalanine
    'TTT' : 'F',    # Phenylalanine
    'TTA' : 'L',    # Leucine
    'TTG' : 'L',    # Leucine
    'TAC' : 'Y',    # Tyrosine
    'TAT' : 'Y',    # Tyrosine
    'TAA' : '_',    # Stop
    'TAG' : '_',    # Stop
    'TGC' : 'C',    # Cysteine
    'TGT' : 'C',    # Cysteine
    'TGA' : '_',    # Stop
    'TGG' : 'W',    # Tryptophan
    'CTA' : 'L',    # Leucine
    'CTC' : 'L',    # Leucine
    'CTG' : 'L',    # Leucine
    'CTT' : 'L',    # Leucine
    'CCA' : 'P',    # Proline
    'CCC' : 'P',    # Proline
    'CCG' : 'P',    # Proline
    'CCT' : 'P',    # Proline
    'CAC' : 'H',    # Histidine
    'CAT' : 'H',    # Histidine
    'CAA' : 'Q',    # Glutamine
    'CAG' : 'Q',    # Glutamine
    'CGA' : 'R',    # Arginine
    'CGC' : 'R',    # Arginine
    'CGG' : 'R',    # Arginine
    'CGT' : 'R',    # Arginine
    'ATA' : 'I',    # Isoleucine
    'ATC' : 'I',    # Isoleucine
    'ATT' : 'I',    # Isoleucine
    'ATG' : 'M',    # Methionine
    'ACA' : 'T',    # Threonine
    'ACC' : 'T',    # Threonine
    'ACG' : 'T',    # Threonine
    'ACT' : 'T',    # Threonine
    'AAC' : 'N',    # Asparagine
    'AAT' : 'N',    # Asparagine
    'AAA' : 'K',    # Lysine
    'AAG' : 'K',    # Lysine
    'AGC' : 'S',    # Serine
    'AGT' : 'S',    # Serine
    'AGA' : 'R',    # Arginine
    'AGG' : 'R',    # Arginine
    'GTA' : 'V',    # Valine
    'GTC' : 'V',    # Valine
    'GTG' : 'V',    # Valine
    'GTT' : 'V',    # Valine
    'GCA' : 'A',    # Alanine
    'GCC' : 'A',    # Alanine
    'GCG' : 'A',    # Alanine
    'GCT' : 'A',    # Alanine
    'GAC' : 'D',    # Aspartic Acid
    'GAT' : 'D',    # Aspartic Acid
    'GAA' : 'E',    # Glutamic Acid
    'GAG' : 'E',    # Glutamic Acid
    'GGA' : 'G',    # Glycine
    'GGC' : 'G',    # Glycine
    'GGG' : 'G',    # Glycine
    'GGT' : 'G'  }

peptides = { "Strep-tag II": "WSHPQFEK" ,
             "c-myc": "EQKLISEEDL",
             "S-tag":"KETAAAKFERQHMDS",
             "HAT-tag":"KDHLIHNVHKEFHAHAHNK" }

result_file = open("result_DNA.txt","w")

for i in peptides:
    AA_Seq = peptides.get(i,"Null")
    print (i + " all the possible DNA sequences of " + AA_Seq + " is: ",file=result_file)
    #AL = []
    x = 1
    for a in AA_Seq:
        print(a, file = result_file)
        PA = []
        for c in codons:
            if codons[c] == a:
                PA.append(c)
                print ("    "+c,file=result_file)

        x *= len(PA)
        print("  ##",file=result_file)
    print("\nThe possible number is : ", file=result_file)
    print (x, file = result_file)
    print("\n", file=result_file)

result_file.close()


import re
from datetime import datetime, timedelta
from typing import Dict, List

from back_testing import BackTester, DayTracker, OptionLegDayTracker, Trade
from util import get_pickle_data

# this is called from flask router with back_test obj which was pickled earlier
def analyze_data(back_tester: BackTester, trade_date: str, option_type: str):
    # analyze_data(back_tester, "2021-09-03", "PE")
    minute_str_list = get_minute_list()
    day_trackers: List[DayTracker] = [day_tracker for day_tracker in back_tester.day_trackers if
                                      day_tracker.trading_date == trade_date]
    if len(day_trackers) == 0:
        return {}
    day_tracker: DayTracker = day_trackers[0]
    short_minute_str_list = [re.sub(r':00$', '', min_str) for min_str in minute_str_list]
    # getting profit,profit perc,option prem data for individual legs
    option_data_list = get_option_data(day_tracker.option_leg_trackers, minute_str_list)
    plot_data = {'minutes': short_minute_str_list, 'expiry': day_tracker.nearest_expiry,
                 'optionPremData': option_data_list, 'totalProfit': round(day_tracker.get_current_profit(), 2)}
    nifty_plot_data = get_nifty_plot_data(day_tracker.nifty_min_data_dic, minute_str_list, day_tracker.trading_date)
    plot_data["niftyData"] = nifty_plot_data
    # total_profit_list = get_total_profit_list(minute_str_list, option_data_list)
    # plot_data['totalProfit'] = total_profit_list
    # plot_data['total_profit_sum'] = day_tracker.get_current_profit()
    return plot_data

def get_option_data(option_leg_trackers: List[OptionLegDayTracker], minute_str_list):
    option_data_list = []
    for option_leg_tracker in option_leg_trackers:
        ticker_candles_dic: Dict[
            str, {}] = option_leg_tracker.strike_ticker_candles_for_trade_date_dic
        value_with_index = get_list_value_with_index(ticker_candles_dic, minute_str_list, option_leg_tracker)
        strike_data = get_strike_plot_data(option_leg_tracker.strike_price, minute_str_list)
        option_prem_data = {"data": value_with_index, 'strikeData': strike_data,
                            'file': option_leg_tracker.option_file_name,
                            "optionType": option_leg_tracker.option_leg.option_type}
        # profit_data, profit_perc_data = get_profit_date(option_leg_tracker, minute_str_list)
        # option_prem_data['profit'] = profit_data
        # option_prem_data['profit_perc'] = profit_perc_data
        option_data_list.append(option_prem_data)
    return option_data_list

def get_profit_date(option_leg_tracker: OptionLegDayTracker, minute_str_list):
    ticker_candles_dic: Dict[
        str, {}] = option_leg_tracker.strike_ticker_candles_for_trade_date_dic
    trades: List[Trade] = option_leg_tracker.trades
    in_our_out = -1
    # having flag to make sure even for boundary condition i am considering those days as trade days
    is_boundary = False
    for key in ticker_candles_dic:
        is_boundary = False
        candle = ticker_candles_dic[key]
        candle['axis_ref_index'] = minute_str_list.index(key)
        matching_trade = len([trade for trade in trades if trade.trade_time == key]) > 0
        if matching_trade:
            is_boundary = True
            in_our_out = in_our_out * -1
        # if its open or close, treat i has 1
        if is_boundary:
            candle['in_our_out'] = 1
        else:
            candle['in_our_out'] = in_our_out
    traded_candles = [ticker_candles_dic[key] for key in ticker_candles_dic if
                      ticker_candles_dic[key]['in_our_out'] == 1]
    profit_reversal = (-1 if option_leg_tracker.option_leg.buy_or_sell == "sell" else 1)
    for candle in traded_candles:
        candle['profit'] = (float(candle['close']) - float(traded_candles[0]['close'])) * profit_reversal
        candle['profit_perc'] = float(candle['profit']) / float(traded_candles[0]['close'])
    profit_data = [[candle['axis_ref_index'], candle['profit']] for candle in traded_candles]
    profit_perc_data = [[candle['axis_ref_index'], candle['profit_perc']] for candle in traded_candles]
    return profit_data, profit_perc_data

# getting total profit by summing up indv profits
def get_total_profit_list(minutes_str_list, option_data_list):
    total_profit_list = []
    for index in range(len(minutes_str_list)):
        profit = None
        for option_data in option_data_list:
            min_profit = get_profit_by_min(option_data['profit'], index)
            if min_profit is not None:
                profit = profit if profit is not None else 0
                profit = profit + min_profit
        if profit is not None:
            total_profit_list.append([index, profit])
    return total_profit_list

def get_profit_by_min(profit_list, min_index):
    min_profit = [profit for profit in profit_list if profit[0] == min_index]
    if len(min_profit) == 0:
        return None
    else:
        return min_profit[0][1]

def get_minute_list():
    # print((entry_date_time_str, exit_date_time_str))
    entry_date_time = datetime.strptime('2021-01-01 09:15:00', '%Y-%m-%d %H:%M:%S')
    exit_date_time = datetime.strptime('2021-01-01 15:30:00', '%Y-%m-%d %H:%M:%S')
    time_diff = exit_date_time - entry_date_time
    minute_diff = (time_diff.total_seconds() / 60)
    minute_list = [entry_date_time + timedelta(minutes=it) for it in range(0, int(minute_diff + 1))]
    minute_str_list = [minute.strftime('%H:%M:%S') for minute in minute_list]
    return minute_str_list

# this is needed for highchart so that the trade could be marked in the graph
def get_list_value_with_index(candle_list_dic: Dict[str, tuple], minute_str_list: List[str],
                              option_leg_tracker: OptionLegDayTracker):
    trades: List[Trade] = option_leg_tracker.trades
    option_premiums_with_trade_marked = []
    start_premium = None
    for key in candle_list_dic:
        matching_trades = [trade for trade in trades if trade.trade_time == key]
        premium_index = minute_str_list.index(key)
        option_value = float(candle_list_dic[key]['close'])
        matching_trade = None
        if len(matching_trades) > 0:
            matching_trade = matching_trades[0]
        if matching_trade is not None:
            # when trade is started/ended at this time, modify the data so that its shown diff. in the graph
            option_trade_entry = {"marker": {
                "fillColor": '#FF0000',
                "lineWidth": 3,
                "lineColor": "#FF0000",
                "radius": 4
            }, "y": option_value, "x": premium_index}
            if start_premium is None:
                start_premium = option_value
            else:
                profit = (option_value - start_premium) * -1
                profit_perc = (profit / start_premium) * 100
                start_premium = None
                option_trade_entry['marker']['profit'] = profit
                option_trade_entry['marker']['profitPerc'] = round(profit_perc, 2)

            option_premiums_with_trade_marked.append(option_trade_entry)
        else:
            option_premiums_with_trade_marked.append([premium_index, option_value])
    return option_premiums_with_trade_marked

def get_nifty_plot_data(nifty_data_dic: Dict[str, tuple], minute_str_list: List[str], date_str: str):
    nifty_min_data_with_index = []
    for index in range(len(minute_str_list)):
        time = minute_str_list[index]
        search_date_time_string = f'{date_str}T{time}+0530'
        if search_date_time_string in nifty_data_dic:
            nifty_min_data_with_index.append([index, nifty_data_dic[search_date_time_string]['close']])
    return nifty_min_data_with_index

def get_strike_plot_data(strike_price: float, minute_str_list: List[str]):
    strike_data_with_index = []
    for index in range(len(minute_str_list)):
        strike_data_with_index.append([index, strike_price])
    return strike_data_with_index


import os
from oauth2client import file, client, tools
from googleapiclient import discovery
import httplib2
from googleapiclient.discovery import build
from googleapiclient.http import MediaFileUpload
from datetime import datetime, timedelta
import time

path = '' #specify path ends with '/' where server have backup dbs.
folder_id = '' #ID of folder in gdrive.
access_token = None
client_id = '' #Client Id take from OAuth 2.0 Client IDs.
client_secret = '' #Cient secret take from OAuth 2.0 Client IDs.
refresh_token = '' #take token from oauthplayground by autheticating.
token_expiry = None
token_uri = "https://accounts.google.com/o/oauth2/token"
user_agent = 'YourAgent/1.0'
credentials = client.GoogleCredentials(access_token, client_id, client_secret, refresh_token, token_expiry, token_uri, user_agent)
http = credentials.authorize(httplib2.Http())
credentials.refresh(http)
service = build('drive', 'v3', http=http)

# upload file to gdrive
def upload():
    for file in os.listdir(path):
        db = os.path.realpath(file)
        file_path, filename = os.path.split(db)
        file = path+filename
        today_date = datetime.today().date()
        file_date = datetime.fromtimestamp(os.path.getctime(file)).date()
        if today_date == file_date:
            file_metadata = {'name': file,'parents': [folder_id]}
            media = MediaFileUpload(file, mimetype='application/zip',resumable=True)
            file = service.files().create(body=file_metadata,media_body=media,fields='id').execute(http=http)

if __name__ == '__main__':
    upload()

#Done by Gokul


def split_line(line):
  separators = [' ', '\t', ',', '/']
  for sep in separators:
    # Split by separators and remove white spaces
    line = list(filter(None, line.split(sep)))
    if len(line) == 1:
      line = line[0]
    else:
      break
  if isinstance(line, str):
    return [line]
  return line

def load_file(filename):
  result = []
  file = open(filename, 'r')
  lines = file.readlines()
  for line in lines:
    # Remove new line sign
    if line[len(line)-1] == '\n':
      line = line[:-1]

    # Line may be empty
    parsedLine = split_line(line)
    if len(parsedLine) == 0:
      continue

    result.append(split_line(line))
  return result

def wczytaj_baze_probek_z_tekstem(nazwa_pliku_z_wartosciami, nazwa_pliku_z_opisem_atr):
  # Parse file with data
  samples = load_file(nazwa_pliku_z_wartosciami)

  # Parse file with attributes
  names = []
  isSymbolic = []
  attributes = load_file(nazwa_pliku_z_opisem_atr)
  for attribute in attributes:
    names.append(attribute[0])
    isSymbolic.append(attribute[1] == 's')

  return (samples, names, isSymbolic)


import sys
import os
import json

from PyQt5.QtWidgets import (QWidget, QLabel, QGridLayout, QPushButton,
                            QLineEdit, QApplication, QComboBox)
from PyQt5.QtGui import QFont, QIcon
from PyQt5.QtCore import Qt

from gui_resources.style import StyleSheet as SS
from gui_resources.style import Font

#TODO
# Combobox selection for delimiter character and decimal character
# Default import configuration options

class SettingsWindow(QWidget):
    '''
    Custom window for application settings
    '''
    def __init__(self, settings: dict) -> None:
        super().__init__()

        # Global app settings
        self.settings = settings

        # Fonts for settings
        self.TitleFont = QFont()
        self.TitleFont.setBold(True)
        self.TitleFont.setPointSize(9)

        # Window settings
        self.setWindowTitle('Settings')
        self.setWindowIcon(QIcon("gui_resources/Quantum_icon.png"))
        self.setMinimumWidth(350)

        # Main layout for settings window
        self.MainLayout = QGridLayout()
        self.MainLayout.setAlignment(Qt.AlignTop)
        self.setLayout(self.MainLayout)

        # Add options for CSV imports
        self.CSVimportLabel = QLabel('CSV Import Settings')
        self.CSVimportLabel.setFont(Font.settings_title)
        self.CSVimportLabel.setAlignment(Qt.AlignCenter)
        self.MainLayout.addWidget(self.CSVimportLabel)

        # Add selection for default settings
        # self.defaultSettingsLabel = QLabel('Default Settings')
        # self.MainLayout.addWidget(self.defaultSettingsLabel, 1, 0)
        self.defaultSettingsCombo = QComboBox()
        self.defaultSettingsCombo.addItems(['Default Settings', 'Siemens', 'StrideLinx'])
        self.defaultSettingsCombo.textActivated.connect(self.defaultSettings)
        self.MainLayout.addWidget(self.defaultSettingsCombo, 1, 0)

        # Add csv import settings
        csv_settings = self.constructCSVsettings()
        self.MainLayout.addLayout(csv_settings, 2, 0)

        # Button to apply the settings
        self.ApplyButton = QPushButton('Apply')
        self.ApplyButton.clicked.connect(self.settingsApply)
        self.MainLayout.addWidget(self.ApplyButton)

    def show(self) -> None:
        '''
        Opens the settings window and populates it with the current settings
        '''
        # Populate current settings to window
        self.DelimiterSelection.setText(self.settings['delimiter'])
        self.DecimalSelection.setText(self.settings['decimal'])
        self.TimeHeaderString.setText(self.settings['time_header_title'])
        self.DateTimeFormatComboBox.clear()
        self.DateTimeFormatComboBox.addItems(self.settings['recent_date_time_format'])
        self.DateTimeFormatLineEdit.setText(self.settings['date_time_format'])

        # Show the settings window
        super().show()
        super().activateWindow()

    def settingsApply(self) -> None:
        '''
        Saves the current settings and stores them in a json file
        '''
        # Save csv import settings
        self.settings['delimiter'] = self.DelimiterSelection.text()
        self.settings['decimal'] = self.DecimalSelection.text()
        self.settings['time_header_title'] = self.TimeHeaderString.text()
        self.settings['date_time_format'] = self.DateTimeFormatLineEdit.text()

        date_time_formats = [
            self.DateTimeFormatComboBox.itemText(i) for i in range(self.DateTimeFormatComboBox.count())
            ][:6]
        if self.settings['date_time_format'] not in date_time_formats:
            date_time_formats.insert(0, self.settings['date_time_format'])
            self.DateTimeFormatComboBox.addItem(self.DateTimeFormatLineEdit.text())
        self.settings['recent_date_time_format'] = date_time_formats

        # Write settings to the settings file
        with open(os.path.join(os.path.dirname(__file__), 'settings.json'), 'w+') as json_file:
            json.dump(self.settings, json_file)

    def constructCSVsettings(self) -> QGridLayout:
        '''
        Convenience function for constructing widgets pertaining to csv import settings
        '''
        # Create layout of csv settings
        self.CSVLayout = QGridLayout()

        # Input for setting the CSV delimiter
        self.DelimiterSelectionLabel = QLabel('Delimiter')
        self.DelimiterSelectionLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.CSVLayout.addWidget(self.DelimiterSelectionLabel, 0, 0)
        self.DelimiterSelection = QLineEdit()
        self.CSVLayout.addWidget(self.DelimiterSelection, 0, 1)

        # Input for setting the CSV comma character
        self.DecimalSelectionLabel = QLabel('Decimal')
        self.CSVLayout.addWidget(self.DecimalSelectionLabel, 0, 2)
        self.DecimalSelection = QLineEdit()
        self.CSVLayout.addWidget(self.DecimalSelection, 0, 3)

        # Input for the time column header
        self.TimeHeaderStringLabel = QLabel('Time Header Title')
        self.CSVLayout.addWidget(self.TimeHeaderStringLabel, 1, 0)
        self.TimeHeaderString = QLineEdit()
        self.CSVLayout.addWidget(self.TimeHeaderString, 1, 1, 1, 3)

        # Input for date/time format of the data
        self.DateTimeFormatLabel = QLabel('Date/Time Format')
        self.CSVLayout.addWidget(self.DateTimeFormatLabel, 2, 0)
        self.DateTimeFormatComboBox = QComboBox()
        self.DateTimeFormatLineEdit = QLineEdit()
        self.DateTimeFormatComboBox.setLineEdit(self.DateTimeFormatLineEdit)
        self.CSVLayout.addWidget(self.DateTimeFormatComboBox, 2, 1, 1, 3)

        return self.CSVLayout

    def defaultSettings(self) -> None:
        selected = self.defaultSettingsCombo.currentText()

        if selected == 'Siemens':
            self.DelimiterSelection.setText(';')
            self.DecimalSelection.setText(',')
            self.TimeHeaderString.setText('TimeString')
            self.DateTimeFormatLineEdit.setText('%d.%m.%Y %H:%M:%S')

        elif selected == 'StrideLinx':
            self.DelimiterSelection.setText(',')
            self.DecimalSelection.setText('.')
            self.TimeHeaderString.setText('time')
            self.DateTimeFormatLineEdit.setText('%Y-%m-%d %H:%M:%S.%f')

if __name__ == '__main__':
    # Helps with scaling when using two screens with diffirent DPI
    QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
    QApplication.setAttribute(Qt.HighDpiScaleFactorRoundingPolicy.PassThrough)

    # Initialize application
    app = QApplication(sys.argv)
    # Create window
    MainWindow = SettingsWindow({})
    MainWindow.show()
    # Terminated when the application is closed
    sys.exit(app.exec())


from itertools import combinations

def perm():
 S, n = input().split(" ")
 n  = int(n)
 S  = str(S)
 list_s = list(S)
 list_s.sort()
 length = len(S)
 fin_list = []
 for i in range(1,n+1):
    new = list(combinations(list_s,i))
    fin_list.append(new)
    #print(new)

 for element in fin_list:
    for small in element:
        print("".join(small))

 #print(fin_list)

perm()


from gql import gql, Client
from gql.transport.requests import RequestsHTTPTransport
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
import os
import numpy as np

# Setup flask app
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

# Setup graphql client
client = Client(
    transport=RequestsHTTPTransport(
        url='https://graphql.fauna.com/graphql',
        headers={'Authorization': 'Bearer '+os.environ['FAUNA_SECRET']}),
    fetch_schema_from_transport=True)
    #schema=schema)

# Setup numpy float formatter for printing to graphql strings in proper format
floatFormatter = '{:.2f}'.format
np.set_printoptions(formatter={'float_kind': floatFormatter})

@app.route('/api/validate', methods=['OPTIONS', 'POST'])
@cross_origin()
def handleValidate():
    data = request.get_json()

    validateQuery = gql('''
        query {{
            findTestByID(id: {id}) {{
                _id
                a {{
                    name
                    data
                }}
                b {{
                    name
                    data
                }}
            }}
        }}
    '''.format(id=data['id']))

    res = client.execute(validateQuery)
    res = res['findTestByID']

    a = res['a']['data']
    b = res['b']['data']

    sortedA, sortedB, aEcdf, bEcdf, d = kolgomorovSmirnov(
        a,
        b)

    same = d <= data['thresh']

    validateMutation = gql('''
        mutation {{
            updateTest(
                id: {id}
                data: {{
                    aEcdf: {{
                        create: {{
                            name: "{aEcdfName}_ECDF"
                            data: {aEcdfData}
                        }}
                    }}
                    bEcdf: {{
                        create: {{
                            name: "{bEcdfName}_ECDF"
                            data: {bEcdfData}
                        }}
                    }}
                    thresh: {thresh}
                    d: {d}
                    same: {same}
            }})
        }}
    '''.format(id=data['id'],
               aEcdfName=res['a']['name'],
               aEcdfData=aEcdf,
               bEcdfName=res['b']['name'],
               bEcdfData=bEcdf,
               thresh=data['thresh'],
               d=d,
               same=same))

    return jsonify({
        'id': data['id'],
        'aName': res['a']['name'],
        'a': a,
        'sortedA': sortedA.tolist(),
        'bName': res['b']['name'],
        'b': b,
        'sortedB': sortedB.tolist(),
        'aEcdf': aEcdf.tolist(),
        'bEcdf': bEcdf.tolist(),
        'thresh': data['thresh'],
        'd': d,
        'same': bool(same),
        'msg': 'Successfully performed dataset validation'
    })

def kolgomorovSmirnov(a, b):
    sortedA = np.sort(a)
    sortedB = np.sort(b)

    sortedA_CDF = ecdf(sortedA)
    sortedA_ECDF = np.array([sortedA_CDF(x) for x in sortedA])

    sortedB_CDF = ecdf(sortedB)
    sortedB_ECDF = np.array([sortedB_CDF(x) for x in sortedB])

    d = dStatistic(sortedA, sortedB, sortedA_ECDF, sortedB_ECDF)

    return sortedA, sortedB, sortedA_ECDF, sortedB_ECDF, d

def ecdf(x):
    x = np.sort(x)
    def result(v):
        return np.searchsorted(x, v, side='right') / x.size
    return result

# NOTE: in order to use this function in the general case,
# we should normalize the concatenated a::b dataset
def dStatistic(a, b, a_ecdf, b_ecdf):
    def new_idx(arr1, arr2, arr1_idx, arr2_idx):
        if arr1_idx >= len(arr1)-1 and arr2_idx >= len(arr2-1):
            return arr1_idx, arr2_idx
        elif arr1_idx >= len(arr1)-1:
            return arr1_idx, arr2_idx+1
        elif arr2_idx >= len(arr2)-1:
            return arr1_idx+1, arr2_idx

        eps = 0.0005
        diff = arr1[arr1_idx] - arr2[arr2_idx]

        if np.abs(diff) < eps:
            return arr1_idx+1, arr2_idx+1
        elif diff < 0:
            return arr1_idx+1, arr2_idx
        else:
            return arr1_idx, arr2_idx+1

    a_idx = 0
    b_idx = 0
    d = -np.Inf
    while True:
        # set d to new max distance between ecdf functions
        d = np.maximum(d, np.abs(a_ecdf[a_idx]-b_ecdf[b_idx]))

        # break if reached the end of the arrays
        if a_idx >= len(a)-1 and b_idx >= len(b)-1:
            break

        # walk through arrays
        (a_idx, b_idx) = new_idx(a, b, a_idx, b_idx)

    return d

'''
control1 = np.array([0.22, -0.87, -2.39, -1.79, 0.37,
                     -1.54, 1.28, -0.31, -0.74, 1.72,
                     0.38, -0.17, -0.62, -1.10, 0.30,
                     0.15, 2.30, 0.19, -0.50, -0.09])
data1 = np.array([-5.13, -2.19, -2.43, -3.83, 0.50,
                  -3.25, 4.32, 1.63, 5.18, -0.43,
                  7.11, 4.87, -3.10, -5.81, 3.76,
                  6.31, 2.58, 0.07, 5.76, 3.50])
control2 = np.array([1.26, 0.34, 0.70, 1.75, 50.57,
                     1.55, 0.08, 0.42, 0.50, 3.20,
                     0.15, 0.49, 0.95, 0.24, 1.37,
                     0.17, 6.98, 0.10, 0.94, 0.38])
data2 = np.array([2.37, 2.16, 14.82, 1.73, 41.04,
                  0.23, 1.32, 2.91, 39.41, 0.11,
                  27.44, 4.51, 0.51, 4.50, 0.18,
                  14.68, 4.66, 1.30, 2.06, 1.19])
'''


__author__ = 'Alexander'
" User gives connections directly to pygrametl objects. Not as variables."

import pygrametl
from pygrametl.datasources import SQLSource
from pygrametl.tables import Dimension, FactTable
import sqlite3

input_src = SQLSource(sqlite3.connect('input.db'), query='SELECT * FROM table')
input2_src = SQLSource(sqlite3.connect('input2.db'), query='SELECT * FROM table')
output_wrapper = pygrametl.ConnectionWrapper(sqlite3.connect('dw.db'))

dim1 = Dimension(
    'dim1',
    'key1',
    ['attr1', 'attr2']
)

dim2 = Dimension(
    name='dim2',
    key='key2',
    attributes=['attr3', 'attr4']
)

ft1 = FactTable(
    name='ft1',
    keyrefs=['key1']
)


produce_dictionary = {'Potatoes': [0.86, 12219, 10508],
                      'Okra': [2.26, 12960, 29290],
                      'Fava beans': [2.69, 11703, 31480],
                      'Watermelon': [0.66, 11485, 7580],
                      'Garlic': [1.19, 12512, 14889],
                      'Parsnips': [2.27, 11270, 25584],
                      'Asparagus': [2.49, 12848, 31991],
                      'Avocados': [3.23, 12369, 39953],
                      'Celery': [3.07, 12334, 37866],
                      'Spinach': [4.12, 11740, 48367],
                      'Cucumber': [1.07, 11994, 12834],
                      'Apricots': [3.71, 11762, 43637],
                      'Ginger': [5.13, 11915, 61126],
                      'Corn': [1.07, 11702, 12522],
                      'Grapefruit': [0.76, 11707, 8897],
                      'Eggplant': [2.32, 11843, 27477],
                      'Green cabbage': [0.8, 11611, 9289],
                      'Yellow peppers': [2.87, 12160, 34899],
                      'Grapes': [2.63, 12294, 32333],
                      'Cherries': [9.5, 12384, 117653],
                      'Apples': [1.88, 12397, 23307],
                      'Green beans': [2.52, 11483, 28938],
                      'Tomatoes': [3.16, 12016, 37969],
                      'Red onion': [0.78, 12549, 9788],
                      'Strawberries': [4.4, 11692, 51446],
                      'Papaya': [1.34, 11775, 15779],
                      'Butternut squash': [1.28, 11495, 14713],
                      'Bananas': [0.86, 12629, 10861],
                      'Lettuce': [1.88, 11891, 22355],
                      'Carrots': [1.26, 12204, 15377],
                      'Daikon': [1.4, 12146, 17004],
                      'Lime': [1.06, 11934, 12650],
                      'Green peppers': [1.89, 11981, 22645],
                      'Beets': [1.51, 12255, 18506],
                      'Coconuts': [1.18, 11840, 13972],
                      'Orange': [1.09, 11180, 12187],
                      'Lemon': [1.29, 12382, 15974],
                      'Brussels sprouts': [1.65, 11947, 19713],
                      'Kale': [5.02, 12293, 61711],
                      'Bok choy': [1.42, 11565, 16422]}
'''
Using this start file, use the dictionary to create a data frame with the produce names as rows and columns named - "Cost Per Pound", "Quantity Sold" and "Total Sale".
NOTE: Please include the questions as part of your print statements so it is easier to grade.

Using Pandas Dataframe methods, display the following information:
'''
import pandas as pd
import numpy as np

df1 = pd.DataFrame(produce_dictionary)
#new column names
new_col = ["Cost Per Pound", "Quantity Sold", "Total Sale"]
df1.index =[new_col]
#switching columns and rows
df1 = df1.T
print('create a data frame with the produce names as rows and columns named')
print(df1)
'''
1. Produce that had the highest and lowest sales in total sales (both name of produce and value)
'''
lowest_sales = df1["Total Sale"].min()
highest_sales = df1["Total Sale"].max()
print()
print("Produce that had the highest and lowest sales in total sales (both name of produce and value)")
print(lowest_sales)
print(highest_sales)
#print(df1[df1.iloc[:,0].min()])

'''
2. Using 'loc', display the quantity and total sales for 'Orange' and 'Beets' (together)
'''

print("Using 'loc', display the quantity and total sales for 'Orange' and 'Beets' (together)")
orange_and_beets_quant = df1.loc[['Orange', 'Beets'],'Quantity Sold'].sum()
orange_and_beets_sales = df1.loc[['Orange', 'Beets'],'Total Sale'].sum()
print(orange_and_beets_quant)
print(orange_and_beets_sales)

'''
3. Using 'loc', display the total sales for 'Apples' through 'Lettuce'
'''
print()
print("Using 'loc', display the total sales for 'Apples' through 'Lettuce'")
Apples_thru_letuce = df1.loc['Apples': 'Lettuce', 'Total Sale']
print(Apples_thru_letuce)

'''
4. Using 'at', update the quantity sold for Apricots to 11,955 and total sales to 44,353.05
'''
print()
print("Using 'at', update the quantity sold for Apricots to 11,955 and total sales to 44,353.05")
df1.at["Apricots","Quantity Sold"] =11955
df1.at["Apricots","Total Sale"] =44353.05
print(df1)

'''
5. hat is the average quantity sold across all products? (print out ONLY quantity sold)
'''
print()
print("What is the average quantity sold across all products? (print out ONLY quantity sold)")
avg_quant = df1.loc[:,'Quantity Sold'].mean()
print(avg_quant)

'''
6. Create a new dataframe for only those produce that have sold between 11,500 to 12,000 (quantity)
'''
print()
print("Create a new dataframe for only those produce that have sold between 11,500 to 12,000 (quantity)")
df2 = df1[(df1.iloc[:,1]>= 11500) & (df1.iloc[:,1] <= 12000)]
print(df2)
''''
7. What is the total sales for the products in the above new dataframe? (print out ONLY total sales)
'''
print()
print("What is the total sales for the products in the above new dataframe? (print out ONLY total sales)")
total_sales_df2 = df2.loc[:,'Total Sale'].sum()
print(total_sales_df2)


from django.shortcuts import render, HttpResponse, redirect, HttpResponseRedirect

from .models import Teams
from car_app.models import Cars

from contact_app.models import Contact_me
from django.contrib import messages
from django.contrib.auth.models import User
from django.core.mail import send_mail, BadHeaderError

# Create your views here.

def Home_page(request):
    total_team = Teams.objects.all()
    features_car = Cars.objects.order_by('-create_data').filter(is_features=True)
    total_car = Cars.objects.order_by('-create_data')[:9]
    # search_fields = Cars.objects.values('model', 'city', 'year', 'body_style') # is this way problem  dublicatvalu
    model_search = Cars.objects.values_list('model', flat=True).distinct()
    city_search = Cars.objects.values_list('city', flat=True).distinct()
    year_search = Cars.objects.values_list('year', flat=True).distinct()
    body_style_search = Cars.objects.values_list('body_style', flat=True).distinct()
    data = {
        "total_team": total_team,
        "features_car": features_car,
        "total_car": total_car,
        # "search_fields": search_fields,
        "model_search": model_search,
        "city_search": city_search,
        "year_search": year_search,
        "body_style_search": body_style_search,
    }
    return render(request, 'pages/index.html', data)

def About_page(request):
    total_team = Teams.objects.all()
    data = {
        "total_team": total_team,
    }
    return render(request, 'pages/about.html', data)

def Services_page(request):
    return render(request, 'pages/services.html')

def Contact_page(request):
    if request.method == 'POST':
        first_name = request.POST['first_name']
        last_name = request.POST['last_name']
        email = request.POST['email']
        subject = request.POST['subject']
        message = request.POST['message']
        data = Contact_me(first_name=first_name, last_name=last_name, email=email, subject=subject, message=message)
        admin_info = User.objects.get(is_superuser=True)
        admin_email = admin_info.email
        form_email = email
        messages.success(request, 'Thanks for contact Us !')
        return redirect('contact')

        # if subject and message and form_email:
        #     try:
        #         send_mail(subject, message, form_email, [admin_email])
        #     except BadHeaderError:
        #         return HttpResponse('Invalid header found.')
        #     data.save()
        #     messages.success(request, 'Thanks for contact Us !')
        #     return redirect('contact')
        # else:
        #     return HttpResponse('Make sure all fields are entered and valid.')

    return render(request, 'pages/contact.html')


from flask import Flask, render_template, url_for, request, redirect, jsonify
from flask_sqlalchemy import SQLAlchemy
import requests
import json
import psycopg2
import pytz
from datetime import datetime, timedelta
from dateutil.parser import parse

app = Flask(__name__)

@app.route('/')
def main():
    return render_template("main.html")

@app.route('/statistics/all')
def statistics_all():
    articles = requests.get('http://127.0.0.1:5001/date_of_take')
    data = []
    data_keys = list(articles.json().keys())
    data_values = list(articles.json().values())
    for i in range(len(articles.json())):
        data.append([data_keys[i], data_values[i]])
    return render_template("statistics.html", data=data)

@app.route('/statistics/week')
def statistics_weak():
    articles = requests.get('http://127.0.0.1:5001/date_of_take')
    data = []
    data_keys = list(articles.json().keys())
    data_values = list(articles.json().values())
    for i in range(len(articles.json())):
        data.append([data_keys[i], data_values[i]])
    data = data[:-8:-1]
    data = data[::-1]
    return render_template("statistics.html", data=data)

@app.route('/statistics/last_month')
def statistics_last_month():
    articles = requests.get('http://127.0.0.1:5001/date_of_take')
    data = []
    data_keys = list(articles.json().keys())
    data_values = list(articles.json().values())
    for i in range(len(articles.json())):
        data.append([data_keys[i], data_values[i]])
    data = data[:-31:-1]
    data = data[::-1]
    return render_template("statistics.html", data=data)

@app.route('/statistics/month')
def statistics_month():
    articles = requests.get('http://127.0.0.1:5001/date_of_take/month')
    data = []
    data_keys = list(articles.json().keys())
    data_values = list(articles.json().values())
    for i in range(len(articles.json())):
        data.append([data_keys[i], data_values[i]])
    return render_template("statistics.html", data=data)

@app.route('/statistics/year')
def statistics_year():
    articles = requests.get('http://127.0.0.1:5001/date_of_take/year')
    data = []
    data_keys = list(articles.json().keys())
    data_values = list(articles.json().values())
    for i in range(len(articles.json())):
        data.append([data_keys[i], data_values[i]])
    return render_template("statistics.html", data=data)

@app.route('/all_users')
def all_users():
    info_person = requests.get('http://127.0.0.1:5001/person')
    return render_template("all_users.html", articles_person=info_person.json())

@app.route('/all_books', methods=['POST', 'GET'])
def all_books():
    info_book = requests.get('http://127.0.0.1:5001/book').json()
    if request.method == "POST":
        arrears = int(request.form['arrears'])
        return redirect(f"/all_books/arrears/{arrears}")
    return render_template("all_books.html", articles_books=info_book)

@app.route('/all_books/arrears/<int:arrears>', methods=['POST', 'GET'])
def all_books_arrears(arrears):
    info_book = requests.get('http://127.0.0.1:5001/book').json()
    data_arrears = []
    for i in info_book:
        if type(i["date_of_issue"]) == str:
            new_time = parse(i["date_of_issue"])
            time_now = datetime.now(pytz.timezone('Europe/Moscow')).strftime("%Y-%m-%d")
            if new_time.date() + timedelta(days=arrears) < parse(time_now).date():
                data_arrears.append(i)
    return render_template("all_books_arrears.html", articles_books=data_arrears, arrears=arrears)

@app.route('/add_person', methods=['POST', 'GET'])
def create_user():
    if request.method == "POST":
        surname = request.form['surname']
        name = request.form['name']
        patronymic = request.form['patronymic']
        cafedra = request.form['cafedra']
        passport_data = request.form['passport_data']
        date_of_birthday = request.form['date_of_birthday']
        registration = request.form['registration']
        place_of_residence = request.form['place_of_residence']
        telephone = request.form['telephone']

        requests.post('http://127.0.0.1:5001/add_user', json={"surname": surname, "name": name,
                                                              "patronymic": patronymic,
                                                              "cafedra": cafedra,
                                                              "passport_data": passport_data,
                                                              "date_of_birthday": date_of_birthday,
                                                              "registration": registration,
                                                              "place_of_residence": place_of_residence,
                                                              "telephone": telephone})
        return redirect('/all_users')
    else:
        return render_template("add_user.html")

@app.route('/add_book', methods=['POST', 'GET'])
def add_book():
    if request.method == "POST":
        author = request.form['author']
        name = request.form['name']

        requests.post('http://127.0.0.1:5001/add_book', json={"author": author, "name": name})
        return redirect('/all_books')
    else:
        return render_template("add_book.html")

@app.route('/book/<int:id>/put', methods=['POST', 'GET'])
def put_book(id):
    info_Book = requests.get(f'http://127.0.0.1:5001/book/{id}')
    if request.method == "POST":

        author = request.form['author']
        name = request.form['name']
        person_id = request.form['person_id']
        requests.put(f'http://127.0.0.1:5001/book/{id}/put',
                     json={"author": author, "name": name,
                           "person_id": person_id, "id": id})
        return redirect('/all_books')
    else:
        return render_template("book_update.html", info_Book=info_Book.json())

@app.route('/all_users/<int:id>/put', methods=['POST', 'GET'])
def put_user(id):
    info_Person = requests.get(f'http://127.0.0.1:5001/all_users/{id}')
    if request.method == "POST":
        surname = request.form['surname']
        name = request.form['name']
        patronymic = request.form['patronymic']
        cafedra = request.form['cafedra']
        passport_data = request.form['passport_data']
        date_of_birthday = request.form['date_of_birthday']
        registration = request.form['registration']
        place_of_residence = request.form['place_of_residence']
        telephone = request.form['telephone']

        requests.put(f'http://127.0.0.1:5001/all_users/{id}/put', json={"surname": surname, "name": name,
                                                              "patronymic": patronymic,
                                                              "cafedra": cafedra,
                                                              "passport_data": passport_data,
                                                              "date_of_birthday": date_of_birthday,
                                                              "registration": registration,
                                                              "place_of_residence": place_of_residence,
                                                              "telephone": telephone})
        return redirect('/all_users')
    else:
        return render_template("user_update.html", info_Person=info_Person.json())

if __name__ == "__main__":
    app.run(debug=True)