import PIL as p
from PIL import ImageTk
from tkinter import filedialog
import cv2
from pathlib import Path
from tkinter import *
import pandas as pd
import real_face_reco
OUTPUT_PATH = Path(__file__).parent
ASSETS_PATH = OUTPUT_PATH / Path("./assets")

def relative_to_assets(path: str) -> Path:
    return ASSETS_PATH / Path(path)

def scan_image():
    global path
    videoCaptureObject = cv2.VideoCapture(1)
    result = True
    while (result):
        ret, frame = videoCaptureObject.read()
        txt="Press q for capture image"
        cv2.putText(frame,txt,(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,255),2)

        cv2.imshow("Scan Image",frame)
        path="./employ_img/"+id.get()+".jpg"
        if (cv2.waitKey(1) & 0xFF == ord('q')):
            cv2.imwrite(path, frame)
            break

    videoCaptureObject.release()
    cv2.destroyAllWindows()

def submit():
    image=path
    id_val=id.get()
    name_val = name.get()
    email_val = email.get()
    new_row=pd.Series([id_val,name_val,email_val,image])
    df=pd.DataFrame([new_row])
    df.to_csv('./data/employData.csv', mode='a', header=False,index=False)

    print("The Id is : " + id_val)
    print("The Name is : " + name_val)
    print("The Email is : " + email_val)

    name.set("")
    email.set("")
    id.set("")

def button_4_fnc():
    videoCaptureObject = cv2.VideoCapture(1)
    result = True
    while (result):
        ret, frame = videoCaptureObject.read()
        txt="Press q for capture image"
        cv2.putText(frame,txt,(50,50),cv2.FONT_HERSHEY_COMPLEX,1,(255,0,255),2)
        cv2.imshow("Scan Image", frame)
        if (cv2.waitKey(1) & 0xFF == ord('q')):
            videoCaptureObject.release()
            cv2.destroyAllWindows()
            break
    print(frame.shape)
    txt_name=real_face_reco.find_img(frame)

    updateData(id=txt_name,set_im=frame)

def updateData(name=None,id=None,email=None,set_im=None):
    df=pd.read_csv("./data/employData.csv")
    df['ID'].astype(str)
    var =df.loc[df['ID'].isin([id])]
    print(var)
    name=var["NAME"].values[0]
    email=var["EMAIL"].values[0]
    out_name.set(name)
    out_id.set(id)
    out_email.set(email)
    path=f"{(var['IMAGE'].values[0])}"
    set_im=cv2.imread(path)
    set_img(set_im)

def button_5_fnc():
    global res_img
    global  image_1,panelB
    path=filedialog.askopenfilename()
    if len(path)>0:
        image=cv2.imread(path)
        txt_name = real_face_reco.find_img(image)
        updateData(id=txt_name,set_im=image)

def set_img(image):
    global res_img
    global image_1, panelB
    image = cv2.resize(image, (500, 468))
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

    image = p.Image.fromarray(image)

    image = ImageTk.PhotoImage(image)
    res_img = image
    canvas.create_image(
        996.0,
        790.0,
        image=res_img
    )

def button_3_fncn():
    global path
    path = filedialog.askopenfilename()
    print(path)
    img=cv2.imread(path)
    path="./employ_img/"+id.get()+".jpg"
    if len(path)>0:

        cv2.imwrite(path,img)

def appendDFToCSV_void(df, csvFilePath, sep=","):
    import os
    if not os.path.isfile(csvFilePath):
        df.to_csv(csvFilePath, mode='a', index=False, sep=sep)
    elif len(df.columns) != len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns):
        raise Exception("Columns do not match!! Dataframe has " + str(len(df.columns)) + " columns. CSV file has " + str(len(pd.read_csv(csvFilePath, nrows=1, sep=sep).columns)) + " columns.")
    elif not (df.columns == pd.read_csv(csvFilePath, nrows=1, sep=sep).columns).all():
        raise Exception("Columns and column order of dataframe and csv file do not match!!")
    else:
        df.to_csv(csvFilePath, mode='a', index=False, sep=sep, header=False)

window = Tk()

window.geometry("1860x1024")
window.configure(bg = "#FFFCB7")

name=StringVar()
email=StringVar()
id=StringVar()
out_id=StringVar()
out_name=StringVar()
out_email=StringVar()

canvas = Canvas(
    window,
    bg = "#FFFCB7",
    height = 1024,
    width = 1860,
    bd = 0,
    highlightthickness = 0,
    relief = "ridge"
)

canvas.place(x = 0, y = 0)
canvas.create_rectangle(
    1.1368683772161603e-13,
    0.0,
    720.0000000000001,
    1024.0,
    fill="#FFFFFF",
    outline="")

canvas.create_text(
    13.0,
    31.0,
    anchor="nw",
    text="Pandoras Box",
    fill="#F63333",
    font=("Roboto Bold", 50 * -1),
    width=718.0
)

canvas.create_text(
    33.0,
    195.0,
    anchor="nw",
    text="Register:",
    fill="#000",
    font=("Roboto Bold", 50 * -1),
    width=233.0
)

canvas.create_text(
    1043.0,
    16.0,
    anchor="nw",
    text="Show Me Everything:",
    fill="#000",
    font=("Roboto Bold", 50 * -1),
    width=664.0
)

entry_image_1 = PhotoImage(
    file=relative_to_assets("entry_1.png")
)
entry_bg_1 = canvas.create_image(
    270.5,
    366.5,
    image=entry_image_1
)
entry_1 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = id, font=('calibre',15,'bold'),fg="#000000"
)
entry_1.place(
    x=53.0,
    y=322.0,
    width=435.0,
    height=87.0
)

entry_image_2 = PhotoImage(
    file=relative_to_assets("entry_2.png")
)
entry_bg_2 = canvas.create_image(
    1602.5,
    761.5,
    image=entry_image_2
)
entry_2 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = out_email, font=('calibre',15,'bold'),fg="#000000"
)
entry_2.place(
    x=1385.0,
    y=717.0,
    width=435.0,
    height=87.0
)

entry_image_3 = PhotoImage(
    file=relative_to_assets("entry_3.png")
)
entry_bg_3 = canvas.create_image(
    1612.5,
    949.5,
    image=entry_image_3
)
entry_3 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = out_id, font=('calibre',15,'bold'),fg="#000000"
)
entry_3.place(
    x=1395.0,
    y=905.0,
    width=435.0,
    height=87.0
)

entry_image_4 = PhotoImage(
    file=relative_to_assets("entry_4.png")
)
entry_bg_4 = canvas.create_image(
    1602.5,
    600.5,
    image=entry_image_4
)
entry_4 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = out_name, font=('calibre',15,'bold'),fg="#000000"
)
entry_4.place(
    x=1385.0,
    y=556.0,
    width=435.0,
    height=87.0
)

entry_image_5 = PhotoImage(
    file=relative_to_assets("entry_5.png")
)
entry_bg_5 = canvas.create_image(
    270.5,
    654.0,
    image=entry_image_5
)
entry_5 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = email, font=('calibre',15,'bold'),fg="#000000"
)
entry_5.place(
    x=53.0,
    y=609.5,
    width=435.0,
    height=87.0
)

entry_image_6 = PhotoImage(
    file=relative_to_assets("entry_6.png")
)
entry_bg_6 = canvas.create_image(
    270.5,
    511.5,
    image=entry_image_6
)
entry_6 = Entry(
    bd=0,
    bg="#C4C4C4",
    highlightthickness=0,
    textvariable = name, font=('calibre',15,'bold'),fg="#000000"
)
entry_6.place(
    x=53.0,
    y=467.0,
    width=435.0,
    height=87.0
)

canvas.create_text(
    34.0,
    281.0,
    anchor="nw",
    text="Enter ID:",
    fill="#000",
    font=("Roboto Bold", 25 * -1),
    width=126.0
)

canvas.create_text(
    1544.0,
    486.0,
    anchor="nw",
    text="Name",
    fill="#000",
    font=("Roboto Bold", 35 * -1),
    width=138.0
)

canvas.create_text(
    1544.0,
    671.0,
    anchor="nw",
    text="Email",
    fill="#000",
    font=("Roboto Bold", 35 * -1),
    width=138.0
)

canvas.create_text(
    1544.0,
    837.0,
    anchor="nw",
    text="Id No",
    fill="#000",
    font=("Roboto Bold", 35 * -1),
    width=138.0
)

canvas.create_text(
    33.0,
    429.0,
    anchor="nw",
    text="Enter Name:",
    fill="#000",
    font=("Roboto Bold", 25 * -1),
    width=163.0
)

canvas.create_text(
    34.0,
    574.0,
    anchor="nw",
    text="Enter Email:",
    fill="#000",
    font=("Roboto Bold", 25 * -1),
    width=189.0
)

button_image_1 = PhotoImage(
    file=relative_to_assets("button_1.png"))
button_1 = Button(
    image=button_image_1,
    borderwidth=0,
    highlightthickness=0,
    command=scan_image,
    relief="flat"
)
button_1.place(
    x=34.0,
    y=762.0,
    width=280.0,
    height=65.0
)

button_image_2 = PhotoImage(
    file=relative_to_assets("button_2.png"))
button_2 = Button(
    image=button_image_2,
    borderwidth=0,
    highlightthickness=0,
    command=submit,
    relief="flat"
)
button_2.place(
    x=220.0,
    y=891.0,
    width=280.0,
    height=65.0
)

button_image_3 = PhotoImage(
    file=relative_to_assets("button_3.png"))
button_3 = Button(
    image=button_image_3,
    borderwidth=0,
    highlightthickness=0,
    command=button_3_fncn,
    relief="flat"
)
button_3.place(
    x=401.0,
    y=762.0,
    width=280.0,
    height=65.0
)

button_image_4 = PhotoImage(
    file=relative_to_assets("button_4.png"))
button_4 = Button(
    image=button_image_4,
    borderwidth=0,
    highlightthickness=0,
    command=button_4_fnc,
    relief="flat"
)
button_4.place(
    x=731.0,
    y=166.0,
    width=471.0,
    height=114.0
)

button_image_5 = PhotoImage(
    file=relative_to_assets("button_5.png"))
button_5 = Button(
    image=button_image_5,
    borderwidth=0,
    highlightthickness=0,
    command=button_5_fnc,
    relief="flat"
)
button_5.place(
    x=1379.0,
    y=166.0,
    width=471.0,
    height=114.0
)

canvas.create_text(
    763.0,
    313.0,
    anchor="nw",
    text="Employ Details:",
    fill="#000",
    font=("Roboto Bold", 40 * -1),
    width=315.0
)

image_image_1 = PhotoImage(
    file=relative_to_assets("image_1.png"))
image_1 = canvas.create_image(
    996.0,
    790.0,
    image=image_image_1
)

image_image_2 = PhotoImage(
    file=relative_to_assets("image_2.png"))
image_2 = canvas.create_image(
    996.0,
    518.0,
    image=image_image_2
)
window.resizable(False, False)
window.mainloop()


import torch.nn as nn
import torch.nn.functional as F
from .block import TransformerBlock

class VanillaTransformer(nn.Module):
    def __init__(
        self,
        num_layers,
        embed_dim,
        hidden_dim,
        num_heads,
        causal=False,
        attn_dropout=0.0,
        ffn_dropout=0.0,
        attn_type="vanilla",
        ffn_type="vanilla",
        norm_type="ln",
        pre_norm=False,
        act_fun="gelu",
    ):
        super().__init__()
        self.layers = nn.ModuleList([])
        for _ in range(num_layers):
            self.layers.append(
                TransformerBlock(
                    embed_dim=embed_dim,
                    hidden_dim=hidden_dim,
                    num_heads=num_heads,
                    causal=causal,
                    attn_dropout=attn_dropout,
                    ffn_dropout=ffn_dropout,
                    attn_type=attn_type,
                    ffn_type=ffn_type,
                    norm_type=norm_type,
                    pre_norm=pre_norm,
                    act_fun=act_fun,
                )
            )

    def forward(self, x, y=None):
        for layer in self.layers:
            x = layer(x)

        return x


import pymysql

def changeword(a1):

    S1=1

    try:
        base = pymysql.connect('localhost', 'root', '', 'verb')
    except pymysql.OperationalError:
        print('Uknown')

    try:
        cursor = base.cursor()
    except pymysql.Error:
        print('cant get cursor')

    try:
        cursor.execute("SELECT `code_parent` FROM `verbs` WHERE `word`=%s",a1)
    except pymysql.Error:
        print('Cant Select')

    code = cursor.fetchone()

    try:
        cursor.execute("SELECT `word` FROM `verbs` WHERE`plural`=0 AND `face`='3-е' AND `code_parent`=%s",code)
    except pymysql.Error:
        S1=a1

    if S1==1:
        S1=cursor.fetchone()

    cursor.close()
    base.close()
    return (S1)


"""myproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""

from django.conf.urls import url
from django.contrib import admin

from pages import views

urlpatterns = [
    url(r'^$', views.home, name='home'),
    url(r'^admin/', admin.site.urls),
    url(r'^IncubatorProgramming/$', views.programmingPage, name='IncubatorProgramming'),
    url(r'^IncubatorSettingsPage/$', views.settingsPage, name='IncubatorSettingsPage'),
    url(r'^IncubatorHelpPage/$', views.helpPage, name='IncubatorHelpPage'),
    url(r'^IncubatorTemperature/$', views.temperatureView, name='IncubatorTemperature'),
    url(r'^IncubatorHumidity/$', views.humidityView, name='IncubatorHumidity'),

]


""" rabit mq worker process """
import time
import pika

SLEEP_TIME = 5
print(' [*] Sleeping for ', SLEEP_TIME, ' seconds.')
time.sleep(SLEEP_TIME)

print(' [*] Connecting to server ...')
credentials = pika.PlainCredentials('mq_user', 'mq_pwd')
connection = pika.BlockingConnection(pika.ConnectionParameters('rabbitmq3', 5672, '/', credentials))
channel = connection.channel()
channel.queue_declare(queue='task_queue', durable=True)

print(' [*] Waiting for messages.')

def callback(call_channel, method, properties, body):
    """ call back """
    print(f" [x] Received {body}")
    cmd = body.decode()

    if cmd == 'hey':
        print("hey there")
    elif cmd == 'hello':
        print("well hello there")
    else:
        print("sorry i did not understand ", body)

    print(" [x] Done")

    call_channel.basic_ack(delivery_tag=method.delivery_tag)

channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue='task_queue', on_message_callback=callback)
channel.start_consuming()


import logging

from shapely.geometry import Polygon, shape, mapping

PRECISION = 5

logger = logging.getLogger(__name__)

def round_geometry_coordinates(geometry: Polygon) -> Polygon:
    """round coordinates of polygon to reduce topology error and geojson file size"""
    geojson_geom = mapping(geometry)
    _round_geojson_coordinates(geojson_geom)
    return shape(geojson_geom)

def _round_geojson_coordinates(geojson_geom: dict) -> None:
    if geojson_geom['type'] == 'GeometryCollection':
        for geometry in geojson_geom['geometries']:
            return _round_geojson_coordinates(geometry)

    geojson_geom['coordinates'] = list(map(_round_coordinates, geojson_geom['coordinates']))

def _round_coordinates(coords) -> list:
    """Adapted from https://github.com/perrygeo/geojson-precision"""
    result = []
    try:
        return round(coords, PRECISION)
    except TypeError:
        for coord in coords:
            result.append(_round_coordinates(coord))

    return result


# Raspberry pi program for reading serial input and sending it to client via mqtt
import serial
import paho.mqtt.client as mqtt
import time

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

# Serial port

# MQTT
client = mqtt.Client()

client.on_connect = on_connect

print("Connecting...")
client.connect("localhost", 1883, 60)
client.loop()

start = time.time()

ser = serial.Serial(
    port='/dev/ttyUSB0',
    baudrate=9600,
)

while True:

    # Read serial input
    data = ser.readline()

    if(data is not None):
        if time.time() - start > 1:
            start = time.time()
            client.publish("RASP", 0b1000000000000000)
        else:
            client.publish("RASP", data)

    client.loop()


from flask import Flask, render_template, request, jsonify
# from flask_apscheduler import APScheduler

import requests, threading, json, os, subprocess, time

from . import compute_eta
from . import eta_computer

def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__, instance_relative_config=True)

    # Configuration
    # loads config from instance/config.py
    app.config.from_pyfile('config.py')

    # ensure the instance folder exists
    try:
        os.makedirs(app.instance_path)
    except OSError:
        pass

    # MODELS ---------
    import mongoengine as me
    from . import models
    app.models = models.init_models(app.config)
    app.me_connection = me.register_connection(db=app.config['MONGODB_DB_NAME'], alias=app.config['MONGOENGINE_DB_ALIAS'])
    app.me = me
    # ---------------
    # CLI COMMANDS --
    from . import flask_cli_commands
    flask_cli_commands.init_commands(app, app.models)
    # -----------
    # INSTANIATE THE ETA COMPUTER
    # original_working_directory = os.getcwd()
    # TODO:
    # put eta_computer in its own module folder... |-->
    # os.chdir(__name__)
    # subprocess.run(["python", "eta_computer.py"])
    # os.chdir(original_working_directory)
    # -----------

    @app.route('/generic_eta')
    def generic_eta():
        start_time = time.perf_counter()

        lat = float(request.args.get('lat'))
        lon = float(request.args.get('lon'))

        max_number_of_puvs = app.config['DEFAULT_MAX_NUMBER_OF_PUVS']
        if request.args.get('puvs') is not None:
            max_number_of_puvs = int(request.args.get('puvs'))

        destination = (lon, lat)
        normal_format_destination = (lat,lon)
        vehicle_segments_total_travel_time_array = eta_computer.generic_eta(app, destination,
        max_number_of_puvs=max_number_of_puvs,
        consider_destination_segment=app.config['CONSIDER_DESTINATION_SEGMENT'],
        route_direction=app.config['ROUTE_DIRECTION'],
        zombie_threshhold_timedelta=app.config['DEFAULT_ZOMBIE_TIMEDELTA']
        )

        # eta_seconds == 0 will not really evaluate to True --> should implement a tolerance check.
        visual_array = [ (vehicle, segments, "Vehicle has arrived!") if eta_seconds == 0 else (vehicle, segments, eta_seconds) for vehicle, segments, eta_seconds in vehicle_segments_total_travel_time_array]
        destination_segment_id = compute_eta.new_locate_segment(app, normal_format_destination)

        end_time = time.perf_counter()
        with open(os.path.join(os.getcwd(),"metrics/data/network_computation/generic_eta/computation.csv"), "a") as log_file:
            log_file.write("{},{},{},{}\n".format(end_time - start_time, max_number_of_puvs, app.models.Segment.objects.count(), app.models.VehicleSegmentData.objects.count()))

        return render_template('generic_eta.html', vehicle_segments_total_travel_time_array=visual_array, destination_segment_id=destination_segment_id)

    @app.route('/generic_eta.json')
    def generic_eta_json():
        start_time = time.perf_counter()

        lat = float(request.args.get('lat'))
        lon = float(request.args.get('lon'))

        max_number_of_puvs = app.config['DEFAULT_MAX_NUMBER_OF_PUVS']
        if request.args.get('puvs') is not None:
            max_number_of_puvs = int(request.args.get('puvs'))

        destination = (lon, lat)
        normal_format_destination = (lat,lon)
        vehicle_segments_total_travel_time_array = eta_computer.generic_eta(app, destination,
        max_number_of_puvs=max_number_of_puvs,
        consider_destination_segment=app.config['CONSIDER_DESTINATION_SEGMENT'],
        route_direction=app.config['ROUTE_DIRECTION'],
        zombie_threshhold_timedelta=app.config['DEFAULT_ZOMBIE_TIMEDELTA']
        )

        destination_segment_id = compute_eta.new_locate_segment(app, normal_format_destination)

        end_time = time.perf_counter()
        with open(os.path.join(os.getcwd(),"metrics/data/network_computation/generic_eta/computation.csv"), "a") as log_file:
            log_file.write("{},{},{},{}\n".format(end_time - start_time, max_number_of_puvs, app.models.Segment.objects.count(), app.models.VehicleSegmentData.objects.count()))

        ret_json = []
        for vehicle, segments, eta_seconds in vehicle_segments_total_travel_time_array:
            ret_json.append({
            "eta_seconds": eta_seconds,
            "vehicle": {
                "id": vehicle.vehicle_id,
                "location": vehicle.vehicle_location,
                "segment": vehicle.segment.segment_id
            },
            "segments_to_cross": len(segments)
            })
        return jsonify(ret_json)

    @app.route('/eta_visual')
    def eta_visual():
        # from client get destination coordinates
        # call identify_nearest_puv() when client requests for eta of nearest PUVs
        # compute for ETA of top 3 PUVs
        #
        top3_puv_ids = compute_eta.identify_nearest_puv()
        base_url = app.config['NIMPA_URL']
        rest_operation = '/latest_location?id='
        complete_URL = base_url + rest_operation + str(top3_puv_ids[2])
        return render_template('eta_visual.html', ids=top3_puv_ids, json_url_resource3=complete_URL)

    @app.route('/new_locate_segment')
    def new_locate_segment():
        lat = float(request.args.get('lat'))
        lon = float(request.args.get('lon'))
        coordinates = (lat, lon)
        print('HELLO')
        compute_eta.new_locate_segment(app, coordinates)

        return render_template('index.html')
    return app


#!/usr/bin/env python3

import datetime
import sys
# import mysql.connector
import time

from google.analytics.data_v1beta import BetaAnalyticsDataClient
from google.analytics.data_v1beta.types import (
    DateRange,
    Dimension,
    Metric,
    RunReportRequest,
)

# KEY_FILE_LOCATION = sys.argv[1]
KEY_FILE_LOCATION = "timelines-key.json"

LIMIT = 10000

def quote(x):
    """CSV-quote x."""
    x = x.replace('"', '""')
    return '"' + x + '"'

def main():
    client = BetaAnalyticsDataClient.from_service_account_json(KEY_FILE_LOCATION)

    # It would be ideal to use proc.pageviews_date_range in this script here,
    # because even though the GA API will just get the pageviews for the entire
    # valid period (thus it's no problem to specify a start date that is too
    # early), some pages may nevertheless get a few pageviews from before they
    # were fully created, and we ideally wouldn't want to count those
    # pageviews. However, using proc.pageviews_date_range to get the exact
    # valid range for each page's URL will require an API call for each URL and
    # I haven't done the math to see if GA API's usage limits allow this.  But
    # in any case, a page shouldn't be getting too many pageviews before it's
    # been marked as created (since logged in views don't count), so doing
    # things the easy way should not overestimate pageviews by very much (and
    # if a page is more than a year old, will yield identical results).
    today = datetime.date.today()
    start_date = max(datetime.date(today.year - 1, today.month, 1),
                     datetime.date(2023, 5, 1))
    # Stop getting pageviews at the last day of the previous month
    end_date = datetime.date(today.year, today.month, 1) - \
            datetime.timedelta(days=1)

    pageviews = pageviews_for_project(client, "364967470",
            start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))
    print("page_path,pageviews")
    for row in pageviews:
        path, views = row
        print(f"{quote(path)},{views}")

def get_report(client, property_id, start_date, end_date, offset=0):
    """Queries the Google Analytics 4 Data API v1."""
    print("Doing PropertyID=%s [%s, %s] (offset: %s)" % (
                property_id, start_date, end_date, offset), file=sys.stderr)

    # For pagination, see
    # https://developers.google.com/analytics/devguides/reporting/data/v1/basics#pagination

    request = RunReportRequest(
        property=f"properties/{property_id}",
        dimensions=[Dimension(name="pagePathPlusQueryString")],
        metrics=[Metric(name="screenPageViews")],
        date_ranges=[DateRange(start_date=start_date, end_date=end_date)],
        offset=offset,
        limit=LIMIT,
    )
    response = client.run_report(request)
    return response

def extracted_pageviews(response):
    """Extract the GA response into a list of tuples containing pageviews data,
    e.g. [('/wiki/Timeline_of_ChatGPT', 2201),
          ('/wiki/Timeline_of_online_food_delivery', 1189),
          ('/wiki/Timeline_of_OpenAI', 659), ...]."""
    result = []
    for row in response.rows:
        dimensions = row.dimension_values  # the pagepath
        pagepath = dimensions[0].value
        pageviews_values = row.metric_values
        assert len(pageviews_values) == 1, pageviews_values
        pageviews = int(pageviews_values[0].value)
        result.append((pagepath, pageviews))
    return result

def pageviews_for_project(client, property_id, start_date, end_date):
    result = []
    if start_date > end_date:
        # This means we already have all the most recent data, so don't query
        return result

    offset = 0
    while True:
        time.sleep(1)
        response = get_report(client, property_id, start_date,
                              end_date, offset)
        result.extend(extracted_pageviews(response))
        offset += LIMIT
        if offset >= response.row_count:
            # The comparison >= is the correct one here (not >) because
            # the first row is considered row 0 according to
            # https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/properties/runReport#body.request_body.FIELDS.offset
            # So e.g. if there are five rows, they will be rows 0,1,2,3,4, and
            # if offset is >=5 then there will be no more rows to fetch. (I
            # also empirically checked that this is the actual behavior of the
            # API.)
            break
    return result

if __name__ == "__main__":
    main()


import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d as plt3d
import numpy as np
import numpy.random as r
import scipy.stats as s
from scipy.special import comb

def basic(numVars, numPoints, p = 0.05, showBest = False):
    dists = {}
    count = 0
    if showBest:
        best = {0:0, 1:0, 2:0}
    for i in range(0, numVars): #generate data
        dists[i] = r.normal(0,1,numPoints)
    for i in range(0, numVars):
        for j in range (i+1, numVars):
            pearson = s.pearsonr(dists[i], dists[j])
            if pearson[1] < p: #count correlations significant at given p-value, default is p < 0.05
                count += 1
                if showBest and abs(pearson[0]) > best[0]:
                    best[0] = abs(pearson[0])  #show most impressive correlation
                    best[1] = i
                    best[2] = j
    if showBest and not best[0] == 0:
        plt.scatter(dists[best[1]], dists[best[2]])
        print(s.pearsonr(dists[best[1]], dists[best[2]]))
        plt.show()
    return count

def plotVarEffect(maxVars, points, varStep, repeat = 1, showDerivatives=0, bonferroni = False):
    x = range(2, maxVars, varStep)
    counts = []
    for numVars in x:
        trials = []
        for _ in range(0, repeat):
            if bonferroni:  #if bonferroni correction is turned on,
                trials.append(basic(numVars, points, p=0.05/comb(numVars, 2)))   #test each hypothesis at a/m to get confidence a, where m is # of hypotheses
            else:
                trials.append(basic(numVars, points))  #if bonferroni is off, just test naively at desired significance level
        counts.append(np.mean(trials)) #record significant correlations found
        print(str(int(numVars/maxVars*100))+'%')
    plt.scatter(x, counts)
    plt.xlabel('variables')
    plt.ylabel('false correlations')
    if showDerivatives > 0:
        data = counts
        for i in range(1, showDerivatives + 1):
            deriv = []
            for j in range(0, len(data) - 1):
                deriv.append((data[j+1] - data[j]) / varStep)
            plt.figure()
            plt.scatter(x[:-i], deriv)
            plt.xlabel('variables')
            plt.ylabel('derivative ' + str(i) + ' of correlations')
            plt.ylim(bottom = 0)
            data = deriv
    plt.show()

def plotPointEffect(variables, maxPoints, pointStep, repeat = 1, showDerivatives = 0, bonferroni = False):
    x = range(3, maxPoints, pointStep)
    counts = []
    for numPoints in x:
        trials = []
        for _ in range(0, repeat):
            if bonferroni:  #if bonferroni correction is turned on,
                trials.append(basic(variables, numPoints, p=0.05/comb(variables, 2)))   #test each hypothesis at a/m to get confidence a, where m is # of hypotheses
            else:
                trials.append(basic(variables, numPoints))  #if bonferroni is off, just test naively at desired significance level
        counts.append(np.mean(trials))
        print(str(int(numPoints/maxPoints*100))+'%')
    plt.scatter(x, counts)
    plt.xlabel('points per variable')
    plt.ylabel('correlations')
    plt.ylim(bottom = 0)
    if showDerivatives > 0:
        data = counts
        for i in range(1, showDerivatives + 1):
            deriv = []
            for j in range(0, len(data) - 1):
                deriv.append((data[j+1] - data[j]) / pointStep)
            plt.figure()
            plt.scatter(x[:-i], deriv)
            plt.xlabel('points per variable')
            plt.ylabel('derivative ' + str(i) + ' of correlations')
            data = deriv
    plt.show()

def plotEffect2d(maxVars, maxPoints, varStep, pointStep, bonferroni = False):
    x = range(2, maxPoints, pointStep)
    y = range(3, maxVars, varStep)
    counts = np.zeros((len(y), len(x)))
    for variables in range(0, len(y)):
        for points in range(0, len(x)):
            if bonferroni:  #if bonferroni correction is turned on,
                counts[variables][points] = basic(y[variables], x[points], p=0.05/comb(variables, 2))   #test each hypothesis at a/m to get confidence a, where m is # of hypotheses
            else:
                counts[variables][points] = basic(y[variables], x[points])  #if bonferroni is off, just test naively at desired significance level
        print(str(int(y[variables]/maxVars*100))+'%')
    fig = plt.figure()
    ax = fig.add_subplot(111, projection = '3d')
    X, Y = np.meshgrid(x, y)
    ax.plot_surface(X, Y, counts)
    ax.set_xlabel('data points')
    ax.set_ylabel('variables')
    ax.set_zlabel('correlations found')
    plt.show()

#print(basic(1000, 20, showBest=True))    #basic example. Pretty strong correlations can pop up randomly if you scan enough variables
#plotVarEffect(1000, 10, 100)    #adding variables increases false correlations, superlinear (derivatives?)
#plotVarEffect(200, 10, 20, 100, 2)      #false correlations are roughly quadratic with variables. High derivatives need many trials
#plotPointEffect(20, 200, 10, 100, 1)      #adding more data points has no effect (yeah I did some more research and this makes sense)
#plotEffect2d(500, 200, 50, 20)    #show pointEffect and varEffect  (haha this method is kinda useless now)
#plotVarEffect(200, 10, 2, bonferroni = True)    #with Bonferroni correction, false correlations occur about 1/20 times. p-value correct


import os
import cv2
from glob import glob

def load_good_dices():
    normal_data_dir = os.path.join('.', 'assets', 'data', 'normal_dice', '*')
    normal_files_folders = glob(normal_data_dir)
    normal_files_paths = []
    labels = []
    for folder in normal_files_folders:
        files = glob(folder + '\\*.jpg')
        normal_files_paths += files
        labels += [int(os.path.basename(folder))] * len(files)

    print(f"{len(normal_files_paths)} normal files found")
    print(f"{len(labels)} normal files labels found")
    # for x in range(len(anomalous_files)):
    #    print(anomalous_files[x])

    return load_images(normal_files_paths), labels

def load_anomalous_dices():
    anomalous_data_dir = os.path.join('.', 'assets',  'data', 'anomalous_dice', '*.jpg')

    anomalous_files = glob(anomalous_data_dir)
    print(f"{len(anomalous_files)} anomalous files found")
    return load_images(anomalous_files), [11]*len(anomalous_files)

def load_images(images_path):
    img_size = 224
    images = []
    for img in images_path:
        try:
            img_arr = cv2.imread(img, 0)  # convert BGR to RGB format
            resized_arr = cv2.resize(img_arr, (img_size, img_size))  # Reshaping images to preferred size
            images.append(resized_arr)
        except Exception as e:
            print(e)
    return images


from PIL import Image, UnidentifiedImageError
import requests
from io import BytesIO
import time
import numpy as np
import cv2

from aruco_ekf import ArUcoEnv, ArUcoEKF, CameraAgent

UPDATE_INTERVAL = 0.1
ENV = ArUcoEnv(np.array([[1,0,1,0,np.pi/2,0], [5,0,0,0,-np.pi/2,0], [-1,0,3,0,0,0], [0,0,-2,0,np.pi,0]]))

ARUCO_DICT = {
    "DICT_4X4_50": cv2.aruco.DICT_4X4_50, "DICT_4X4_100": cv2.aruco.DICT_4X4_100, "DICT_4X4_250": cv2.aruco.DICT_4X4_250, "DICT_4X4_1000": cv2.aruco.DICT_4X4_1000,
    "DICT_5X5_50": cv2.aruco.DICT_5X5_50, "DICT_5X5_100": cv2.aruco.DICT_5X5_100, "DICT_5X5_250": cv2.aruco.DICT_5X5_250, "DICT_5X5_1000": cv2.aruco.DICT_5X5_1000,
    "DICT_6X6_50": cv2.aruco.DICT_6X6_50, "DICT_6X6_100": cv2.aruco.DICT_6X6_100, "DICT_6X6_250": cv2.aruco.DICT_6X6_250, "DICT_6X6_1000": cv2.aruco.DICT_6X6_1000,
    "DICT_7X7_50": cv2.aruco.DICT_7X7_50, "DICT_7X7_100": cv2.aruco.DICT_7X7_100, "DICT_7X7_250": cv2.aruco.DICT_7X7_250, "DICT_7X7_1000": cv2.aruco.DICT_7X7_1000,
    "DICT_ARUCO_ORIGINAL": cv2.aruco.DICT_ARUCO_ORIGINAL,
    "DICT_APRILTAG_16h5": cv2.aruco.DICT_APRILTAG_16h5, "DICT_APRILTAG_25h9": cv2.aruco.DICT_APRILTAG_25h9, "DICT_APRILTAG_36h10": cv2.aruco.DICT_APRILTAG_36h10,"DICT_APRILTAG_36h11": cv2.aruco.DICT_APRILTAG_36h11
}

CAMERA_INTRINSIC = np.array([[608.58924596, 0,           314.4157201],
                             [0,            609.1273208, 234.53093946],
                             [0,            0,           1]])
CAMERA_DISTORTION = np.array([4.88590894e-02, 5.80568720e-01, 1.22917285e-03, -1.98513739e-03, -2.41165314e+00])

if __name__ == '__main__':
    aruco_type = "DICT_5X5_100"
    ekf = ArUcoEKF(ENV, np.array([0.8994711026693413, -1.6668953491807064, 1.074997912251441]).T)
    camera_agent = CameraAgent(ENV, ARUCO_DICT[aruco_type], CAMERA_INTRINSIC, CAMERA_DISTORTION)

    t = time.time()
    while True:
        try:
            # Get responses from Rest API
            img_response = requests.get('http://192.168.0.1/cam0')
            odom_response = requests.get('http://192.168.0.1/data/odometry')
            # Convert data from response
            camera_agent.last_image = np.array(Image.open(BytesIO(img_response.content)))

            odom = odom_response.json()
            dt, t = time.time()-t, time.time()
            vel = np.array(odom[3:6]).T

            # Perform kalman filtering
            ekf.predict(vel, dt)
            ekf.update(camera_agent)

            print('state, odom', ekf.state, odom[:3])
            print('dt', dt)

            time.sleep(UPDATE_INTERVAL)

        except UnidentifiedImageError:
            print('Unable to retrieve camera image')

        except requests.exceptions.JSONDecodeError:
            print('Unable to retrieve odometry data')

        except KeyboardInterrupt:
            print(' Keyboard Interrupt')
            break


import PyPDF4 as pdff
import pyttsx3 as tts

#set the voice to 'en' or 'pt'

'''Some pdf files not works, so you need to open it with text editor like word from windows and save it as pdf.'''
#To Read Pdf File
file_path = 'Richard Dawkins - O Capelão do Diabo.pdf'
file1 = pdff.PdfFileReader(open(file_path, 'rb'))

#Instance of speaker
readder = tts.init()

#Reader page by page in Unicode
#Just because this book, I did start to read from page 6
for paper in range(6,file1.getNumPages()):
    sheett = file1.getPage(paper)
    ready = sheett.extractText()
    # If you want save audio
    readder.save_to_file(ready, f'book_{paper}.mp3')
    print(ready)
    readder.say(ready)
    readder.runAndWait()


import flet as ft
import flet_fastapi
import os
from components.page_header.page_header import PageHeader
from components.search_bar.search_bar import SearchBar
from components.bookmarks.bookmarks import Bookmarks
from components.socials.socials import Socials
from utils import *

async def main(page: ft.Page):
    page.title = "Subhradeep's Custom Homepage"
    page.fonts = fonts
    page.vertical_alignment = ft.MainAxisAlignment.CENTER

    ref_search_field = ft.Ref[ft.TextField]()

    async def on_keyboard(e: ft.KeyboardEvent):
        if e.key == "/":
            ref_search_field.current.focus()
        await page.update_async()

    content = ft.Column(
        [
            PageHeader(),
            ft.Container(
                SearchBar(
                    page,
                    ref_search_field
                ),
                padding=5
            ),
            Socials(),
            Bookmarks(),
        ],
        spacing=35,
        expand=True,
        scroll=ft.ScrollMode.HIDDEN,
        horizontal_alignment=ft.CrossAxisAlignment.CENTER,
    )

    page.on_keyboard_event = on_keyboard

    await page.add_async(
        content
    )

app = flet_fastapi.app(main, assets_dir=os.path.abspath("assets"))


from django.conf import settings
from django.db import models

class Image(models.Model):
    url = models.URLField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    posted_at = models.DateTimeField()
    height = models.IntegerField(null=True, blank=True)
    width = models.IntegerField(null=True, blank=True)
    is_validated = models.BooleanField(default=True)
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        null=True
    )

    def __str__(self):
        return f"[{self.id}] | {self.url}"


import os
import dj_database_url
"""
Django settings for newsapp project.

For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'mydatabase',
    }
}

db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.7/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'f50_i!-#i4v7u$!dqutwp3trr!wn5&v_mwf9j4dw1&m$97qzn%'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

#TEMPLATE_DEBUG = True

ALLOWED_HOSTS = ['127.0.0.1','crazinfo.herokuapp.com','localhost']

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'news',
    'rest_framework',
    'channels',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

#TEMPLATE_CONTEXT_PROCESSORS = (
#    "django.contrib.auth.context_processors.auth",
 #   "django.core.context_processors.debug",
  #  "django.core.context_processors.i18n",
  #  "django.core.context_processors.media",
 #   "django.core.context_processors.request",
#)
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
	'OPTIONS': {
            'context_processors': [
                # Insert your TEMPLATE_CONTEXT_PROCESSORS here or use this
                # list if you haven't customized them:
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.contrib.messages.context_processors.messages',
		'django.template.context_processors.request',
            ],
            'debug':DEBUG,
	},
    },
]
ROOT_URLCONF = 'newsapp.urls'

WSGI_APPLICATION = 'newsapp.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.7/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.7/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "asgi_redis.RedisChannelLayer",
        "CONFIG": {
            "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
        },
        "ROUTING": "news.routing.channel_routing",
    },
}

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.7/howto/static-files/
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage'

STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "static"),
]

STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles')
"""
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
	'applogfile': {
        'level':'DEBUG',
        'class':'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(BASE_DIR, 'news.log'),
        'maxBytes': 1024*1024*5, # 5MB
        'backupCount': 10,
    	},
    },
    'loggers': {
        'django': {
            'handlers': ['console','applogfile'],
            'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'),
        },
	'news':{
            'handlers': ['applogfile',],
            'level': 'DEBUG',
	},
    },
}
"""
STATIC_URL = '/static/'
LOGIN_URL='/news/login/'
LOGIN_REDIRECT_URL='/news/'


import places as p
import distance as d

import tsp
import maps

city = "Charlotte"
time_limit = 3600

places = p.getPlaces(city)
p.quickPrintPlaces(places)
#print(len(places))

matrix_approx = d.adjMatrixApprox(places)
#d.printMatrix(matrix_approx)

order = tsp.find_route(matrix_approx, places, time_limit, tsp.metric_func)
order, distances, durations = maps.solve(order)

for i in range(len(distances)):
    order[i].print()
    print("Walk " + str(distances[i]) + " feet for " + str(durations[i]) + " seconds to the next stop\n")

order[-1].print()


# 1 этап. Порождение грамматик
from functools import reduce
# Считать имя файла источника. Если пустое - text.txt
try:
    source = input('Файл-источник: ')
except EOFError:
    source = 'text.txt'
if len(source) == 0:
    source = 'text.txt'

# Считать источник по строкам
with open(source, 'r', encoding='utf-8') as fi:
    text = fi.read().replace('\n', ' ').lower().split()
print('Исходый текст:', *text)

# Составить словарь. Строки разбить на слова, убрать все знаки препинания,
# присоединить к словарю, отсортировать по длине
vocab = sorted(set([w.strip('.,:;<>?/\'"|\\~•`!@#$%^&*()_-+=[]{}№') for w in text]), key=len, reverse=True)
print('Словарь:', *vocab)

# Составить алфавит, отсортировать
abc = sorted(set(reduce(lambda letters, x: letters.union([c for c in x if c.isalnum()]), vocab, set())))
print('Алфавит:', *abc)
with open('text.voc', 'w', encoding='utf-8') as fv, open('text.abc', 'w', encoding='utf-8') as fa:
    [print(w, file=fv) for w in vocab]
    print(*abc, file=fa)

# Функция ищет правило с левой частью = an, в правой части терминальный начальный символ слова w,
# возвращает нетерминальную часть или -1 если не найдено
def rulex(w, an):
    for r in rules:
        if len(w) > 0 and w[0] == r.right[0] and an == r.left:
            return r.right[1]
    return -1

# Функция строит все цепочки из узла rr длиной <= n
def getchaines(rp, n):
    if n == 0 or rp.right[1] == 0:
        return {rp.right[0]}
    result = set()
    for r in rules:
        if rp.right[1] == r.left:
            result |= set([rp.right[0] + r for r in getchaines(r, n - 1)])
    return result

def twinremove():
    # Удаляем дубли
    cnt = len(rules) - 1
    while cnt > 1:
        for i in range(cnt - 1, 0, -1):
            if rules[cnt].left == rules[i].left and rules[cnt].right == rules[i].right:
                del rules[cnt]
                cnt -= 1
        cnt -= 1

# Правило вывода: left - левая часть (0 - начало), rstr - терминальная правая часть,
# rnterm - нетерминальная правая часть (0 - окончание)
class Rule:
    def __init__(self, left=0, rstr='', rnterm=0):
        self.left = left
        self.right = (rstr, rnterm)

maxlen = len(vocab[0])  # Максимальная длина слова
rules, cnt, cntl = [], 1, 0  # Список правил, следующий номер для нового правила, локальный номер для поиска

# По словам словаря
for w in vocab:
    cntl = 0
# Ищем по цепочке от начала (0) до первого несовпадения
    while rulex(w, cntl) >= 0:
        cntl = rulex(w, cntl)
        w = w[1:]
# Далее строить новую подцепочку. Если слово максимальной длины, остаточное правило длины 2, иначе 1
    if len(w) == maxlen:
        restlen = 2
    else:
        restlen = 1

# Строим новую ветвь дерева от последнего совпавшего узла
    while len(w) > restlen:
        rules.append(Rule(cntl, w[0], cnt))
        w, cntl, cnt = w[1:], cnt, cnt + 1
    rules.append(Rule(cntl, w))

# Проверить, что остаток цепочки максимальной длины является суффиксом цепочки меньшей длины
    if maxlen == 2 and all(not r.endswith(w) for r in vocab if len(r) < maxlen):
        vocab.append(w)

# Распечатать и сохранить в файле правила отсортированные по левой части
rules = sorted(rules, key=lambda x: x.left)
[print(r.left, '->', *r.right) for r in sorted(rules, key=lambda x: x.left)]
print()
with open('text.rul', 'w', encoding='utf-8') as fr:
    [print(r.left, '->', *r.right, file=fr) for r in rules]

# 2 этап Получение рекурсивной грамматики
# Соединение правил остатка длины 2 с неостаточными цепочками
# Выбираем все остаточные правила длины 2
restrules = [[r, None, None] for r in rules if len(r.right[0]) == 2]

for r in restrules:
    rr, rn, rm = r[0].left, r[0].right[0][0], r[0].right[0][1]
    # Ищем правило n для правила r по второму символу
    for i in range(len(rules)):
        if rules[i].right[1] == 0 and len(rules[i].right[0]) == 1 and rules[i].right[0] == rm:
            # Ищем правило m для правила n по левой части и для правила r по первому символу
            for j in range(i - 1, 0, -1):
                if rules[j].right[1] == rules[i].left and rules[j].right[0] == rn:
                    # Если найдены n, m - заносим в список к правилу r
                    r[1], r[2] = rules[j], rules[i]
                    break
        if r[2] is not None:
            break
# По списку производим замену
for r in restrules:
    if r[1] is not None:
        rules.remove(r[0])
        for rule in rules:
            if rule.right[1] == r[0].left:  # Если правая часть совпадает с r - заменить на n
                rule.right = (rule.right[0], r[1].left)
            if rule.left == r[0].left:  # Если левая часть совпадает с r - заменить на n
                rule.left = r[1].left
# Удалить дубли
twinremove()
print('***2 part end')
[print(r.left, '->', *r.right) for r in rules]

# 3 этап Объединение совпадающих цепочек
chaineslist = []
i = 0
while i < len(rules):
    # Получить все цепочки для узла rch длиной не более len(rules)
    chaines = getchaines(rules[i], len(rules))
    chuniq = True
    for ch in chaineslist:
        # Если множество цепочек проверяемого Aj эквивалентно сохранённому уникальному множеству цепочек узла Ai
        if chaines == ch[1]:
            aj, ai = ch[0].left, rules[i].left
            # Поменять все вхождения Aj на Ai и в левых и в правых частях правил вывода в основном списке
            for rr in rules:
                if rr.left == aj:
                    rr.left = ai
                if rr.right[1] == aj:
                    rr.right = (rr.right[0], ai)
            # и в списке для проверки множества цепочек
            for rch in chaineslist:
                if rch[0].left == aj:
                    rch[0].left = ai
                if rch[0].right[1] == aj:
                    rch[0].right = (rch[0].right[0], ai)
            chuniq = False
            break
    # Если не нашлось узла Ai, на который поменяли Aj, множество цепочек уникально, сохраняем его с узлом
    if chuniq:
        chaineslist.append((rules[i], chaines))
    i += 1
# Удалить дубли
twinremove()
print('*** 3 part end: new rules:')
[print(r.left, '->', *r.right) for r in rules]
# Сохраняем результат в файле text.res
with open('text.res', 'w',  encoding='utf-8') as fr:
    [print(r.left, '->', *r.right, file=fr) for r in rules]


import pytest

from django import test
from rest_framework import status

from calendar_j.services.attendance import attendance
from calendar_j.services.protection import protection
from utils.test import compare as compare_utils
from utils.test import data as data_utils

@pytest.fixture(name="user1")
def fixture_registered_user1(client: test.Client):
    user1_data = data_utils.UserData.create_nth_user_data(1)
    client.post(path="/api/v1/user/registration/", data=user1_data.for_registration, content_type="application/json")
    return user1_data

@pytest.fixture(name="user2")
def fixture_registered_user2(client: test.Client):
    user2_data = data_utils.UserData.create_nth_user_data(2)
    client.post(path="/api/v1/user/registration/", data=user2_data.for_registration, content_type="application/json")
    return user2_data

@pytest.fixture(name="user3")
def fixture_registered_user3(client: test.Client):
    user3_data = data_utils.UserData.create_nth_user_data(3)
    client.post(path="/api/v1/user/registration/", data=user3_data.for_registration, content_type="application/json")
    return user3_data

@pytest.mark.django_db
def test_attendance_success(
    client: test.Client,
    user1: data_utils.UserData,
    user2: data_utils.UserData,
    user3: data_utils.UserData,
):
    """Test Schedule Attendance Update API"""
    client.post(path="/api/v1/user/login/", data=user1.for_login, content_type="application/json")

    schedule1_data = data_utils.ScheduleData.create_nth_schedule_data(
        n=1, protection_level=protection.ProtectionLevel.FOLLOWER, participant_ids=[2, 3]
    ).as_dict()
    client.post(
        path="/api/v1/calendar/schedule/",
        data=schedule1_data,
        content_type="application/json",
    )

    # Cannot Update
    response = client.patch(
        path="/api/v1/calendar/schedule/1/attendance/",
        data={"status": attendance.AttendanceStatus.HOLD},
        content_type="application/json",
    )
    compare_utils.assert_response_equal(response, status.HTTP_404_NOT_FOUND)

    client.post("/api/v1/user/logout/")
    client.post("/api/v1/user/login/", data=user2.for_login, content_type="application/json")

    # Can Update
    response = client.patch(
        path="/api/v1/calendar/schedule/1/attendance/",
        data={"status": attendance.AttendanceStatus.HOLD},
        content_type="application/json",
    )
    expected = {"id": 1, "status": attendance.AttendanceStatus.HOLD, "participant": 2, "schedule": 1}

    compare_utils.assert_response_equal(response, status.HTTP_200_OK, expected)


from django.shortcuts import render, redirect

from equation.forms import CommentForm, ValuesForm
from equation.models import Comments
from services import solution_of_the_equation

def homepage(request):
    """ Returning the main page """
    comments = Comments.objects.all().order_by('-created_at')[:5]

    if request.method == "POST":
        form = ValuesForm(request.POST)
        if form.is_valid():
            values = form.cleaned_data
            answer = solution_of_the_equation(values)
            context = {
                'form': form,
                'answer': answer,
                'comments': comments
            }
            return render(request, 'equation/homepage.html', context)
    else:
        form = ValuesForm()
        context = {
            'form': form,
            'comments': comments
        }
        return render(request, 'equation/homepage.html', context)

def comment_page(request):
    """ Display comments """
    if request.method == "POST":
        form = CommentForm(request.POST)
        if form.is_valid():
            comment = form.save(commit=False)
            comment.save()
        return redirect('homepage')
    else:
        form = CommentForm()
        context = {
            'form': form
        }
        return render(request, 'equation/new_comment.html', context)


from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import math
from selenium.webdriver.support.ui import Select
import os

def calc(x):
  return str(math.log(abs(12*math.sin(int(x)))))

try:
    link = "http://suninjuly.github.io/redirect_accept.html"
    browser = webdriver.Chrome()
    browser.get(link)

    button = browser.find_element(By.CSS_SELECTOR, ".trollface.btn.btn-primary") # клацнуть на кнопку
    button.click()

    new_window = browser.window_handles[1]  # узнаем имя вкладки, через массив всех имен вкладок, просим вывести нужную по порядку (если знаем)
    browser.switch_to.window(new_window) #переход на новую вкладку, в скобках имя новой вкладки

    X = browser.find_element(By.CSS_SELECTOR, "[id='input_value']") # находим элемент x на странице
    x = X.text
    y = calc(x) # посчитать формулу
    print(y)

    Answer = browser.find_element(By.CSS_SELECTOR, "[id='answer']") # передать в поле значение
    Answer.send_keys(y)

    button2 = browser.find_element(By.CSS_SELECTOR, ".btn.btn-primary") # клацнуть на кнопку
    button2.click()

finally:
    # ожидание чтобы визуально оценить результаты прохождения скрипта
    time.sleep(10)
    # закрываем браузер после всех манипуляций
    browser.quit()
    # пустая строка

#ALERT
#alert('Hello!');

#согласиться с ошибкой в модальном окне, чтобы закрыть его
#переходим на окно и соглашаемся
#alert = browser.switch_to.alert
#alert.accept()
#confirm.dismiss() #отказаться в модальном окне

#Чтобы получить текст из alert, используйте свойство text объекта alert:
#alert = browser.switch_to.alert
#alert_text = alert.text

#чтобы ввести текст в модальное окно
#prompt = browser.switch_to.alert
#prompt.send_keys("My answer")
#prompt.accept()

#BROWSER_WINDOW
#browser.switch_to.window(window_name) #переход на новую вкладку, в скобках имя новой вкладки
#new_window = browser.window_handles[1] #узнаем имя вкладки, через массив всех имен вкладок, просим вывести нужную по порядку (если знаем)
#first_window = browser.window_handles[0] #имя текущей вкладки, для дальнейшей работы с ней

#    X = browser.find_element(By.CSS_SELECTOR, "[id='input_value']") # находим элемент x на странице
#    x = X.text
#    y = calc(x) # посчитать формулу
#    print(y)
#    browser.execute_script("window.scrollTo(0, 180)") # прокрутить страницу на заданное кол-во пикселей

#    FirstName = browser.find_element(By.CSS_SELECTOR, "[placeholder='Enter first name']") # передать в поле значение
#    FirstName.send_keys("Artem")

#вставить файл
#    current_dir = os.path.abspath(os.path.dirname(__file__))  # получаем путь к директории текущего исполняемого файла
#    file_name = "for_add_txt_file.txt"
#    file_path = os.path.join(current_dir, file_name)  # добавляем к этому пути имя файла
#    element = browser.find_element(By.CSS_SELECTOR, "[id='file']")
#paste_manual    element.send_keys("C:\\Users/Minchenko_KL\\PycharmProjects\\Stepik\\venv\\for_add_txt_file.txt")
#paste_auto    element.send_keys(file_path)

#    StepSix = browser.find_element(By.CSS_SELECTOR, "[for='robotCheckbox']") #клацнуть на чекбокс
#    StepSix.click()

#    StepSeven = browser.find_element(By.CSS_SELECTOR, "[for='robotsRule']")  # клацнуть на радиокнопку
#    StepSeven.click()

#    button = browser.find_element_by_tag_name("button")
#    browser.execute_script("return arguments[0].scrollIntoView(true);", button)
#    button.click()

#    select = Select(browser.find_element(By.TAG_NAME, "select"))
#    select.select_by_visible_text(str(x))


import argparse
import os
from sklearn.utils import shuffle
from tqdm import tqdm

parser = argparse.ArgumentParser(description='Simple data generator')
parser.add_argument("data", type=str, help="Name of the dataset")
parser.add_argument('-n', '--names', type=int, default=None, help="Number of unique names")
parser.add_argument('-s', '--size', type=int, default=None, help="Average object size")
parser.add_argument('-e', '--seed', type=int, default=None, help="Random generator seed")
parser.add_argument('-r', '--requests', type=int, default=10000000, help="Number of requests to generate")
parser.add_argument('-f', '--rpf', type=int, default=1000000, help="Number of requests per file")
parser.add_argument('-w', '--workload', type=float, default=0.7, help="Percentage read requests in workload")

args = parser.parse_args()

import numpy as np
np.random.seed(args.seed)

requests = args.requests

if args.names is None:
    number_of_names = np.random.randint(requests / 1000, 2 * requests / 1000)
else:
    number_of_names = args.names

if args.size is None:
    size = 20 * 1024
else:
    size = args.size

out_path = os.path.join('data/', args.data)
if not os.path.exists(out_path):
    os.makedirs(out_path)

print('Generating sizes')
names_size_mapping = np.random.poisson(size, size=number_of_names)

access_map = {}

file_counter = 0
num_get = 0
num_put = 0

stime = 0

for i in range(0, requests, args.rpf):
    reqs_to_generate = min(requests - i, args.rpf)
    print('Generating', reqs_to_generate, 'requests. Done', i, 'out of', requests)

    p_ids = np.random.poisson(int(number_of_names/2), int(reqs_to_generate/2))
    l_ids = np.random.randint(0, number_of_names, size=reqs_to_generate)
    # l_ids = np.random.logistic(loc=10, scale=1, size=int(reqs_to_generate/2))
    ids = np.concatenate((p_ids, l_ids), axis=None)
    ids = shuffle(ids)

    # ids = np.random.randint(0, number_of_names, size=reqs_to_generate)

    timestamps = np.random.exponential(0.5, size=reqs_to_generate).astype(np.int)
    timestamps = stime + np.cumsum(timestamps)

    with open(os.path.join(out_path, str(file_counter) + '.csv'), 'w') as f:
        for j in tqdm(range(reqs_to_generate)):
            if ids[j] in access_map:
                request_type = 'GET' if np.random.rand() <= args.workload else 'PUT'
                access_map[ids[j]] = access_map[ids[j]] + 1
            else:
                request_type = 'PUT'
                access_map[ids[j]] = 1

            if request_type == 'GET':
                num_get += 1
            else:
                num_put += 1
            wstr = str(timestamps[j]) + ',' + str(int(ids[j])) + ',' + str(names_size_mapping[int(ids[j])]) + ',' + str(request_type) + '\n'
            f.write(wstr)

    file_counter += 1
    stime = max(timestamps)

print(num_get, num_put)


import os, sys, time, json
import numpy as np
import matplotlib.pyplot as plt
import matplotlib

COLORS = ['tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple', 'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan']

def main(path_to_folder, use_plots=None, plot_type=0, name=None, save_=True):

    use_plots = None if use_plots in [None, ''] else [int(n) for n in use_plots.split(';')]
    plot_type = int(plot_type)

    fig_folder = os.path.join('log', 'figures', f'{time.strftime("%Y-%m-%d-%H_%M_%S")}_ti_one_plot{f"_{name}" if name is not None else ""}')
    if not os.path.isdir(fig_folder) and save_:
        os.mkdir(fig_folder)
        os.mkdir(os.path.join(fig_folder, 'png'))

    with open(os.path.join(path_to_folder, 'roll_out_results.json'), 'r') as f:
        # Copy so not both changed during updates
        paths = npify_dict(json.load(f))

    task_dict = None
    if os.path.exists(os.path.join(path_to_folder, 'task_dict.json')):
        with open(os.path.join(path_to_folder, 'task_dict.json'), 'r') as f:
            # Copy so not both changed during updates
            task_dict = json.load(f)
            task_dict = {el: key for key, el in task_dict.items()} if task_dict is not None else None

    plotting_data = {}
    for path in paths:
        base_task = path['true_tasks'][0, 0]['base_task']
        spec = path['true_tasks'][0, 0]['specification']
        spec = f"{int(spec * 100) / 100 if type(spec) is float or type(spec) is np.float64 else [int(k * 100) / 100 for k in spec]}"

        task_map = {'velocity_forward': 8, 'velocity_backward': 8,
                    'goal_forward': 17, 'goal_backward': 17,
                    'flip_forward': 9, 'jump': 10,
                    'stand_front': 1, 'stand_back': 1}

        rewards = path['observations'][:, task_map[task_dict[base_task]]]

        if base_task in plotting_data.keys():
            plotting_data[base_task][spec] = rewards
        else:
            plotting_data[base_task] = {spec: rewards}

    target_map = {'velocity_forward': 'Velocity', 'velocity_backward': 'Velocity',
                'goal_forward': 'Distance', 'goal_backward': 'Distance',
                'flip_forward': 'Velocity', 'jump': 'Velocity',
                'stand_front': 'Angle', 'stand_back': 'Angle'}

    class_map = {'flip_forward': 'Front flip', 'jump': 'Jump',
                 'goal_backward': 'Goal in back', 'goal_forward': 'Goal in front',
                 'stand_back': 'Back stand', 'stand_front': 'Front stand',
                 'velocity_backward': 'Run backward', 'velocity_forward': 'Run forward'}

    # Start plotting
    print(f'Plotting ...')

    plt.style.use('seaborn')

    # Use Latex text
    matplotlib.rcParams['pdf.fonttype'] = 42
    matplotlib.rcParams['ps.fonttype'] = 42
    matplotlib.rcParams['mathtext.fontset'] = 'stix'
    matplotlib.rcParams['font.family'] = 'STIXGeneral'
    #matplotlib.rcParams['font.size'] = 24

    if plot_type == 0:
        size_ = 32
    elif plot_type == 1:
        size_ = 38
    else:
        size_ = 12
    plt.rc('figure', titlesize=size_*1.0)  # fontsize of the figure title
    plt.rc('axes', titlesize=size_*1.0)  # fontsize of the axes title
    plt.rc('axes', labelsize=size_*1.0)  # fontsize of the x and y labels
    plt.rc('xtick', labelsize=size_*0.8)  # fontsize of the tick labels
    plt.rc('ytick', labelsize=size_*0.8)  # fontsize of the tick labels
    plt.rc('legend', fontsize=size_*0.8)  # legend fontsize

    n_plots = len(plotting_data.keys()) if use_plots is None else len(use_plots)
    fig, axs = plt.subplots(int(np.ceil(n_plots / 4)), min([n_plots, 4]))
    axs = axs.reshape(-1) if type(axs) is np.ndarray else [axs]

    for fig_nr, base_task in enumerate(plotting_data.keys()) if use_plots is None else enumerate(use_plots):
        title = task_dict[base_task] if task_dict is not None and base_task in task_dict else f'Base Task {base_task}'

        y_min, y_max = np.inf, -np.inf
        spec_max, spec_min = None, None
        x_max = 0
        for s_nr, spec in enumerate(sorted([float(k) for k in plotting_data[base_task].keys()])):
            spec = str(spec)
            p_len = 100 if title in ['velocity_forward', 'velocity_backward'] else 50 if title in ['jump'] else len(plotting_data[base_task][spec])
            x_max = max([x_max, p_len])
            axs[fig_nr].plot(range(p_len), plotting_data[base_task][spec][range(p_len)], color=COLORS[s_nr], linewidth=size_ * 0.2)
            axs[fig_nr].plot([0, p_len], [float(spec), float(spec)], linestyle='--', color=COLORS[s_nr], label='target', linewidth=size_ * 0.2)

            y_min = min([y_min, plotting_data[base_task][spec].min()])
            y_max = max([y_max, plotting_data[base_task][spec].max()])
            spec_max = float(spec)
            if s_nr == 0:
                spec_min = float(spec)

        y_min = min([y_min, spec_min])
        y_max = max([y_max, spec_max])

        el = axs[fig_nr].plot([0], [0], linestyle='--', color='k', label=f'Target {target_map[title]}', linewidth=size_ * 0.2)
        axs[fig_nr].legend(handles=el, loc='upper right', bbox_to_anchor=(1.0, 1. if spec_max <= 0 else 0.15))

        axs[fig_nr].set_title(class_map[title])
        axs[fig_nr].set_xlabel('Time Step $\it{t}$')
        axs[fig_nr].set_ylabel(target_map[title])

        axs[fig_nr].set_ylim([y_min - 0.05 * (y_max - y_min), y_max + 0.05 * (y_max - y_min)])
        axs[fig_nr].set_xlim([-1., x_max + 1])

        axs[fig_nr].set_xticks((np.linspace(axs[fig_nr].get_xlim()[0] + 1, axs[fig_nr].get_xlim()[1] - 1, 5) * 10.).astype(np.int) / 10.)
        axs[fig_nr].set_yticks((np.linspace(0. if spec_min > 0. else spec_min, 0. if spec_max < 0. else spec_max, 5) * 10.).astype(np.int) / 10.)

    if plot_type == 0:
        plt.subplots_adjust(hspace=0.4)
        fig.set_size_inches(45, 14.5)
    elif plot_type == 1:
        fig.set_size_inches(42, 6.0)
    else:
        fig.set_size_inches(35, 6.0)

    if save_:
        plt.savefig(os.path.join(fig_folder, 'ti_one_plot.pdf'), format='pdf', dpi=100,
                    bbox_inches='tight')
        plt.savefig(os.path.join(fig_folder, 'png', 'ti_one_plot.png'), format='png', dpi=100,
                    bbox_inches='tight')
    else:
        plt.show()
    plt.close()

def npify_dict(d: dict):
    if type(d) is dict:
        for k, v in d.items():
            if type(v) is dict:
                d[k] = npify_dict(v)
            else:
                d[k] = np.asarray(v)
    elif type(d) is list:
        for i, el in enumerate(d):
            if type(el) is dict:
                d[i] = npify_dict(el)
            else:
                d[i] = np.asarray(el)
    else:
        raise ValueError(d)
    return d

if __name__ == '__main__':
    main(*sys.argv[1:])


from typing import Any
from flask import Flask, jsonify, request
from marshmallow import Schema, fields, validate

from errors import NoPlacesFoundException, ValidationError
from service.google_serp_scrapper import GoogleSERPScraper
import asyncio
from keys_enum import Keys
import traceback
import colorlog

app = Flask(__name__)

# Define the logger
# Define the logger
logger = colorlog.getLogger()

handler = colorlog.StreamHandler()
handler.setFormatter(colorlog.ColoredFormatter(
    '%(log_color)s%(levelname)s:%(name)s:%(message)s',
    log_colors={
        'DEBUG': 'cyan',
        'INFO': 'green',
        'WARNING': 'yellow',
        'ERROR': 'red',
        'CRITICAL': 'red,bg_white',
    },
    reset=True,
    style='%'
))

logger.addHandler(handler)
logger.setLevel(colorlog.INFO)

class ParamsSchema(Schema):
    query = fields.Str(required=True, validate=validate.Length(min=1))
    latitude = fields.Float(required=True)
    longitude = fields.Float(required=True)

params_schema = ParamsSchema()

@app.before_request
def validate_params():
    if request.path == '/get_places':
        errors = params_schema.validate(request.args)
        if errors:
            logger.error(f"Validation error: {errors}")
            request_info = {
                'query': request.args.get('query', ''),
                'latitude': request.args.get('latitude', ''),
                'longitude': request.args.get('longitude', '')
            }
            return jsonify({'errors': errors, 'request_info': request_info}), 400

async def async_scrape(query, url):
    if url:
        scraper = GoogleSERPScraper()
        titles = scraper.scrape_url(url)
    elif query:
        scraper = GoogleSERPScraper()
        titles = scraper.scrape(query)
    else:
        return {'error': 'No query or URL provided.'}, 400

    result = {
        "local_results": titles
    }
    return result

async def scrape_places(query, latitude, longitude):
    try:
        scraper = GoogleSERPScraper()
        result = {}
        result['request_info'] = {
            'query': query,
            'latitude': latitude,
            'longitude': longitude
        }

        places_link = scraper.generate_gmaps_url(query, latitude=latitude, longitude=longitude)
        places_array = scraper.get_places(places_link)
        if (places_array):
            result['places_result'] = scraper.places_to_json(objects=places_array)
            logger.info(
                f"Scraping places for query {query} at latitude {latitude} and longitude {longitude} was successful")
        else:
            logger.error(f"No places were scraped for query {query} at latitude {latitude} and longitude {longitude}")
            raise NoPlacesFoundException('No places were scraped')

        return result
    except NoPlacesFoundException as e:
        logger.error(f"Exception occurred: {e}", exc_info=True)  # This will log the stack trace
        return {'error': 'An error occurred while scraping places', 'request_info': result['request_info']}, 500

@app.route("/get_places", methods=['GET'])
async def get_places():
    query = request.args.get('query')
    latitude = request.args.get('latitude')
    longitude = request.args.get('longitude')

    result = await asyncio.gather(scrape_places(query=query, latitude=latitude, longitude=longitude))
    return result

@app.errorhandler(404)
def not_found_error(error):
    logger.error('Resource not found', exc_info=True)
    return jsonify({'error': 'Resource not found'}), 404

@app.errorhandler(500)
def internal_error(error):
    logger.error(f'An internal error occurred: {error}', exc_info=True)
    return jsonify({'error': f'An internal error occurred {error}'}), 500

app.run()


import os
import sys

from PyQt5.QtWidgets import QPushButton, QProgressBar, QFileDialog, QHBoxLayout

# class responsible for choosing and loading file containing data used later
class FileLoader(QHBoxLayout):

    def __init__(self, btn_name, error_display_method, set_filepath_method):
        super().__init__()

        self.__error_display_method = error_display_method
        self.__set_filepath_method = set_filepath_method
        self.__create_all(btn_name)

    def __create_all(self, btn_name="Select file", parent=None):
        self.__file_loader_dialog_btn = self.__create_file_loader_dialog_btn(btn_name)
        self.__loader = QProgressBar(parent)

        self.addWidget(self.__file_loader_dialog_btn)
        self.addWidget(self.__loader)

    def __create_file_loader_dialog_btn(self, btn_name):
        loader_btn = QPushButton(btn_name)
        loader_btn.clicked.connect(self.__choose_and_read_file)

        return loader_btn

    # method responsible for choosing file and displaying loading progress
    def __choose_and_read_file(self):
        self.__loader.setValue(1)
        parent = None
        # sets current directory as default one
        current_dir = os.path.dirname(sys.argv[0])
        self.__loader.setValue(10)
        # changes default type of file explorator
        options = QFileDialog.DontUseNativeDialog
        self.__loader.setValue(20)
        # opens window in which user can choose file
        self.maybe_selected_file, _ = QFileDialog.getOpenFileName(parent, "Choose csv file",
                                                                  current_dir, "CSV (*.csv)", options=options)
        self.__loader.setValue(30)
        if self.maybe_selected_file:
            self.__loader.setValue(40)
            self.__loader.setValue(50)
            # returns selected filepath
            self.__set_filepath_method(self.maybe_selected_file)
            return

        else:
            self.__error_display_method("Error: file loading aborted")
            self.__loader.setValue(1)

    def set(self, val):
        self.__loader.setValue(val)


#
# @lc app=leetcode id=889 lang=python3
#
# [889] Construct Binary Tree from Preorder and Postorder Traversal
#

# @lc code=start
# Definition for a binary tree node.
from typing import List, Optional

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        """
        Definition for a binary tree node.

        Attributes:
        - val: Value of the node.
        - left: Left child node.
        - right: Right child node.
        """
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def __init__(self) -> None:
        """
        Initialize the Solution object with a dictionary to keep track of
        the indices of values in the postorder traversal.
        """
        self.valToIndex = {}

    def constructFromPrePost(self, preorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        """
        Construct a binary tree from its preorder and postorder traversal lists.

        Args:
        - preorder: List[int]: Preorder traversal of the binary tree.
        - postorder: List[int]: Postorder traversal of the binary tree.

        Returns:
        - The root node of the constructed binary tree.
        """

        # Populate the valToIndex dictionary with indices of values from the postorder traversal.
        for i in range(len(postorder)):
            self.valToIndex[postorder[i]] = i

        # Start the recursive tree construction using the entire length of both lists.
        return self.build(preorder, 0, len(preorder)-1,
                          postorder, 0, len(postorder)-1)

    def build(self, preorder: List[int], preStart: int, preEnd: int,
              postorder: List[int], postStart: int, postEnd: int) -> TreeNode:
        """
        Recursive helper function to construct the binary tree using parts of the preorder and postorder lists.

        Args:
        - preorder: List[int]: Preorder traversal of the current subtree.
        - preStart, preEnd: Define the segment of the preorder list to consider for the current subtree.
        - postorder: List[int]: Postorder traversal of the current subtree.
        - postStart, postEnd: Define the segment of the postorder list to consider for the current subtree.

        Returns:
        - The root node of the constructed subtree.
        """

        # Base case: if the current segment of the preorder list is empty, return None.
        if preStart > preEnd:
            return None

        # Base case: if only one element is left in the segment, create and return a node.
        if preStart == preEnd:
            return TreeNode(preorder[preStart])

        # The first element in the current preorder list is the root of the current subtree.
        rootVal = preorder[preStart]

        # The second element in the current preorder list is the root of the left subtree.
        leftRootVal = preorder[preStart+1]

        # Find the index of the root of the left subtree in the postorder list.
        index = self.valToIndex[leftRootVal]

        # Calculate the size of the left subtree using its end index in the postorder list.
        leftSize = index - postStart + 1

        # Create a new TreeNode with the root value.
        root = TreeNode(rootVal)

        # Recursively construct the left subtree.
        root.left = self.build(preorder, preStart+1, preStart+leftSize,
                               postorder, postStart, index)

        # Recursively construct the right subtree.
        root.right = self.build(preorder, preStart+leftSize+1, preEnd,
                                postorder, index+1, postEnd-1)

        return root

# @lc code=end


import cv2
import sys

class FrameWrapper():
    """
    A standard interface for getting frames from images, videos, and the webcam.
    TODO: ZED camera interfacing

    Example usage:
        filenames = ['relative/path/img.png', './video.mp4', 'webcam']
        frames = FrameWrapper(filenames)

        # Shows img.png, then all frames in video.mp4, then frames from webcam forever
        for frame in frames:
            cv2.imshow('Next frame', frame)
    """

    # Keywords used to identify file types
    WEBCAM = ['webcam']
    VIDEO_EXTS = ['mp4', 'avi']
    IMG_EXTS = ['jpg', 'png']

    VIDEO_TRIES = 200
    WEBCAM_TRIES = 10

    def __init__(self, filenames, resize=1):
        self.filenames = filenames  # Get this list of relative paths to files from vis
        # There aren't any checks for resize==1 to improve speed b/c this expects resize != 1
        self.resize = resize

    def __iter__(self):
        self.index = -1
        self.next_data = ('', None)
        self.next_data_obj()
        return self

    def __next__(self):
        if not self.has_next:
            raise StopIteration

        while self.index < len(self.filenames):
            if self.next_data[0] == "v": # Video
                # Try to get a frame out at most VIDEO_TRIES times.
                # If it still fails, we're probably at the end of the video file
                for i in range(self.VIDEO_TRIES):
                    ret, frame = self.next_data[1].read()
                    if ret:
                        return cv2.resize(frame, None, fx=self.resize, fy=self.resize)
                    print("WARNING: Failed to get frame from video {}. Try {}." \
                            .format(self.filenames[self.index], i), file=sys.stderr)
                self.next_data_obj()
            elif self.next_data[0] == "i": # Image
                img = self.next_data[1]
                self.next_data_obj()
                if img is not None:
                    return cv2.resize(img, None, fx=self.resize, fy=self.resize)
                print("WARNING: Failed to get image {}." \
                        .format(self.filenames[self.index-1]), file=sys.stderr)
            else: # Webcam
                # Try to get a frame out at most WEBCAM_TRIES times.
                for i in range(self.WEBCAM_TRIES):
                    ret, frame = self.next_data[1].read()
                    if ret:
                        return cv2.resize(frame, None, fx=self.resize, fy=self.resize)
                    print("WARNING: Failed to get frame from webcam. Try {}." \
                            .format(i), file=sys.stderr)
                self.next_data_obj()

        raise StopIteration

    def next_data_obj(self):
        """
        Helper function for getting the next object (video, image, webcam) when
        the previous one is exhausted.
        """
        # Close the webcam if it was open and we don't want it anymore
        if self.next_data[0] in self.WEBCAM:
            self.next_data[1].release()

        # Stop if we don't have any more data
        if self.index >= len(self.filenames) - 1:
            self.index += 1
            self.has_next = False
            return

        # Prepare the next data object
        self.index += 1
        filename = self.filenames[self.index]
        extension = filename[filename.rindex('.') + 1:].lower() if '.' in filename else None

        if filename in self.WEBCAM:
            self.next_data = ('w', cv2.VideoCapture(0))
        elif extension in self.VIDEO_EXTS:
            self.next_data = ('v', cv2.VideoCapture(filename))
        elif extension in self.IMG_EXTS:
            self.next_data = ('i', cv2.imread(filename))
        else:
            print("Unknown file format:", extension)

        self.has_next = True


#%% import and read
import re
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
from matplotlib.pyplot import cm
from simulation import load_perp_params
import seaborn as sns

sns.set_style('whitegrid') # darkgrid, white grid, dark, white and ticks
plt.rc('axes', titlesize=18)     # fontsize of the axes title
plt.rc('axes', labelsize=14)    # fontsize of the x and y labels
plt.rc('xtick', labelsize=13)    # fontsize of the tick labels
plt.rc('ytick', labelsize=13)    # fontsize of the tick labels
plt.rc('legend', fontsize=13)    # legend fontsize
plt.rc('font', size=13)          # controls default text sizes

COLL = 'MATIC'
QUOTE = 'USD'

FILENAME = 'results/res119-20-AVAXUSDMATIC_2022919-9035130173671625568.csv'

perpsymbol = re.search("-[A-Z]+_", FILENAME).group(0)[1:-1]
INDEX = perpsymbol[:(len(perpsymbol) - len(QUOTE + COLL))]

def main():

    file = FILENAME if FILENAME[-3:] == 'csv' else FILENAME + '.csv'
    df = pd.read_csv(file)

    df['mid_price_rel'] = (df['mid_price'] - df['idx_px']) / df['idx_px']
    df['mark_price_rel'] = (df['mark_price'] - df['idx_px']) / df['idx_px']
    df['cex_price_rel'] = df['cex_px'] / df['idx_px'] - 1
    df['datetime'] = pd.to_datetime(df['time'], format='%y-%m-%d %H:%M', utc=True)
    df['timestamp'] = df['datetime'].apply(datetime.datetime.timestamp)

    df = df[(df['datetime'] >= datetime.datetime(2022, 9, 18, 1, 0, 1, tzinfo=datetime.timezone.utc)) & (df['datetime'] < datetime.datetime(2022, 9, 18, 2, 15, 0,  tzinfo=datetime.timezone.utc))]

    price_columns = [x for x in df.columns if re.search('^perp_pi', x)]
    price_columns.reverse()
    if len(price_columns) > 0:
        # transform price into price impact
        for col in price_columns:
            df[col] = df[col] / df['mid_price'] - 1

    from_date = df['timestamp'].min()
    to_date = df['timestamp'].max()

    print(f"Date range: {datetime.datetime.fromtimestamp(from_date)} -- {datetime.datetime.fromtimestamp(to_date)}")

    # print("\nPremium summary (in bps):")
    # print(1e4 * df[['mark_price_rel', 'avg_long_slip', 'avg_short_slip', '100klots_long_slip', '100klots_short_slip']].describe())
    q = [0.01, 0.05, 0.10, 0.20, 0.25, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 0.95, 0.99]

    print("\nFunding rate accrued over 8h summary:")
    x = df['funding_rate'].rolling(8 * 60).sum().abs().values

    x = np.nanquantile(df['funding_rate'].rolling(8 * 60).sum().abs().values, q)
    v = np.quantile(x, q)
    print("\n".join([f"{100*_q:.1f}%: {1e4 *_v: .4f} bps" for _q, _v in zip(q,v)]))
    print(f"mean +- stddev: {np.mean(x)} +- {np.std(x)}")

    plot_analysis(df, file)

def plot_perp_slippage(fig, df):
    slippage = [x for x in df.columns if re.search('^perp_price', x)]
    slippage = [slippage[0], slippage[5], slippage[10],  slippage[15],  slippage[-16], slippage[-11], slippage[-6], slippage[-1]]
    slippage.reverse()
    # print(perp_pnls)
    color = iter(cm.rainbow(np.linspace(0, 1, len(slippage))))
    ax = fig.add_subplot()
    for i, p in enumerate(slippage):
        if i % 4 != 0:
            next
        c = next(color)
        ax.plot(df['datetime'], 1e4 * df[p], 'o-', c=c, label=re.sub("perp_price_", "", p))

    plt.xlabel("Time")
    plt.ylabel("Slippage (from mid-price, bps)")

    plt.legend()
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%y/%m/%d %H:%M'))
    fig.autofmt_xdate()

def plot_perp_price(fig, df):

    color = iter(cm.rainbow(np.linspace(0, 1, 2)))
    ax = fig.add_subplot()
    c = next(color)
    ax.plot(df['datetime'], df['mark_price'], 'o-', c=c, label="Mark-price")
    c = next(color)
    ax.plot(df['datetime'], df['idx_px'], 'o-', c=c, label="Oracle")
    # c = next(color)
    # ax.plot(df['datetime'], 1e4 * df['mid_price'], 'o-', c=c, label="Mid-price")

    plt.xlabel("Time")
    plt.ylabel(f"{INDEX}/{QUOTE}")

    plt.legend()
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%y/%m/%d %H:%M'))
    fig.autofmt_xdate()

def plot_analysis(df, file=None):
    print(f"Index: {INDEX}, Quote: {QUOTE}, Collateral: {COLL}")
    fig = plt.figure(figsize=(10,6), tight_layout=True)
    # plot_perp_slippage(fig, df)
    plot_perp_price(fig, df)
    plt.show()

if __name__ == "__main__":
    main()


import os
from PIL import Image
import torch
from torchvision.transforms import functional as F

class UnlabeledDataset(torch.utils.data.Dataset):
    def __init__(self, root, transform):
        r"""
        Args:
            root: Location of the dataset folder, usually it is /unlabeled
            transform: the transform you want to applied to the images.
        """
        self.transform = transform
        self.image_dir = root
        self.filelist = os.listdir(self.image_dir)
        problem_img = ['15460.PNG','151438.PNG', '158432.PNG']
        for p in problem_img:
            if p in self.filelist:
                self.filelist.remove(p)
        self.num_images = len(self.filelist)

    def __len__(self):
        return self.num_images

    def __getitem__(self, idx):
        # the idx of unlabeled image is not consecutive
        with open(os.path.join(self.image_dir, self.filelist[idx]), 'rb') as f:
            try:
                img = Image.open(f).convert('RGB')
            except OSError:
                print(self.filelist[idx],'caused error')
        return F.to_tensor(img)

def main():
    #device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')

    unlabeled_data = UnlabeledDataset(root = '/unlabeled', transform = None)
    data_loader = torch.utils.data.DataLoader(unlabeled_data, batch_size=1024,  num_workers=4)

    mean = 0.
    std = 0.
    nb_samples = 0.
    for data in data_loader:
        #data: batch x 3 x 244 x 244// not using the collate fn by prof
        batch_samples = data.size(0)
        data = data.view(batch_samples, data.size(1), -1)
        mean += data.mean(2).sum(0)
        std += data.std(2).sum(0)
        nb_samples += batch_samples
        if nb_samples % 1000 == 0:
            print(nb_samples,'samples succeeded!')

    mean /= nb_samples
    std /= nb_samples
    print('mean: ', mean, 'std: ', std)

if __name__ == "__main__":
    main()


from flask_main import app,db
from flask import render_template,url_for,redirect
from models import Task
from datetime import datetime
import forms

@app.route("/")
def index():
    return render_template('index.html', title='Home')

@app.route("/chatbot")
def chat():
    return render_template('chatbot.html', title='Home')

@app.route("/sampleform",methods=['get','post'])
def sampleform():
    form=forms.SampleForm()
    if form.validate_on_submit():
        t=Task(title=form.title.data,date=datetime.utcnow())
        db.session.add(t)
        db.session.commit()
        return redirect(url_for('sampleform_output'))
    return render_template("sampleform.html",form=form)

@app.route("/sampleform_out")
def sampleform_output():
    t=Task.query.all()
    return render_template('sampleform_out.html',tasks=t)

@app.route("/edit/<int:task_id>",methods=['get','post'])
def edit(task_id):
    task=Task.query.get(task_id)
    form=forms.SampleForm()
    if task:
        if form.validate_on_submit():
            task.title=form.title.data
            task.date=datetime.utcnow()
            db.session.commit()
            return redirect(url_for("sampleform_output"))
        form.title.data=task.title
        return render_template("edit.html",form=form,task_id=task_id)
    return redirect(url_for("sampleform_output"))

@app.route("/delete/<int:task_id>",methods=['get','post'])
def delete(task_id):
    task=Task.query.get(task_id)
    if task:
            db.session.delete(task)
            db.session.commit()
            return redirect(url_for("sampleform_output"))
    return redirect(url_for("sampleform_output"))


import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import os
import torchvision.datasets as datasets
import torchvision.transforms as transforms

class AlexNet(nn.Module):
    def __init__(self, num_classes=101):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(64, 192, kernel_size=5, padding=2),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.Conv2d(192, 384, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.Conv2d(256, 256, kernel_size=3, padding=1),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )
        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
        self.classifier = nn.Sequential(
            nn.Dropout(),
            nn.Linear(256 * 6 * 6, 4096),
            nn.ReLU(inplace=True),
            nn.Dropout(),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.classifier(x)
        return x

def train(model, optimizer, criterion, train_loader, valid_loader, writer, num_epochs):

    # 将模型设置为训练模式
    model.train()

    # 定义最佳验证集准确率和最佳模型参数
    best_valid_acc = 0.0
    best_model_params = model.state_dict()

    for epoch in range(num_epochs):
        train_loss = 0.0
        train_acc = 0.0
        valid_loss = 0.0
        valid_acc = 0.0

        # 训练模型
        for inputs, labels in train_loader:
            inputs = inputs.to(device)
            labels = labels.to(device)

            optimizer.zero_grad()

            outputs = model(inputs)
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            train_loss += loss.item() * inputs.size(0)
            _, preds = torch.max(outputs, 1)
            train_acc += torch.sum(preds == labels.data)

        # 在验证集上测试模型
        with torch.no_grad():
            model.eval()
            for inputs, labels in valid_loader:
                inputs = inputs.to(device)
                labels = labels.to(device)

                outputs = model(inputs)
                loss = criterion(outputs, labels)

                valid_loss += loss.item() * inputs.size(0)
                _, preds = torch.max(outputs, 1)
                valid_acc += torch.sum(preds == labels.data)

        # 计算平均损失和准确率
        train_loss /= len(train_loader.dataset)
        train_acc /= len(train_loader.dataset)
        valid_loss /= len(valid_loader.dataset)
        valid_acc /= len(valid_loader.dataset)

        # 记录训练和验证集的损失和准确率
        writer.add_scalar('train_loss', train_loss, epoch + 1)
        writer.add_scalar('train_acc', train_acc, epoch + 1)
        writer.add_scalar('valid_loss', valid_loss, epoch + 1)
        writer.add_scalar('valid_acc', valid_acc, epoch + 1)

        print('Epoch [{}/{}], Train Loss: {:.4f}, Train Acc: {:.4f}, Valid Loss: {:.4f}, Valid Acc: {:.4f}'
              .format(epoch+1, num_epochs, train_loss, train_acc, valid_loss, valid_acc))

        # 如果当前模型在验证集上的准确率更好，则保存模型参数
        if valid_acc > best_valid_acc:
            best_valid_acc = valid_acc
            best_model_params = model.state_dict()

    # 加载最佳模型参数
    model.load_state_dict(best_model_params)

    # 保存模型
    torch.save(model.state_dict(), 'alexnet.pth')

def test(test_loader, criterion, writer):
    new_model = AlexNet(num_classes=101)
    # 加载保存的模型参数
    checkpoint = torch.load('alexnet.pth')
    new_model.load_state_dict(checkpoint)

    # 设置模型为评估模式
    new_model.eval()
    test_loss = 0
    correct = 0
    with torch.no_grad():
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = new_model(data)
            test_loss += criterion(output, target).item()  # 将一批的损失相加
            pred = output.argmax(dim=1, keepdim=True)  # 找到概率最大的下标
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    test_accuracy = 100. * correct / len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset), test_accuracy))
    writer.add_scalar('Testing Loss', test_loss)
    writer.add_scalar('Testing Accuracy', test_accuracy)

def get_data_loaders(data_dir, batch_size):
    # 定义数据预处理方式，包括裁剪、缩放和标准化
    transform = transforms.Compose([
        transforms.RandomResizedCrop(224),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.485, 0.456, 0.406],
                             std=[0.229, 0.224, 0.225])
    ])

    # 加载数据集
    full_dataset = datasets.ImageFolder(os.path.join(data_dir), transform=transform)

    # 将数据集按照数量划分为训练集、验证集和测试集
    num_samples = len(full_dataset)
    num_train = int(num_samples * 0.8)
    num_valid = int(num_samples * 0.1)
    num_test = num_samples - num_train - num_valid

    train_dataset, valid_dataset, test_dataset = torch.utils.data.random_split(
        full_dataset, [num_train, num_valid, num_test])
    print(len(train_dataset), len(valid_dataset), len(test_dataset))
    # 创建DataLoader对象
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=4)
    valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=batch_size, shuffle=False, num_workers=4)
    test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=4)

    return train_loader, valid_loader, test_loader

if __name__ == '__main__':

    # 设置超参数
    num_epochs = 30
    batch_size = 64
    learning_rate = 0.0001

    # 定义tensorboard日志文件夹路径
    log_dir = 'runs/alexnet_caltech101'

    # 初始化tensorboard的SummaryWriter
    writer = SummaryWriter(log_dir=log_dir)

    # 获取数据加载器
    train_loader, valid_loader, test_loader = get_data_loaders('./caltech-101/101_ObjectCategories', batch_size)

    # 创建模型
    model = AlexNet(num_classes=101)

    # 将模型移动到GPU上进行训练
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    model.to(device)

    # 定义损失函数和优化器
    criterion = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)

    # 训练模型
    train(model, optimizer, criterion, train_loader, valid_loader, writer, num_epochs)

    # 测试模型
    test(test_loader, criterion, writer)

    # 关闭tensorboard的SummaryWriter
    writer.close()


#----------------Simple Crptocurrency example------------------------
#   Everytime a miner mine the pending transactions (add them to a new block and passing proof of work)
#   his reward is added to newly created pending transaction array with his toAddress and reward amount
import hashlib
import datetime

class Transaction:
    def __init__(self,fromAddress,toAddress,Amount):
        self.fromAddress=fromAddress
        self.toAddress=toAddress
        self.Amount=Amount

class Block:
    def __init__(self,date_time,Transactions,previoushash):
        self.date_time=date_time
        self.Transactions=Transactions
        self.previoushash=previoushash
        self.count=0
        self.currenthash=self.calculatehash()
    def calculatehash(self):
        string=str(self.date_time)+str(self.Transactions)+str(self.previoushash)+str(self.count)
        return  hashlib.sha256(string.encode()).hexdigest()
    def mine(self,difficulty):
        x="0"*difficulty
        current_hash=self.currenthash
        while(current_hash[0:difficulty]!=x):
            self.count+=1
            self.current_hash=self.calculatehash()

class Blockchain:
    def __init__(self,GenesisTransaction,difficulty):
        date_time=datetime.datetime.now()
        self.chain=[Block(date_time,GenesisTransaction,-1)]
        self.difficulty=difficulty
        self.PendingTransactions=[]
        self.miningrewards=100
    def Getlatest(self):
         return self.chain[len(self.chain)-1]
#  mining the list of pending transactions and adding to the chain
#  passing the miners address to add his reward to the new pending transaction list (with his address and reward amount)
    def mineBlock(self,MinerAddress):
        date_time=datetime.datetime.now()
        lasthash=self.Getlatest().currenthash
        newblock=Block(date_time,self.PendingTransactions,lasthash)
        newblock.mine(self.difficulty)
        print("Congo !!! -- A new block mined--")
        print("YIPPEEEEEE!!! -------------Miner rewarded------------")
        print("...Miner's reward will be added once a new block containing his reward is mined")
        print()
        self.chain.append(newblock)
#  adding the miners reward to new pending transaction with his address and reward amount
        self.PendingTransactions=[Transaction(None,MinerAddress,self.miningrewards)]
    def CreateTransaction(self,transaction):
        self.PendingTransactions.append(transaction)
#   Balance of an address is checked by traversing the complete chain and cheching
#   every transaction object in the transaction array of each block
    def GetBalanceofAddress(self,address):
        balance=0
        for block in self.chain:
            for transaction in block.Transactions:
                if(transaction.fromAddress==address):
                    balance-=transaction.Amount
                elif(transaction.toAddress==address):
                    balance+=transaction.Amount
        return balance
    def isValid(self):
        for i in range(1,len(self.chain)):
            current=self.chain[i]
            previous=self.chain[i-1]
            x=current.count #changing the temp to 0 just to validate that currently hash is same as when the block was created because temp value is changed while mining
            current.count=0
            if(current.previoushash!=previous.currenthash):
                return False
            if(current.currenthash!=current.calculatehash()):
                return False
        current.count=x #changing back the temp to its mined value, if some one wants to know how many times loop ran(computation power)
        return True
#   Genesis block with new Genesis transaction
GenesisTransactions=[Transaction(None,"Genesis",2000)]
mychain=Blockchain(GenesisTransactions,4)

mychain.CreateTransaction(Transaction("one","two",1000))
mychain.CreateTransaction(Transaction("two","three",2000))
mychain.CreateTransaction(Transaction("three","four",3000))

mychain.mineBlock("sumit")
#  after mining a new block with above pending transactions miner("Sumit") got a reward
#  that is saved in a new pending transaction array
print("Balance of --Sumit-- >",mychain.GetBalanceofAddress("sumit"))
print("______________________________________________________________")
print()
#  the balance is 0 as the transactions array with his reward is not yet added to the chain
#  once the pending record with his reward is mined by someone his balance will increase.

mychain.CreateTransaction(Transaction("here","there",2400))
mychain.CreateTransaction(Transaction("here","there",6000))
mychain.mineBlock("sumit")
print("Balance of --Sumit-- >",mychain.GetBalanceofAddress("sumit"))
#  ----------chceck validity-------
print()
print("______________________________")
print()
print("valid : ",mychain.isValid())