# Christopher Jones 2023, adapted from cleanRL

import argparse
import os
import random
import time
from distutils.util import strtobool

#  import gym
import sys
sys.path.append("build/")
import PyATMSim
from random import randint
from stable_baselines3.common.buffers import ReplayBuffer
import gymnasium as gym

import numpy as np
# import pybullet_envs  # noqa
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter

load_from_file = False

batch_size = 512
tau = 0.005
policy_frequency = 2
noise_clip = 0.5
learning_starts = 5e3
exploration_noise = 0.2
policy_noise = 0.2
gamma=0.999
buffer_size = int(1e6)
learning_rate = 1e-4
total_timesteps = int(1e8)
torch_deterministic = True
seed = 1

cuda = True

class Actor(nn.Module):
    def __init__(self, env):
        super().__init__()
        self.fc1 = nn.Linear(np.array(env.single_observation_space.shape).prod(), 256)
        self.fc2 = nn.Linear(256, 1024)
        self.fc3 = nn.Linear(1024, 1024)
        self.fc4 = nn.Linear(1024, 256)
        self.fc_mu = nn.Linear(256, np.prod(env.single_action_space.shape))
        # action rescaling
        self.register_buffer(
            "action_scale", torch.tensor((env.action_space.high - env.action_space.low) / 2.0, dtype=torch.float32)
        )
        self.register_buffer(
            "action_bias", torch.tensor((env.action_space.high + env.action_space.low) / 2.0, dtype=torch.float32)
        )

    def forward(self, x):
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = F.relu(self.fc3(x))
        x = F.relu(self.fc4(x))
        x = torch.tanh(self.fc_mu(x))

        return x * self.action_scale + self.action_bias

class EnvWrap():
    def __init__(self):
        self.env = PyATMSim.ATMSim("environment_boundaries.json","airport_data.json", 1,0,0, 25)
        self.env.step()
        self.action_space = gym.spaces.Box(low=-1, high=1, shape = (3,))
        self.observation_space = gym.spaces.Box(low=-1000, high=1000, shape  = np.array(self.env.traffic[0].get_observation()).shape)
        self.single_observation_space = self.observation_space
        self.single_action_space = self.action_space
    def reset(self):
        return self.env.reset()
    def step(self):
        return self.env.step()

if __name__ == "__main__":
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.backends.cudnn.deterministic = torch_deterministic

    device = torch.device("cuda" if torch.cuda.is_available() and cuda else "cpu")

    # env setup
    envs = EnvWrap()
    actor = Actor(envs)
    # device = "cpu"
    if device == torch.device("cuda"):
        # actor.load_state_dict(torch.load("./saved_models/final_1024/actor.pt"))
        actor.load_state_dict(torch.load("./models/actor.pt"))
        actor.to(device)
    else:
        actor.load_state_dict(torch.load("./models/actor.pt", map_location=device))
        # actor.load_state_dict(torch.load("./saved_models/final_1024/actor.pt", map_location=device))

    envs.single_observation_space.dtype = np.float32
    obs = envs.reset()

    states = {i : i.get_observation() for i in envs.env.traffic}
    actions = {i : [] for i in envs.env.traffic}

    aircraft = envs.env.traffic[0]
    prev = states[aircraft][2]*41000

    index = 0
    max_aircraft = 100

    altitudes = {i : [] for i in range(max_aircraft)}
    speeds = {i : [] for i in range(max_aircraft)}
    distances = {i : [] for i in range(max_aircraft)}

    lifespan_file = open("./results/lifespans.csv", "w+")
    aircraft_total = 0
    steps = 0
    ac_conflict = 0

    while index < max_aircraft:
        steps +=1
        prev = list(states)
        states = {i : i.get_observation() for i in envs.env.traffic}
        actions={}

        for traffic in states:
            reward=-170 + traffic.reward
            if reward>0:
                print(reward)
            if traffic.terminated:
                if traffic.conflict_flag:
                    ac_conflict+=1
                aircraft_total+=1
                lifespan_file.write(str(traffic.lifespan)+'\n')
        with torch.no_grad():
            for state in states:
                action = actor(torch.Tensor(states[state]).to(device))
                action = action.cpu().numpy().clip(envs.single_action_space.low, envs.single_action_space.high)
                actions[state] = action

        this_action=0
        for traffic in actions:
            this_action = actions[traffic].copy()
            this_action[0] = 180 + 180*this_action[0]
            this_action[1] = 20500* + 20500*this_action[1]
            this_action[2] = 245 + (105*this_action[2])
            traffic.set_actions(this_action)

        final_terminated = not envs.step()
        if aircraft not in list(states):
            for i in list(states):
                if i not in prev:
                    aircraft = i
                    index+=1
                    # altitude_file.write("NEW \n")
                    # speed_file.write("NEW\n")
                    # distance_file.write("NEW\n")
        else:
            altitudes[index].append(str(states[aircraft][2]*41000))
            speeds[index].append(str(states[aircraft][4]*350))
            distances[index].append(str(aircraft.distance_to))

        # prev = states[aircraft][2]*41000
        # altitude_file.write(str(states[aircraft][2]*41000) + '\n')
        # speed_file.write(str(states[aircraft][4]*350) + '\n')
        # distance_file.write(str(aircraft.distance_to)+ '\n')

    altitude_file = open("./results/altitudes.csv", "w+")
    speed_file = open("./results/speeds.csv", "w+")
    distance_file = open("./results/distance.csv", "w+")
    infringements = open("./results/infringements.txt", "w+")

    max_length = lambda dict : max([len(i) for i in dict.values()])

    max_altitude = max_length(altitudes)
    for i in range(max_altitude):
        string = ""
        for ac in range(max_aircraft):
            altitudes[ac] = ["" for i in range(max_altitude - len(altitudes[ac]))] + altitudes[ac]
            if i < len(altitudes[ac]):
                string += altitudes[ac][i]
            string+=","
        altitude_file.write(string + '\n')

    max_speed = max_length(speeds)
    for i in range(max_altitude):
        string = ""
        for ac in range(max_aircraft):
            speeds[ac] = ["" for i in range(max_altitude - len(speeds[ac]))] + speeds[ac]
            if i < len(speeds[ac]):
                string += speeds[ac][i]
            string+=","
        speed_file.write(string + '\n')

    max_distance = max_length(distances)
    for i in range(max_distance):
        string = ""
        for ac in range(max_aircraft):
            distances[ac] = ["" for i in range(max_altitude - len(distances[ac]))] + distances[ac]
            if i < len(distances[ac]):
                string += distances[ac][i]
            string+=","
        distance_file.write(string + '\n')

    infringements.write("total: " + str(envs.env.total_infringements)+ '\n')
    infringements.write("near: " + str(envs.env.total_near_infringements)+'\n')
    infringements.write("total aircraft: " + str(aircraft_total)+'\n')
    infringements.write("total steps: " + str(steps)+'\n')
    infringements.write("AC conflicts: "+ str(ac_conflict))


atletas = []
while True:
    nome = str(input("Digite o nome do atleta (ou Enter para finalizar): "))
    if nome == "":
        break
    atleta = {
        "nome": nome,
        "notas": [],
        "melhorNota": 0,
        "piorNota": 0,
        "media": 0,
    }
    for n in range(7):
        atleta.get("notas").append(float(input(f"{n+1}º nota: ")))
    atleta.get("notas").sort()
    atleta["piorNota"] = atleta.get("notas").pop(0)
    atleta["melhorNota"] = atleta.get("notas").pop()
    atleta["media"] = sum(atleta.get("notas"))/5

    print(f"Melhor nota: {atleta.get('melhorNota'): } ")
    print(f"Pior nota: {atleta.get('piorNota'): } ")
    print(f"Media das notas: {atleta.get('media'): } ")

print("\nResultado final")
for atleta in atletas:
    print(f"{atleta.get('nome')}: {atleta.get('media'):.f}")


# -*- coding: utf-8 -*-
# @File    : ShuffleAnArray.py
# @Date    : 2022-07-11
# @Author  : tc
"""
384. 打乱数组
给你一个整数数组 nums ，设计算法来打乱一个没有重复元素的数组。打乱后，数组的所有排列应该是 等可能 的。

实现 Solution class:

Solution(int[] nums) 使用整数数组 nums 初始化对象
int[] reset() 重设数组到它的初始状态并返回
int[] shuffle() 返回数组随机打乱后的结果

示例 1：
输入
["Solution", "shuffle", "reset", "shuffle"]
[[[1, 2, 3]], [], [], []]
输出
[null, [3, 1, 2], [1, 2, 3], [1, 3, 2]]

解释
Solution solution = new Solution([1, 2, 3]);
solution.shuffle();    // 打乱数组 [1,2,3] 并返回结果。任何 [1,2,3]的排列返回的概率应该相同。例如，返回 [3, 1, 2]
solution.reset();      // 重设数组到它的初始状态 [1, 2, 3] 。返回 [1, 2, 3]
solution.shuffle();    // 随机返回数组 [1, 2, 3] 打乱后的结果。例如，返回 [1, 3, 2]

Fisher-Yates 洗牌算法:
https://leetcode.cn/problems/shuffle-an-array/solution/da-luan-shu-zu-yi-ding-gong-ping-de-xi-p-21iy/

"""
import random
from typing import List

class Solution:
    def __init__(self, nums: List[int]):
        self.nums = nums
        self.original = nums.copy()

    def reset(self) -> List[int]:
        self.nums = self.original.copy()
        return self.nums

    def shuffle(self) -> List[int]:
        shuffled = [0] * len(self.nums)
        for i in range(len(self.nums)):
            j = random.randrange(len(self.nums))
            shuffled[i] = self.nums.pop(j)
        self.nums = shuffled
        return self.nums

# Your Solution object will be instantiated and called as such:
# obj = Solution(nums)
# param_1 = obj.reset()
# param_2 = obj.shuffle()


from flask_restful import Resource
from flask import jsonify, request

from ..models.incident_model import IncidentModel, incidents

class Incident(Resource ,IncidentModel):
    """This class provides access to operations on Get and post records """

    def __init__(self):
        self.data = IncidentModel()

    def get(self):
        """This method Fetches all records"""

        resp = self.data.get_all_records()
        if len(resp)== 0:
             return {
                 "Status": 404,
                 "Message": "No records found"
             },404
        return {
            "status": 200,
            "Data": resp
            },200

    def post(self):
        """This method creates a new record"""

        details = request.get_json()
        createdBy = details['createdBy']
        record_type = details['type']
        location = details['location']
        comment = details['comment']

        if not comment or comment=="" or not location :
            return {"message":"You must provide record details",
                    "status":400
                    },400

        resp = self.data.save(createdBy,record_type,location,comment)
        return {
                "status": 201,
                "data": [
                    {
                        "id": len(resp),
                        "message": "created red-flag record"
                     }
                ]
            },201

class SingleRecord(Resource, IncidentModel):
    """This resource will be used to get a single record """

    def __init__(self):
        self.db = IncidentModel()

    def get(self,id):
        """This method gets a single incident record"""

        if not id or not isinstance(id,int):
            return {
                "Status": 404,
                "Message": "Please Enter a valid ID"
            },404

        resp = self.db.get_single_record(id)
        if len(resp)== 0:
            return {
                "Status": 404,
                "Message": "Record not Found"
            },404

        return {
            "status": 200,
            "Data": resp
        },200

    def delete(self,id):
        """This method deletes a record"""
        record = self.get_single_record(id)
        if len(record) == 0:
            return {"message": "No record with this ID", "status": 404},404
        incidents.remove(record[0])
        return {
                "status": 200,
                "data": [
                    {
                        "id": id,
                        "message": "Red-flag record has been deleted"
                    }
                ]
            },200

class EditComment(Resource, IncidentModel):
    """This resource will be used to edit a comment"""

    def __init__(self):
        pass

    def patch(self,id):
        """ This method updates the comment field data"""
        resp = self.get_single_record(id)

        if len(resp) == 0:

            return jsonify({
                "message": "No record with this ID",
                "status": 404
               })

        data = request.get_json()

        comment = data['comment']

        index = self.get_index(id)
        data = {
            "comment": comment,
            "index": index
        }

        self.update_comment(**data)
        return jsonify({
            "status": 200,
            "data":[{
                "id": id,
                "message": "Updated red-flag record's Comment"
            }]
            })

class EditLocation(Resource, IncidentModel):
    """This resource will be used to edit location of a record"""

    def __init__(self):
        pass

    def patch(self,id):
        """Updates record location data"""
        resp = self.get_single_record(id)

        if len(resp) == 0:

            return jsonify({
                "message": "No record with this ID",
                "status": 404
               })

        data = request.get_json()

        location = data['location']

        index = self.get_index(id)
        data = {
            "location": location,
            "index": index
        }

        self.update_location(**data)
        return jsonify({
            "status": 200,
            "data":[{
                "id": id,
                "message": "Updated red-flag record's Location"
            }]
            })


from bottle import route, run, template, get, debug
from bottle import static_file, url
import json
import os
import pandas as pd
import numpy as np
from power_rankings_load import load_power_rankings, load_team_stats, load_teams
from load_scores import load_scores

adjusted_stats_file = "adjustedStats_2017_final.csv"
bracket_guide = "bracket_guide_2017.csv"

@route('/')
def home():
    return template("index.html", url=url)

@route('/details')
def details():
    return template("index_details.html", url=url)

@route('/powerrankings')
def powerrank():
    rankings = load_power_rankings(adjusted_stats_file)
    teams = [""] + load_teams(bracket_guide)
    return template("index_powerrankings.html", url=url, rankings=rankings, teams=teams)

@route('/stats')
def stats():
    stats = load_team_stats(adjusted_stats_file)
    teams = load_teams(bracket_guide)
    return template("index_stats.html", url=url, stats=stats, teams=teams)

@route('/projections')
def projections():
    teams = [""] + load_teams(bracket_guide)
    stats = load_team_stats(adjusted_stats_file)
    file_name = adjusted_stats_file
    return template("index_projections.html", url=url, teams=teams, stats=stats, file_name=file_name)

@route('/bracket')
def bracket():
    return template("bracket.html", url=url)

@route('/team_stats/<team>')
def team_stats(team):
    team = team.replace("_"," ")
    stats = load_team_stats(adjusted_stats_file)
    stats = stats.loc[stats.Team == team, :]
    with open("team_images.JSON") as infile:
        team_images = json.load(infile)
        return template("team_stats.html", url=url, stats=stats, teams=team_images, team=team)

@route('/masters')
def masters():
    # return "Come back next year, 2017"
    update_time, individual_standings, total_standings, places = load_scores()
    return template("index_masters.html", url=url, update_time=update_time,
                    individual_standings=individual_standings,
                    total_standings=total_standings,
                    places=places)

@route('/static/<filename>', name = 'static')
def send_static(filename):
    return static_file(filename, root='static')

from bottle import get, post, request # or route

if __name__ == "__main__":

    port = int(os.environ.get('PORT', 80))
    debug(True)
    run(host='0.0.0.0', port=port, reloader=True)


import gtfs_kit as gk

path = 'VLOOT.zip'
gk.list_feed(path)
feed = gk.read_feed(path, dist_units='km')
feed.describe()

trip_stats = feed.compute_trip_stats()
trip_stats.head().T

numOfTrips = trip_stats.start_stop_id.size

# Bazel is ID 1
filtered_df = trip_stats.loc[trip_stats['start_stop_id'] == "1"]
start_times = filtered_df['start_time'].tolist()
print(start_times)

# Hemiksem is ID 2
filtered_df = trip_stats.loc[trip_stats['start_stop_id'] == "2"]
start_times = filtered_df['start_time'].tolist()
print(start_times)


#analise qual valor é o maior
from time import sleep
def maior(* núm):
    print('-='*30)
    print('ANALISANDO VALORES...')
    cont = 0
    for i in núm:
        print(i,end=' ')
        sleep(0.5)
        if cont == 0:
            m = i
        elif i>m:
            m = i
        cont +=1
    print(f'O maior valor digitado foi: {m}')

maior(99,87,56,32,78,23)
maior(10,22,35,2,7)
maior(182,200345,3,1,0)
maior(0)
maior(1,2,3,4,5,6,1000)


from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
from hue_link import HueLink

class PhoneRequest(BaseModel):
    power_source: Optional[int] = None
    battery_percent: int

hue_link = HueLink('192.168.1.2')
app = FastAPI()

@app.get("/")
def read_root():
    return {"Hello": "World"}

@app.post("/iot/api/phone")
async def battery(item: PhoneRequest):
    charge_status = item.dict()
    try:
        if(charge_status['power_source'] != None):
            hue_link.bed_phone_indicator_on_plugin(charge_status['battery_percent'])
            #bed_phone_indicator_on_plugin(bridge, charge_status['battery_percent'], battery_palette)
        else:
            hue_link.bed_phone_indicator_on_unplug(charge_status['battery_percent'])
    except:
        print('Error')
        app.logger.info('Missing information - skipping')
        return 'error'
    return 'success'

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=80, debug=False)


#!/usr/bin/env python3
"""
app.py

eBook Library Parser
"""
from dataclasses import dataclass
from pathlib import Path
from sys import argv
from typing import Generator, Optional, Tuple

store = Path("/home/mohh/Downloads/eBooks/English/all")
supported_formats = ("epub", "pdf")

@dataclass(order=True)
class Ebook:
    path: Path

    def __post_init__(self):
        self.loc = self.path.parent
        self.filename = self.path.name
        divider = self.filename.find("-")
        self.title = self.path.stem[:divider].replace("_", " ")
        self.isbn = self.path.stem[divider + 1:]
        self.extension = self.path.suffix

    def __str__(self) -> str:
        return f"{self.isbn:>25} {self.title}{self.extension}"

@dataclass
class Library:
    directory: Path
    book_types: Tuple[str, str] = supported_formats

    @property
    def books(self) -> Generator:
        yield from sorted(Ebook(book) for book in self.directory.iterdir())

    def report(self, search: Optional[str] = None, ext: Optional[str] = None) -> None:
        header = f"Library Report {'[' + ext + ']' if ext else ''}"
        header += f"{'search: ' + search if search else '':>{80 - len(header)}}\n"
        header += f"{'-' * 80}"
        print(header)

        for book in self.books:
            if ext is None:
                if search:
                    if self._search(search, book.filename):
                        print(book)
                else:
                    print(book)
            elif ext in self.book_types:
                if f".{ext}" == book.extension:
                    if search:
                        if self._search(search, book.filename):
                            print(book)
                    else:
                        print(book)

    @staticmethod
    def _search(term: str, title: str) -> bool:
        return term.lower() in title.lower().replace("_", " ")

def main(loc: Path = store):
    library = Library(loc)
    args = argv
    # added for testing...
    if "pytest" in args[0]:
        args = ["test", "computer vision", "pdf"]

    if len(args) > 1:
        library.report(*args[1:])
    else:
        library.report()

if __name__ == "__main__":
    main()


from Jumpscale import j
from gevent import Greenlet
import gevent
from .ScheduledJob import ScheduledJob

class ScheduledRun(j.baseclasses.object):
    def _init(self, name, timeout=1200):
        self.name = name
        self.jobs = {}
        self.mainloop = Greenlet(self._mainloop)
        self.mainloop.start()
        self.timeout = timeout
        self.error = ""
        self.sleep_time = 0.1
        self.nr_scheduled = 0  # last nr as used for scheduling
        self.nr_done = 0  # nr of last job succesfully executed
        self.events = {}

    def _mainloop(self):
        while True:
            # need to do in careful way so we never kill the greenlet
            self.check()
            gevent.sleep(self.sleep_time)

    # def greenlet_add(self, name, method, *args, **kwargs):
    #     if name in self.greenlets:
    #         raise j.exceptions.BASE("cannot add greenlet: %s already exists" % name)
    #     g = Greenlet(method, *args, **kwargs)
    #     self.greenlets[name] = g
    #     self.greenlets[name].start()

    def schedule(self, name, method, period=0, time_start=0, timeout=0, event=None, retry=None, **kwargs):
        """

        :param self:
        :param name:
        :param method: method to execute
        :param event: number of nr to wait untill finished (waitgroup like in GOLANG)
        :param period: recurring period in seconds, 0 means only run once
        :param start_time: time to start in epoch, in <100000 then will do current epoch + this time
        :param timeout: in seconds after start
        :param args:
        :param kwargs:
        :return:
        """
        if time_start < 100000 and time_start != 0:
            time_start = j.data.time.epoch + time_start

        nr = 1
        name_ = name
        while name_ in self.jobs:
            nr += 1
            name_ = name + str(nr)

        name = name_
        self.nr_scheduled += 1
        sj = ScheduledJob(
            name=name,
            method=method,
            args=[],
            kwargs=kwargs,
            period=period,
            time_start=time_start,
            timeout=timeout,
            nr=self.nr_scheduled,
            event=event,
            retry=retry,
        )
        self.jobs[name] = sj

    def check(self):
        now = j.data.time.epoch
        keys = [key for key in self.jobs.keys()]
        for key in keys:
            if key in self.jobs:
                gs = self.jobs[key]
                if gs.event:
                    if self.nr_done < gs.event:
                        # means we cannot start yet
                        continue
                gs.check()
                if gs.done:
                    self.nr_done += 1

    def event_get(self, name):
        self.events[name] = self.nr_scheduled
        return self.events[name]

    def stop(self):
        self.mainloop.kill()


import time
import csv
from selenium import webdriver
from selenium.webdriver.common.by import By

options = webdriver.ChromeOptions()
driver = webdriver.Chrome(options=options)

driver.get("https://guiamedico.cremesp.org.br/")

crm = 101213
text = 'crm'

driver.find_element(By.NAME, 'crm').send_keys(crm)
driver.find_element(By.XPATH, '/html/body/app-root/div/app-principal/div/div[1]/app-pesquisa-form/div[1]/div/form/div/div[2]/button').click()

time.sleep(1)

try:
    text = driver.find_element(By.XPATH, '//*[@id="DataTables_Table_0"]/tbody/tr/td[2]').text
except:
    text = 'CRM não encontrado'

with open('crm.csv', 'w', newline='', encoding='utf-8') as arquivo_csv:
    escritor_csv = csv.writer(arquivo_csv)
    escritor_csv.writerow([crm, text])

arquivo_csv.close()


from operator import attrgetter

from django.db import models

class OrderedModel(models.Model):
    """
    Mixin for supplying ordable, semi-automatically populated fields for models
    """

    ordering_field = None
    ordering_queryset = None

    def get_ordering_queryset(self):
        assert self.ordering_queryset is not None, (
            "'%s' should either include a `ordering_queryset` attribute, "
            "or override the `get_ordering_queryset` method."
            % self.__class__.__name__
        )

    def save(self, *args, **kwargs):
        assert self.ordering_field is not None, (
            "'%s' must specify an `ordering_field`" % self.__class__.__name__
        )

        if getattr(self, self.ordering_field) is None:
            try:
                instances = self.get_ordering_queryset().all()
                last = sorted(instances, key=attrgetter(self.ordering_field))[::-1][0]
                ordering_value = getattr(last, self.ordering_field) + 1
            except IndexError:
                ordering_value = 0

            setattr(self, self.ordering_field, ordering_value)

        super(OrderedModel, self).save(*args, **kwargs)

    class Meta:
        abstract = True


import time
from django_rq import job
from .models import Author

@job
def get_report():
    start = time.time()
    time.sleep(60)
    authors = Author.objects.all()
    with open('report.txt', 'w', encoding='utf-8') as f:
        for author in authors:
            f.write(author.nickname+'\n')
    return time.time() - start

@job
def get_report_fast():
    time.sleep(5)
    authors = Author.objects.all()
    with open('report_fast.txt', 'w', encoding='utf-8') as f:
        for author in authors:
            f.write(author.nickname+'\n')


from __future__ import annotations
from tkinter import *
from typing import List, Tuple
from unittest import result
from tabuleiro import Posicao, ResultadosJogada, Tabuleiro

class GerenteInterfaceGrafica:
    """
    Essa classe é responsável por exibir o estado do jogo em uma janela.
    Pertence ao domínio da solução.
    """

    def __init__(self, tab : Tabuleiro, interface_jogador : 'InterfaceJogador') -> None:
        self.__tab = tab
        self.__interface = interface_jogador
        self.__janela_principal : Tk = None
        self.__quadro_principal : Frame = None
        self.__quadro_mensagem : Frame = None
        self.__quadro_botoes : Frame = None
        self.__vazio : PhotoImage = None
        self.__moeda : PhotoImage = None
        self.__p1 : PhotoImage = None
        self.__p2 : PhotoImage = None
        self.__imgs_tabuleiro : List[List[Label]] = list()

        self.__mover_cima : Button = None
        self.__mover_baixo : Button = None
        self.__mover_esquerda : Button = None
        self.__mover_direita : Button = None
        self.__passar : Button = None
        self.__reiniciar : Button = None
        self.__label_mensagem : Button = None

    def atualizar_posicoes(self, resultado_jogada : ResultadosJogada) -> None:
        posicoes = resultado_jogada.obter_pos_modificadas()
        for pos in posicoes:
            img = self.__selecionar_imagem(pos)
            x = pos.x()
            y = pos.y()
            l = self.__get_label(x,y)
            l.configure(image=img)
            l.image = img

    def redefinir_mensagem(self) -> None:
        self.__label_mensagem['text'] = "Vez do jogador 1"

    def __gerar_msg_prox_jogador(self, j_atual : int) -> str:
        return "Vez do jogador {}".format(j_atual+1)

    def __gerar_msg_vencedor(self, j_atual : int) -> str:
        return "Jogador {} venceu".format(j_atual+1)

    def atualizar_mensagem(self, resultados_jogada : ResultadosJogada) -> None:
        j_atual = resultados_jogada.obter_prox_jogador()
        if resultados_jogada.obter_status_partida() is False:
            self.__label_mensagem['text'] = self.__gerar_msg_prox_jogador(j_atual)
        else:
            self.__label_mensagem['text'] = self.__gerar_msg_vencedor(j_atual)

    def construir_interface_grafica(self, estado_tabuleiro : List[List[Posicao]]) -> None:
        self.__construir_janela_principal()
        self.__construir_quadros()
        self.__carregar_imagens()

        self.__construir_tabuleiro()

        self.atualizar_interface_grafica(estado_tabuleiro)

        self.__construir_botoes()

        self.__janela_principal.mainloop()

    def __construir_janela_principal(self) -> None:
        self.__janela_principal = Tk()
        self.__janela_principal.title("The Collectors")
        self.__janela_principal.geometry("1000x1000")
        self.__janela_principal.resizable(False, False)
        self.__janela_principal["bg"] = "gray"

    def __construir_quadros(self) -> None:
        self.__quadro_principal = Frame(self.__janela_principal, padx=32, pady=25, bg="gray")
        self.__quadro_mensagem = Frame(self.__janela_principal, padx=4, pady=1, bg="gray")
        self.__quadro_botoes = Frame(self.__janela_principal, padx=4, pady=1, bg="gray")

        self.__quadro_principal.grid(row=0 , column=0)
        self.__quadro_botoes.grid(row=1, column=0)
        self.__quadro_mensagem.grid(row=2 , column=0)

    def __carregar_imagens(self) -> None:
        self.__vazio = PhotoImage(file="imagens/fundo.gif")
        self.__moeda = PhotoImage(file="imagens/fundo_moeda.gif")
        self.__p1 = PhotoImage(file="imagens/p1.gif")
        self.__p2 = PhotoImage(file="imagens/p2.gif")

    def __construir_tabuleiro(self) -> None:
        for x in range(12):
            linha : List[Label] = list()
            for y in range(12):
                l = Label(self.__quadro_principal, bd=0.5, relief='solid', image=self.__vazio)
                linha.append(l)
                l.grid(row=x , column=y)
            self.__imgs_tabuleiro.append(linha)

    def __construir_botoes(self) -> None:
        self.__mover_cima = Button(self.__quadro_botoes, text="cima", command=lambda: self.__interface.mover_jogador(0, -1))
        self.__mover_cima.grid(row=0, column=0)
        self.__mover_baixo = Button(self.__quadro_botoes, text="baixo", command=lambda: self.__interface.mover_jogador(0, 1))
        self.__mover_baixo.grid(row=0, column=1)
        self.__mover_esquerda = Button(self.__quadro_botoes, text="esquerda", command=lambda: self.__interface.mover_jogador(-1, 0))
        self.__mover_esquerda.grid(row=0, column=2)
        self.__mover_direita = Button(self.__quadro_botoes, text="direita", command=lambda: self.__interface.mover_jogador(1, 0))
        self.__mover_direita.grid(row=0, column=3)
        self.__passar = Button(self.__quadro_botoes, text="passar a vez", command=lambda: self.__interface.passar_vez())
        self.__passar.grid(row=0, column=4)
        self.__reiniciar = Button(self.__quadro_botoes, text="reiniciar", command=lambda: self.__interface.reiniciar_partida())
        self.__reiniciar.grid(row=0, column=5)
        self.__label_mensagem = Label(self.__quadro_mensagem, bg="gray", text='Vez do jogador 1', font="arial 14")
        self.__label_mensagem.grid(row=0, column=0, columnspan=3)

    def __get_label(self, x : int, y : int) -> Label:
        return self.__imgs_tabuleiro[x][y]

    def __get_pos(self, estado_tabuleiro : List[List[Posicao]], x : int, y : int) -> Posicao:
        return estado_tabuleiro[x][y]

    def __get_label(self, x : int, y : int) -> Label:
        return self.__imgs_tabuleiro[y][x]

    def atualizar_interface_grafica(self, estado_tabuleiro : List[List[Posicao]]) -> None:
        for x in range(12):
            for y in range(12):
                pos = self.__get_pos(estado_tabuleiro, x, y)
                label = self.__get_label(x,y)
                img = self.__selecionar_imagem(pos)
                label.configure(image=img)
                label.image = img

    def __selecionar_imagem(self, pos : Posicao) -> PhotoImage:
        if pos.jogador1():
            return self.__p1
        elif pos.jogador2():
            return self.__p2
        elif pos.moeda():
            return self.__moeda
        else:
            return self.__vazio


import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib

print("Initializing Jarvis")
MASTER = "Shesh"

engine = pyttsx3.init('sapi5')
voices = engine.getProperty('voices')
engine.setProperty('voice', voices[0].id)

def speak(text):
    engine.say(text)
    engine.runAndWait()

def wishMe():
    hour = int(datetime.datetime.now().hour)
    print(hour)

    if hour>=0 and hour <12:
        speak("good morning" + MASTER)

    elif hour>=12 and hour<18:
        speak("good afternoon" + MASTER)

    else:
        speak("good Evening" + MASTER)

    speak("i am your assistant. How may I help you?")

def sendEmail(to, content):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.login('shakya1125@gmail.com', 'password')
    server.sendmail("madhu2003@gmail.com", to, content)
    server.close()

def takeCommand():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening...")
        audio = r.listen(source)

    try :
        print("Recognizing...")
        query = r.recognize_google(audio, language = 'en-in')
        print(f"user said: {query}\n")

    except Exception as e:
        print("Say that again please...")
        query = None

    return query

def main():
    speak("Initializing Jarvis...")
    wishMe()
    query = takeCommand()

    if 'wikipedia' in query.lower():
        speak('searching wikipedia...')
        query = query.replace("wikipedia", "")
        results = wikipedia.summary(query, sentences =2)
        print(results)
        speak(results)

    elif 'open youtube' in query.lower():

        url = "youtube.com"
        chrome_path ='C:\\Users\\admin\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'
        webbrowser.get(chrome_path).open(url)

    elif 'open google' in query.lower():

        url = "google.com"
        chrome_path = 'C:\\Users\\admin\\AppData\\Local\\Google\\Chrome\\Application\\chrome.exe'
        webbrowser.get(chrome_path).open(url)

    elif 'play music' in query.lower():
        songs_dir = "C:\music\music"
        songs = os.listdir(songs_dir)
        print(songs)
        os.startfile(os.path.join(songs_dir, songs[0]))

    elif 'the time' in query.lower():
        strTime = datetime.datetime.now().strftime("%H:%M:%S")
        speak(f"{MASTER} the time is {strTime}")

    elif 'open code' in query.lower():
        codePath = "D:\Voive Ass"
        os.startfile(codePath)

    elif 'email to madhu' in query.lower():
        try:
            speak("what should i send")
            content = takeCommand()
            to = "madhu2003@gmail.com"
            sendEmail(to, content)
            speak("Email has been sent to madhu")
        except Exception as e:
            print(e)

main()


#!/usr/bin/env python
maxnum = 2**25

for x in range(1, maxnum + 1):
    if x % 15 == 0:
        print('fizzbuzz')
    elif x % 5 == 0:
        print('buzz')
    elif x % 3 == 0:
        print('fizz')
    else:
        numstr = str(bin(x))[2:].replace('1', '9')
        emp_str = "% 25s" % numstr
        zero_str = emp_str.replace(' ', '0')
        all = zero_str[:5] + ':' +  \
                zero_str[5:10] + ':' + \
                zero_str[10:15] + ':' + \
                zero_str[15:20] + ':' + \
                zero_str[20:]
        print(all)


# ##### BEGIN GPL LICENSE BLOCK #####
#
#  This program is free software; you can redistribute it and/or
#  modify it under the terms of the GNU General Public License
#  as published by the Free Software Foundation; either version 2
#  of the License, or (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software Foundation,
#  Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
#
# ##### END GPL LICENSE BLOCK #####

import os
import json

import bpy
from bpy.app.handlers import persistent
from bpy_extras.io_utils import ImportHelper

use_icons = False
try:
	import bpy.utils.previews
	use_icons = True
except:
	pass

from . import addon_updater_ops
from .poliigon_converter import PMC_workflow
from .poliigon_converter import get_preferences

# -----------------------------------------------------------------------------
# GLOBALS
# -----------------------------------------------------------------------------

global preview_collections
preview_collections = {}
global config_data
config_data = {}

# list of valid filename endings, non case-sensitive (but keep these lowercase)
imgtypes = [".bmp",".sgi",".rgb",".bw",".png", ".jpg",".jpeg",".jp2",".j2c",
			".tga",".cin",".dpx",".exr",".hrd",".tiff",".tif"]
MAX_SEARCH_DEPTH = 5 # inclusive, folder levels deep for searching for images

MAPPING_ITEMS = (
	("uv_uber_mapping", "UV + UberMapping", "Use UV coordinate type mapping, and the Poliigon mapping node group"),
	("uv_standard", "UV + Standard Mapping", "Use UV coordinate type mapping, and built in mapping node"),
	("flat_standard", "Generated (Flat) + Standard Mapping", "Use generated coordinate type mapping, and built in mapping node"),
	("box_standard", " Generated (Box) + Standard Mapping", "Use box coordinate type mapping, and built in mapping node")
)

# -----------------------------------------------------------------------------
# FUNCTIONS
# -----------------------------------------------------------------------------

def print_verbose(*args):
	"""Print only if verbose enabled"""
	prefs = get_preferences()
	if not prefs:
		# default to print?
		print(" ".join(map(str, args)))
	if prefs.verbose:
		print(" ".join(map(str, args)))

def load_file_sets_from_path(path):
	"""Load folder and subfolder of image files"""

	path = bpy.path.abspath(path)
	if not os.path.isdir(path):
		return []

	# recursive find images down to three levels deep of subfolders
	subfiles = []
	for root, dirs, files in os.walk(path, topdown=True):
		depth = root[len(path) + len(os.path.sep):].count(os.path.sep)
		if depth < MAX_SEARCH_DEPTH:
			# We're currently two directories in, so all subdirs have depth 3
			subfiles += [os.path.join(root, d) for d in files \
						if os.path.splitext(d)[-1] in imgtypes]

	# consoldiate/extract the base name paths for the material sets
	paths = PMC_workflow.get_sets_from_filenames(None, subfiles)

	# build format to pass through to loading popup operator
	file_sets = [{"name" : "", "setpath" : p, "warning":""} for p in paths]

	# print_verbose("Poliigon, detected filesets:", file_sets)
	return file_sets

def folderset_list_update(context, items):
	"""Triggered to re-draw/load the list, called after folder name changes"""
	pmcprop = context.window_manager.pmc_props
	pmcprop.folderset_list.clear()

	# clear existing thumbnails, if any
	material_thumbs = preview_collections["materials"]
	material_thumbs.clear()

	workflow = PMC_workflow() # reusing same object
	items_sorted = []

	for itm in items:
		# load with dryrun, so won't actually build material, just get settings
		status, _ = workflow.build_material_from_set(context, itm["setpath"], dryrun=True)
		items_sorted.append([itm, status.copy(),
							 workflow.build_name(),
							 workflow.workflow,
							 workflow.get_thumbnail(pmcprop.preview_type)])

	# zip sorting based on to-be-made material name
	n = [new[2] for new in items_sorted] # ie actual build name
	fallback = range(0,len(n)) # in case of name clash, use starting order
	items_sorted = [new[-1] for new in sorted(zip(n,fallback,items_sorted))]

	# list the non-specular workflows found
	non_spec = [itm[2] for itm in items_sorted if itm[3] != "SPECULAR"]

	for i, (itm, status, build_name, itm_workflow, thumbnail) in enumerate(items_sorted):
		# skip if specular and non-spec exists
		if itm_workflow == "SPECULAR" and build_name in non_spec:
			continue

		if thumbnail:
			thumb_id = i
			_ = material_thumbs.load(str(thumb_id), thumbnail, 'IMAGE')
		else:
			thumb_id = -1

		item = pmcprop.folderset_list.add()
		item.label = "{} material set".format(build_name)
		item.description = build_name
		item.name = build_name
		item.setpath = itm["setpath"]
		item.checked = True
		item.loaded = False
		item.materialname = build_name
		item.thumb_id = thumb_id

		urllist = workflow.splitMaterialName(build_name)
		urlend = ''
		for a in urllist:
			urlend += a+"%20"
		item.urlend = urlend[:-3]

		if status != {}:
			item.checked = False

		# distinguish if already loaded (show check), or just material name overlap
		for m in bpy.data.materials:
			if m.pmc_matprops.setpath == itm['setpath']:
				item.checked = False
				item.loaded = True
				item.materialname = m.name

		# in all cases, dump status - if all is good, then is equal to "{}",
		# used for drawing in list ui
		item.status = json.dumps(status)

	# Finally, update the row index if needed
	if len(pmcprop.folderset_list) <= pmcprop.folderset_list_index:
		pmcprop.folderset_list_index = len(pmcprop.folderset_list)-1

def folderset_update(self, context):
	items = load_file_sets_from_path(context.window_manager.pmc_texture_path)
	folderset_list_update(context, items)

def deselect_all_update(self, context):
	""" Triggered when the deselect_property is toggled"""
	pmcp = context.window_manager.pmc_props

	# skip if being internally modified, or nothing loaded yet anyways
	if pmcp.deselect_all_internal is True:
		return
	elif not pmcp.folderset_list:
		return

	pmcp.check_toggle_internal = True
	if pmcp.deselect_all is True:
		for itm in pmcp.folderset_list:
			if itm.checked is True:
				itm.checked = False
	else:
		any_checked = False
		for itm in pmcp.folderset_list:
			if itm.loaded is False:
				itm.checked = True
				any_checked = True
				# consider restricting to only checking True those without errors
		if not any_checked:
			# scenario where everything is already loaded, so flip deselect
			# back to being on (as nothing is selected)
			# Will have UI behavior of clicking, but it staying on
			pmcp.deselect_all_internal = True
			pmcp.deselect_all = True
			pmcp.deselect_all_internal = False

	pmcp.check_toggle_internal = False
	return

def folderset_list_col_checked_update(self, context):
	"""Triggered when a detected material's checkmark is toggled"""
	pmcp = context.window_manager.pmc_props
	if pmcp.check_toggle_internal is True:
		return
	anychecks = [itm.checked for itm in pmcp.folderset_list \
				if itm.checked is True]

	# set the state of the deselect button accordingly
	pmcp.deselect_all_internal = True
	if True not in anychecks:
		pmcp.deselect_all = True
	else:
		pmcp.deselect_all = False
	pmcp.deselect_all_internal = False

def get_json_path():
	"""Returns primary path for json config data"""
	return os.path.join(os.path.dirname(__file__),"config.json")

def load_json():
	"""Load values of json config values"""
	json_path = get_json_path()
	if not os.path.isfile(json_path):
		return {}
	try:
		infile = open(json_path,'r')
		data = json.load(infile)
		infile.close()
		return data
	except:
		return {}

def save_json_key(key, value):
	"""Save key to json file."""
	global config_data
	config_data = load_json()
	config_data[key] = value

	with open(get_json_path(), 'w') as outfile:
		json.dump(config_data, outfile)

	# reload the property with updated default
	register_texture_path()

def default_texture_path():
	"""Default value for the textures path."""
	global config_data
	config_data = load_json()
	if "texture_path" in config_data:
		return config_data["texture_path"]
	else:
		return "//"

@persistent
def load_post(scene):
	"""Runs after opening a file, such as fresh open."""
	config_data = load_json()
	if config_data == {}:
		return
	elif 'texture_path' not in config_data:
		return
	elif config_data['texture_path'] == "//":
		return

	# this will cause some delay on reload, depending on size of folder set
	bpy.ops.pmc.refresh_folder()

def register_texture_path():
	"""Function to on-the-fly deregister and register the texturepath."""

	if hasattr(bpy.types.WindowManager, "pmc_texture_path"):
		del bpy.types.WindowManager.pmc_texture_path

	bpy.types.WindowManager.pmc_texture_path = bpy.props.StringProperty(
		name = "Textures folder",
		description = "Folder or folder of folders of material images",
		subtype = 'DIR_PATH',
		update = folderset_update,
		default = default_texture_path()
	)

def get_material_thumbnails(self, context):
	"""Function to return thumbnails for UI drawing"""

	# must save to global variable to avoid known blender enum strings issue
	global ENUM_THUMBNAIL_LIST
	ENUM_THUMBNAIL_LIST = []

	pmaterials = preview_collections["materials"]
	pmain = preview_collections["main"]

	pmcprop = context.window_manager.pmc_props
	for i, material_set in enumerate(pmcprop.folderset_list):
		if not pmaterials and (not pmain or "no_preview" not in pmain):
			icon = "ERROR"
		elif not pmaterials:
			icon = pmain["no_preview"].icon_id
		elif material_set.thumb_id == -1:
			icon = pmain["no_preview"].icon_id
		else:
			if str(material_set.thumb_id) not in pmaterials:
				print("Error! {} not in thumbs".format(material_set.thumb_id))
				icon = pmain["no_preview"].icon_id
			else:
				temp = pmaterials[str(material_set.thumb_id)]
				icon = temp.icon_id

		ENUM_THUMBNAIL_LIST.append((
			str(i),
			str(material_set.name),
			"Preview the material {}".format(material_set.name),
			icon,
			i, # retain order
		))
	return ENUM_THUMBNAIL_LIST

def update_folderset_list_index(self, context):
	"""Update trigger to adjust thumbnail if select UI row is changed"""
	pmcprop = context.window_manager.pmc_props
	if pmcprop.check_toggle_internal is True:
		return
	if not pmcprop.folderset_list:
		return
	pmcprop.check_toggle_internal = True
	pmcprop.thumbnails = str(pmcprop.folderset_list_index)
	pmcprop.check_toggle_internal = False

def update_material_thumbnails(self, context):
	"""Trigger called to update thumbnails"""
	pmcprop = context.window_manager.pmc_props
	if pmcprop.check_toggle_internal is True:
		return
	pmcprop.check_toggle_internal = True
	pmcprop.folderset_list_index = int(pmcprop.thumbnails)
	pmcprop.check_toggle_internal = False

# -----------------------------------------------------------------------------
# OPERATORS / SUPPORT CLASSES
# -----------------------------------------------------------------------------

class PathItem(bpy.types.PropertyGroup):
	"""Class to pass group of image paths from one operator to the next"""
	setpath = bpy.props.StringProperty(name="Set path")
	warning = bpy.props.StringProperty(name="Warning")

class PMC_load_materials_from_UIList(bpy.types.Operator):
	bl_idname = "pmc.load_materials_from_uilist"
	bl_label = "Load materials"
	bl_description = "Load all checked materials in list"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	def execute(self,context):
		pmcs = context.scene.pmc_sceneprops
		file_sets = [{"name" : "", "setpath" : itm.setpath, "warning":itm.status} \
			for	itm in context.window_manager.pmc_props.folderset_list.values() \
			if itm.checked is True]
		bpy.ops.pmc.load_material_popup(#'INVOKE_DEFAULT',
				file_sets=file_sets,
				loading_from_uilist=True,
				use_ao=pmcs.use_ao,
				use_disp=pmcs.use_disp,
				use_sixteenbit=pmcs.use_sixteenbit,
				conform_uv=pmcs.conform_uv,
				use_micro_displacements=pmcs.use_micro_displacements,
				mapping_type=pmcs.mapping_type
				)
		return {'FINISHED'}

class PMC_load_and_apply_material(bpy.types.Operator):
	bl_idname = "pmc.load_and_apply_material"
	bl_label = "Load & Apply Material"
	bl_description = "Load (or reload) and apply highlighted material"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	index = bpy.props.IntProperty(options={'HIDDEN'})

	@classmethod
	def poll(cls, context):
		# disable operator if material already loaded
		ind = bpy.context.window_manager.pmc_props.folderset_list_index
		if not bpy.context.window_manager.pmc_props.folderset_list:
			return False
		if len(bpy.context.window_manager.pmc_props.folderset_list) <= ind:
			return False
		else:
			return True

	def execute(self,context):
		pmcs = context.scene.pmc_sceneprops
		itm = context.window_manager.pmc_props.folderset_list[self.index]
		file_sets = [{"name" : "", "setpath" : itm.setpath, "warning":itm.status}]
		bpy.ops.pmc.load_material_popup(
				file_sets=file_sets,
				loading_from_uilist=True,
				use_ao=pmcs.use_ao,
				use_disp=pmcs.use_disp,
				use_sixteenbit=pmcs.use_sixteenbit,
				conform_uv=pmcs.conform_uv,
				use_micro_displacements=pmcs.use_micro_displacements,
				mapping_type=pmcs.mapping_type
				)

		if context.selected_objects:
			bpy.ops.pmc.apply_material('INVOKE_DEFAULT', index=self.index)
			if pmcs.use_disp:
				self.report({"WARNING"}, "Default displacement = 0, consider adjusting")
		else:
			self.report({"WARNING"}, "No objects selected to apply material")
		return {'FINISHED'}

class PMC_load_material_popup(bpy.types.Operator):
	"""Executes material loading, no longer used as a popup however"""
	bl_idname = "pmc.load_material_popup"
	bl_label = "Load Material Settings"
	bl_description = "Confirm settings for loading materials"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	# sets of materials based on filenames, already made unique
	file_sets = bpy.props.CollectionProperty(type=PathItem)

	# additional loading settings
	loading_from_uilist = bpy.props.BoolProperty(
		default=False,
		options={"HIDDEN"}
	)
	use_ao = bpy.props.BoolProperty(
		name="Include Ambient Occlusion (AO)",
		description="Use Ambient Occlusion maps (if available)",
		default=True
	)
	use_disp = bpy.props.BoolProperty(
		name="Include Displacement maps",
		description="Use Displacement maps (if available)",
		default=True
	)
	use_sixteenbit = bpy.props.BoolProperty(
		name="Use 16 bit maps (if available)",
		description="Use 16 bit maps (if available)",
		default=False
	)
	conform_uv = bpy.props.BoolProperty(
		name="Conform maps to image dimensions",
		description="Set mapping-node scale to ensure uniform UVs",
		default=True
	)
	use_micro_displacements = bpy.props.BoolProperty(
		name="Use micro-displacements (if available, enables experimental)",
		description="Enable micro displacements using adaptive subdivision. "+\
		"Note! This will enable blender's experimental mode if not already active",
		default=False
	)
	mapping_type = bpy.props.EnumProperty(
		name="Coordinate type",
		description="Determine what method of texture coordiantes to use",
		items=MAPPING_ITEMS
	)

	def execute(self, context):
		pmcs = context.scene.pmc_sceneprops
		pmcp = context.window_manager.pmc_props
		# ensure the pricnipled shader exists
		if not hasattr(bpy.types, 'ShaderNodeBsdfPrincipled'):
			print("Poliigon: Blender is missing required BSDF Principled shader, use blender 2.79+")
			self.report({"ERROR","Blender is missing required BSDF Principled shader"})
			return {'CANCELLED'}

		# ensure at least one set is included
		if not self.file_sets:
			print("Poliigon: No paths included, nothing imported")
			self.report({"INFO"},"No paths included, nothing imported")
			return {'CANCELLED'}

		print_verbose("Poliigon: Running load materials, {} sets identified".format(
				len(self.file_sets)))
		paths = [name.setpath for name in self.file_sets] # convert to paths
		added_materials = []
		added_objects = []
		imported_models = False
		initial_active = context.active_object
		if bpy.app.version < (2, 80):
			self.use_micro_displacements = False

		# previously could load multiple materials at once, though now only one
		for set_path in paths:
			print_verbose("Poliigon: Loading "+set_path)
			# will auto initialize material builder
			workflow = PMC_workflow(
					use_ao=self.use_ao,
					use_disp=self.use_disp,
					use_sixteenbit=self.use_sixteenbit,
					conform_uv=self.conform_uv,
					microdisp=self.use_micro_displacements,
					mapping=self.mapping_type
					)
			status, material = workflow.build_material_from_set(context,set_path)
			added_materials.append((status, material))

			# Load OBJ if file exists
			# (must truncate the size off of setpath, e.g. '_4K')
			model_basename = workflow.setpath[:-(1+len(workflow.size))]
			obj_path = model_basename + ".obj"
			fbx_path = model_basename + ".fbx"
			new_objects = []
			if not pmcs.import_object:
				pass
			elif os.path.isfile(obj_path):
				print_verbose("Poliigon: Found OBJ to import "+obj_path)
				try:
					initial_objs = list(bpy.data.objects)
					bpy.ops.import_scene.obj(filepath=obj_path)
					new_objects = list( set(bpy.data.objects) - set(initial_objs))
				except Exception as e:
					print_verbose("Poliigon: Failed to import OBJ model: "+str(e))
			elif os.path.isfile(fbx_path):
				print_verbose("Poliigon: Found FBX to import "+fbx_path)
				try:
					initial_objs = list(bpy.data.objects)
					bpy.ops.import_scene.fbx(filepath=fbx_path)
					new_objects = list(set(bpy.data.objects) - set(initial_objs))
				except Exception as e:
					print_verbose("Poliigon: Failed to import FBX model: "+str(e))
					new_objects = []

			if new_objects:
				print_verbose("Poliigon: Model objects imported, applying settings ")
				imported_models = True
				added_objects += new_objects
				for ob in new_objects:
					ob.data.materials.clear() # clears materials, not slots
					ob.active_material_index = 0 # ensure first slot is used
					ob.active_material = material # auto-creates slot
					print_verbose("Poliigon: \tAdded material to "+ob.name)

				print_verbose("Poliigon: Model imported and material applied")

				# attempt to make paths relative
				if bpy.data.filepath=='':
					print_verbose("File not saved, could not make paths relative")
				else:
					print_verbose("attemping to make relative paths")
					workflow.set_relative()

			# update the UI list flag as imported
			ui_set = [row for row in pmcp.folderset_list
				if row.setpath == set_path]
			if ui_set:
				ui_set[0].loaded = True
			else:
				print_verbose("Poliigon: Could not directly mark material as loaded, full reloading")

			# clear the material setpath of other previously imported materials
			existing_mats = [mat for mat in bpy.data.materials
				if mat.pmc_matprops.setpath == material.pmc_matprops.setpath
				and mat != material]
			for mat in existing_mats:
				mat.pmc_matprops.setpath = "" # cleared to not apply old mat

		self.report({'INFO'},"Loaded {} materials".format(len(added_materials)))
		print_verbose("Poliigon: Loaded {} materials".format(len(added_materials)))
		# folderset_update(self, context)

		if imported_models:
			# if auto-imported models, do some additional cleanup
			if initial_active:
				bpy.data.objects.remove(initial_active)
			if added_objects:
				if hasattr(bpy.data, "collections"): # 2.8
					group = bpy.data.collections.new(os.path.basename(model_basename))
				else:
					group = bpy.data.groups.new(os.path.basename(model_basename))
				for ob in added_objects:
					group.objects.link(ob)
					if hasattr(ob, "select_set"): # 2.8
						ob.select_set(True)
					else:
						ob.select = True
			# make at least one of the objects active
			if hasattr(context, "view_layer"):
				context.view_layer.objects.active = added_objects[0] # the 2.8 way
			else:
				context.scene.objects.active = added_objects[0] # the 2.7 way
			bpy.ops.object.transforms_to_deltas(mode='ROT', reset_values=True)

		return {'FINISHED'}

class PMC_refresh_folder(bpy.types.Operator):
	bl_idname = "pmc.refresh_folder"
	bl_label = "Refresh Poliigon Material Folder"
	bl_description = "Click to refresh folder for loading Poliigon textures"

	def execute(self, context):
		folderset_update(self, context)
		return {'FINISHED'}

class PMC_apply_material(bpy.types.Operator):
	bl_idname = "pmc.apply_material"
	bl_label = "Apply Material"
	bl_description = "Replace all materials on selected meshes with the selected material"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	index = bpy.props.IntProperty(options={'HIDDEN'})

	@classmethod
	def poll(cls, context):
		ind = bpy.context.window_manager.pmc_props.folderset_list_index
		if len(bpy.context.window_manager.pmc_props.folderset_list)!=0:
			itm = bpy.context.window_manager.pmc_props.folderset_list[ind]
			if itm.loaded:
				return True
			else:
				return False
		else:
			return False

	def execute(self, context):
		addon_prefs = get_preferences(context)
		pmcs = context.scene.pmc_sceneprops
		if not addon_prefs:
			verbose = None
		else:
			verbose = addon_prefs.verbose

		itm = context.window_manager.pmc_props.folderset_list[self.index]
		# mat = itm.materialname

		valid_mats = [mat for mat in bpy.data.materials
			if mat.pmc_matprops.setpath == itm.setpath]
		if not valid_mats:
			self.report({"ERROR"},"Could not apply material to object, material not matched")
			print_verbose("Could not apply material to object, material not matched")
			return {'CANCELLED'}
		mat = valid_mats[-1] # select one, though shouldn't be duplciates really

		# list of selected objects which can have materials applied (must support UVs)
		# TODO, consider expanding availability
		objs = [ob for ob in context.selected_objects if hasattr(ob.data,"uv_layers")]

		if len(context.selected_objects)==0:
			self.report({"ERROR"},"No objects selected to apply materials")
			return {'CANCELLED'}
		elif len(objs)==0:
			self.report({"ERROR"},"No objects selected supporting materials")
			print_verbose("No objects selected supporting materials")
			return {'CANCELLED'}

		count_no_UV = 0

		if verbose:
			print("Applying materials for these objects:")
			print(objs)

		# clear existing materials, and apply micro displacements if appropriate
		for ob in objs:
			# ob.data.materials.clear() # clears materials, not slots
			# ob.active_material_index = 0 # ensure first slot is used
			ob.active_material = mat # auto-creates slot if needed

			# add adaptive subdiv if micro displacements set to true, and experimental
			if mat.pmc_matprops.use_micro_displacements:
				if not hasattr(ob, "cycles"):
					print_verbose("Poliigon: Cycles not available, cannot set adaptive subdivision")
				elif not hasattr(ob.cycles, "use_adaptive_subdivision"):
					print_verbose("Poliigon: No adaptive subdivision available")
				else:
					ob.cycles.use_adaptive_subdivision = True
					any_subsurf = len([mod for mod in ob.modifiers if mod.type=="SUBSURF"])>0
					if not any_subsurf:
						mod = ob.modifiers.new(type='SUBSURF', name="Micro Subsurf")
						mod.levels=0
						mod.render_levels=0
			if len(ob.data.uv_layers)==0:
				count_no_UV += 1
				print_verbose("Object is missing UVs for applying materials: "+
						ob.name)

		if count_no_UV > 0 and pmcs.mapping_type in ('uv_uber_mapping', 'uv_standard'):
			# Only warn if using a UV approach
			print_verbose("No UV layers found on "+str(count_no_UV)+
						" of selected objects, please unwrap meshes")
			bpy.ops.pmc.missing_uv_warnings(
				'INVOKE_DEFAULT', count_missing_uvs=count_no_UV)
		return {'FINISHED'}

class PMC_missing_UV_warnings(bpy.types.Operator):
	bl_idname = "pmc.missing_uv_warnings"
	bl_label = "Objects Missing UVs"
	bl_description = "Warning popup for when there are missing UVs on material-applied objects"
	bl_options = {'INTERNAL'}

	count_missing_uvs = bpy.props.IntProperty(options={'HIDDEN'})

	def invoke(self, context, event):
		return context.window_manager.invoke_props_dialog(self)

	def draw(self, context):
		layout = self.layout
		col = layout.column()
		col.scale_y = 0.7
		col.label(text="No UV layers found on {} of the  selected objects,".format(
				self.count_missing_uvs),
				icon="ERROR")
		if self.count_missing_uvs==1:
			col.label(text="please unwrap mesh", icon="BLANK1")
		else:
			col.label(text="please unwrap meshes", icon="BLANK1")

	def execute(self, context):
		return {'FINISHED'}

class PMC_set_default_path(bpy.types.Operator):
	bl_idname = "pmc.set_default_path"
	bl_label = "Save path"
	bl_description = "Save as the default path for loading textures"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	def execute(self, context):
		path = context.window_manager.pmc_texture_path
		save_json_key("texture_path", path)
		return {'FINISHED'}

class PMC_unset_default_path(bpy.types.Operator):
	bl_idname = "pmc.unset_default_path"
	bl_label = "Apply Material"
	bl_description = "Remove this custom path for loading textures"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	def execute(self, context):
		context.window_manager.pmc_texture_path = "//"
		save_json_key("texture_path", "//")
		return {'FINISHED'}

class PMC_remove_unused_materials(bpy.types.Operator):
	bl_idname = "pmc.remove_unused_materials"
	bl_label = "Remove Unused Materials"
	bl_description = "Removes all unused materials imported by the Poliigon converter"
	bl_options = {'REGISTER', 'UNDO', 'INTERNAL'}

	def execute(self,context):
		removed_mats = 0
		removed_images = 0

		materials = [material for material in bpy.data.materials
			if material.pmc_matprops
			and material.pmc_matprops.setpath # not empty, thus from converter
			and ((material.users == 0 and not material.use_fake_user)
				or (material.users == 1 and material.use_fake_user))
			]
		material_images = []

		for mat in materials:
			if mat.node_tree and mat.node_tree.nodes:
				material_images += [
					node.image for node in mat.node_tree.nodes
					if node.type == "TEX_IMAGE"
					and node.image]

			mat.use_fake_user = False
			bpy.data.materials.remove(mat)
			removed_mats += 1

		for image in material_images:
			if not image.users == 0:
				continue
			image.user_clear()
			bpy.data.images.remove(image)
			removed_images += 1

		folderset_update(self, context)
		if removed_images > 0 or removed_mats > 0:
			self.report({"INFO"}, "Removed {} materials and {} images".format(
				removed_mats, removed_images))
		else:
			self.report({"WARNING"}, "No materials or images removed")
		return {'FINISHED'}

# -----------------------------------------------------------------------------
# PREFERENCES AND PROPERTY GROUPS
# -----------------------------------------------------------------------------

class PMC_preferences(bpy.types.AddonPreferences):
	bl_idname = __package__

	verbose = bpy.props.BoolProperty(
		name = "Verbose",
		description = "Print out more logging information, for debugging",
		default = False)

	# addon updater preferences

	auto_check_update = bpy.props.BoolProperty(
		name="Auto-check for update every week",
		description="If enabled, auto-check for updates using an interval",
		default=False,
		)
	updater_intrval_months = bpy.props.IntProperty(
		name='Months',
		description="Number of months between checking for updates",
		default=0,
		min=0
		)
	updater_intrval_days = bpy.props.IntProperty(
		name='Days',
		description="Number of days between checking for updates",
		default=7,
		min=0,
		)
	updater_intrval_hours = bpy.props.IntProperty(
		name='Hours',
		description="Number of hours between checking for updates",
		default=0,
		min=0,
		max=23
		)
	updater_intrval_minutes = bpy.props.IntProperty(
		name='Minutes',
		description="Number of minutes between checking for updates",
		default=0,
		min=0,
		max=59
		)

	def draw(self, context):
		layout = self.layout
		if not hasattr(bpy.types, 'ShaderNodeBsdfPrincipled'):
			box = layout.box()
			col = box.column()
			col.scale_y = 0.7
			col.label(text="")
			col.label(text="This blender version is missing required BSDF Principled "+\
					"shader node, use blender v2.79+ to use addon", icon="ERROR")
			col.label(text="")
			return

		mainrow = layout.row()
		col = mainrow.column()
		row = col.row(align=True)
		row.scale_y = 2
		pmain = preview_collections["main"]
		if not pmain or "poliigon_logo" not in pmain:
			p = row.operator("wm.url_open", text="Get more textures")
		else:
			poliigon_icon = pmain["poliigon_logo"]
			p = row.operator("wm.url_open", text="Get more textures",
							icon_value=poliigon_icon.icon_id)
		p.url="http://poliigon.com"
		col.prop(self,"verbose",text="Show verbose logging in console")

		# updater draw function
		col = mainrow.column()
		addon_updater_ops.update_settings_ui_condensed(self, context, col)

# -----------------------------------------------------------------------------
# PROPERTY GROUPS
# -----------------------------------------------------------------------------

class folderset_list_col(bpy.types.PropertyGroup):
	"""Class to register properties to item rows of the to-be-imported list"""
	label = bpy.props.StringProperty(default="")
	description = bpy.props.StringProperty(default="")
	checked = bpy.props.BoolProperty(
		default=True,
		update=folderset_list_col_checked_update)
	setpath = bpy.props.StringProperty(default="")
	status = bpy.props.StringProperty(default="{}") # json format
	loaded = bpy.props.BoolProperty(default=False)
	materialname = bpy.props.StringProperty(default="")
	urlend = bpy.props.StringProperty(default="")
	thumb_id = bpy.props.IntProperty()

class PMC_props(bpy.types.PropertyGroup):
	"""Class to register properties to window, not saved with settings or file"""
	folderset_list = bpy.props.CollectionProperty(type=folderset_list_col)
	folderset_list_index = bpy.props.IntProperty(
		default=0,
		update=update_folderset_list_index)
	show_advanced = bpy.props.BoolProperty(
		name = "Advanced Options",
		description = "Show additional advanced options",
		default=False)
	deselect_all = bpy.props.BoolProperty(
		name = "Deselect All",
		description = "Deselect all materials detected, or select all if "+\
					"already deselected",
		default=False,
		update=deselect_all_update)
	deselect_all_internal = bpy.props.BoolProperty(
		description="Internally used property, for use in toggling "+\
					"deselect_all without triggering its update function",
		default=False,
		options={'HIDDEN'}
		)
	check_toggle_internal = bpy.props.BoolProperty(
		description="Internally used property, for use in toggling a detected "+\
					"set's checkmark without triggering its update function",
		default=False,
		options={'HIDDEN'}
		)
	thumbnails = bpy.props.EnumProperty(
		items=get_material_thumbnails,
		update=update_material_thumbnails
	)
	preview_type = bpy.props.EnumProperty(
		name = "Preferred preview",
		items=(
			("sphere", "Sphere", "Display sphere previews, if found", "MESH_UVSPHERE", 0),
			("cube", "Cube", "Display cube previews, if found", "MESH_CUBE", 1),
			("flat", "Flat", "Display flat previews, if found", "MESH_PLANE", 2)),
		update=folderset_update
	)

class PMC_scene_props(bpy.types.PropertyGroup):
	"""Class to register properties to scene, is saved with settings and file"""
	use_ao = bpy.props.BoolProperty(
		name="Include Ambient Occlusion maps (if available)",
		description="Use Ambient Occlusion maps (if available)",
		default=True
	)
	use_disp = bpy.props.BoolProperty(
		name="Include Displacement maps (if available)",
		description="Use Displacement maps (if available)",
		default=True
	)
	use_sixteenbit = bpy.props.BoolProperty(
		name="Use 16 bit maps (if available)",
		description="Load 16 bit version of texture maps where they exist",
		default=True
	)
	conform_uv = bpy.props.BoolProperty(
		name="Conform maps to image dimensions",
		description="Set the mapping-node scale to ensure uniform, non-stretching UVs",
		default=True
	)
	use_micro_displacements = bpy.props.BoolProperty(
		name="Use micro-displacements (if available, enables experimental)",
		description="Enable micro displacements using adaptive subdivision. "+\
		"Note! This will enable blender's experimental mode if not already active",
		default=False
	)
	mapping_type = bpy.props.EnumProperty(
		name="Coordinate type",
		description="Determine what method of texture coordiantes to use",
		items=MAPPING_ITEMS
	)
	import_object = bpy.props.BoolProperty(
		name="Import models (if found)",
		description="Automatically import associated object models with the material set",
		default=False
	)

class PMC_matprops(bpy.types.PropertyGroup):
	"""Class to register properties to individual materials, saved with file"""
	status = bpy.props.StringProperty(default="")
	workflow = bpy.props.StringProperty(default="")
	setname = bpy.props.StringProperty(default="")
	size = bpy.props.StringProperty(default="")
	setpath = bpy.props.StringProperty(default="") # used for reloading/ticks
	use_ao = bpy.props.BoolProperty(default=True)
	use_disp = bpy.props.BoolProperty(default=True)
	use_sixteenbit = bpy.props.BoolProperty(default=True)
	use_micro_displacements = bpy.props.BoolProperty(default=False)

# -----------------------------------------------------------------------------
# REGISTER / UNREGISTER
# -----------------------------------------------------------------------------

classes = (
	folderset_list_col,
	PathItem,
	PMC_props,
	PMC_scene_props,
	PMC_matprops,
	PMC_load_materials_from_UIList,
	PMC_load_and_apply_material,
	PMC_load_material_popup,
	PMC_refresh_folder,
	PMC_apply_material,
	PMC_missing_UV_warnings,
	PMC_set_default_path,
	PMC_unset_default_path,
	PMC_remove_unused_materials,
	PMC_preferences
	)

def make_annotations(cls):
	"""Converts class fields to annotations if running with Blender 2.8"""
	if bpy.app.version < (2, 80):
		return cls
	bl_props = {k: v for k, v in cls.__dict__.items() if isinstance(v, tuple)}
	if bl_props:
		if '__annotations__' not in cls.__dict__:
			setattr(cls, '__annotations__', {})
		annotations = cls.__dict__['__annotations__']
		for k, v in bl_props.items():
			annotations[k] = v
			delattr(cls, k)
	return cls

def register():
	"""Register classes, properties, and global icons"""
	register_texture_path()

	for cls in classes:
		make_annotations(cls)
		bpy.utils.register_class(cls)

	bpy.types.WindowManager.pmc_props = bpy.props.PointerProperty(type=PMC_props)
	bpy.types.Material.pmc_matprops = bpy.props.PointerProperty(type=PMC_matprops)
	bpy.types.Scene.pmc_sceneprops = bpy.props.PointerProperty(type=PMC_scene_props)

	# try to load poliigon icon
	try:
		script_path = bpy.path.abspath(os.path.dirname(__file__))
		icons_dir = os.path.join(script_path,'icons')
		custom_icons = bpy.utils.previews.new()
		material_thumbs = bpy.utils.previews.new()
		preview_collections["main"] = custom_icons
		preview_collections["materials"] = material_thumbs
	except Exception as e:
		print("Poliigon: Failed to load custom icons, may be old blender version")
		print("\t"+str(e))
		preview_collections["main"] = ""
		preview_collections["materials"] = ""

	if use_icons:
		logo_path = os.path.join(icons_dir, "poliigon-logo.png")
		nopreview_path = os.path.join(icons_dir, "no-preview-icon.png")
		if os.path.isfile(logo_path):
			custom_icons.load("poliigon_logo", logo_path, 'IMAGE')
		if os.path.isfile(nopreview_path):
			custom_icons.load("no_preview", nopreview_path, 'IMAGE')

	# register the new-file handler, to trigger refresh if non-nill path
	if hasattr(bpy.app.handlers, "load_post"):
		bpy.app.handlers.load_post.append(load_post)

def unregister():
	"""Unregister classes, properties, and global icons"""

	# remove icons
	if use_icons and preview_collections["main"] != "":
		for pcoll in preview_collections.values():
			bpy.utils.previews.remove(pcoll)
		preview_collections.clear()

	if hasattr(bpy.types.WindowManager, "pmc_texture_path"):
		del bpy.types.WindowManager.pmc_texture_path
	del bpy.types.WindowManager.pmc_props
	del bpy.types.Material.pmc_matprops

	if hasattr(bpy.app.handlers, "load_post") and \
			load_post in bpy.app.handlers.load_post:
		bpy.app.handlers.load_post.remove(load_post)

	for cls in reversed(classes):
		bpy.utils.unregister_class(cls)


import cv2

image = cv2.imread("data/Task_1.jpg")
imgeCopy = image.copy()
refPt = []
cropping = False
def click_and_crop(event, x, y, flags, param):
	# grab references to the global variables
	global refPt, cropping
	# if the left mouse button was clicked, record the starting
	# (x, y) coordinates and indicate that cropping is being
	# performed
	if event == cv2.EVENT_LBUTTONDOWN:
		refPt = [(x, y)]
		# print("inittial",refPt)
		cropping = True
	# check to see if the left mouse button was released
	elif event == cv2.EVENT_LBUTTONUP:
		# record the ending (x, y) coordinates and indicate that
		# the cropping operation is finished
		refPt.append((x, y))
		cropping = False
		# draw a rectangle around the region of interest
		cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
		# print(refPt)
		cv2.imwrite("task1Results/Task_1_cropped.jpg",imgeCopy[refPt[0][1]:refPt[1][1],refPt[0][0]:refPt[1][0]])
		cv2.imshow("Window", image)
		cv2.imwrite("task1Results/Task_1_insights.jpg",image)

# Making Window For The Image
cv2.namedWindow("Window")
cv2.imshow("Window",image)

# Adding Mouse CallBack Event
cv2.setMouseCallback("Window",click_and_crop)
# cv2.imwrite()
cv2.waitKey(0)


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
#import seaborn as sns

import statsmodels.api as sm
from scipy import stats

from parameters import parameters

import statsmodels.stats.api as sms

selected_colums_regression = parameters["selected_colums_regression"]

output_variable = parameters["output_variable"]

if output_variable not in selected_colums_regression:
    selected_colums_regression.append(output_variable)
    print("added output variable into selected columns")

# retrieves data
hourly_data = pd.read_csv("data_erling/hourly_data_areas.csv")

date_hour_list = hourly_data["Date"].values.tolist() # e.g., 2020-06-05-7 -> 07:00-08:00 on 5 June 2020
for index, element in enumerate(date_hour_list):
    hour = index % 24
    date_hour_list[index] = element + "-" + str(hour)

# converting month, weekday and week to one-hot encoding
month_one_hot_encoding = False
if "Month" in selected_colums_regression:
    month_one_hot_encoding = True
    selected_colums_regression.remove("Month")  # want as seperate df
weekday_one_hot_encoding = False
if "Weekday" in selected_colums_regression:
    weekday_one_hot_encoding = True
    selected_colums_regression.remove("Weekday")  # want as seperate df
week_one_hot_encoding = False
if "Week" in selected_colums_regression:
    week_one_hot_encoding = True
    selected_colums_regression.remove("Week")  # want as seperate df
hour_one_hot_encoding = False
if "Hour" in selected_colums_regression:
    hour_one_hot_encoding = True
    selected_colums_regression.remove("Hour")  # want as seperate df

lin_reg_data = pd.DataFrame(hourly_data, columns=selected_colums_regression)
lin_reg_data = lin_reg_data.astype(float)

# converting month, weekday and week to one-hot encoding part 2
if month_one_hot_encoding:
    selected_colums_regression.append("Month")  # for documentation
    month_one_hot = pd.get_dummies(hourly_data["Month"], prefix="Month")
    lin_reg_data = pd.concat([lin_reg_data, month_one_hot], axis=1)
    del lin_reg_data['Month_1']
if weekday_one_hot_encoding:
    selected_colums_regression.append("Weekday")  # for documentation
    weekday_one_hot = pd.get_dummies(hourly_data["Weekday"], prefix="Weekday")
    lin_reg_data = pd.concat([lin_reg_data, weekday_one_hot], axis=1)
    del lin_reg_data['Weekday_1']
if week_one_hot_encoding:
    selected_colums_regression.append("Week")  # for documentation
    week_one_hot = pd.get_dummies(hourly_data["Week"], prefix="Week")
    lin_reg_data = pd.concat([lin_reg_data, week_one_hot], axis=1)
    del lin_reg_data['Week_1']
if hour_one_hot_encoding:
    selected_colums_regression.append("Hour")  # for documentation
    week_one_hot = pd.get_dummies(hourly_data["Hour"], prefix="Hour")
    lin_reg_data = pd.concat([lin_reg_data, week_one_hot], axis=1)
    del lin_reg_data['Hour_1']

training_test_split = date_hour_list.index(parameters["test_split"])
training_data_regression = lin_reg_data[0:training_test_split] # 2014-01-01-0 - 2019-12-31-23 # 6 years

# train Ordinary Least Squares model
def make_mlr_with_summary(days, training_data_regression,poly):
    x_sm = training_data_regression[:-24*days]
    y_sm = training_data_regression[output_variable][24*days:]

    polynomial_features= PolynomialFeatures(degree=poly)
    x_sm = polynomial_features.fit_transform(x_sm)

    y_sm = y_sm.reset_index()
    del y_sm["index"]
    X_train = sm.add_constant(x_sm)
    model = sm.OLS(y_sm, X_train)
    result = model.fit()

    print(result.summary())
    # get values of the residuals
    residual = result.resid
    # run tests and get the p values
    print('p value of Jarque-Bera test is: ', stats.jarque_bera(residual)[1])
    print('p value of Shapiro-Wilk test is: ', stats.shapiro(residual)[1])
    print('p value of Kolmogorov-Smirnov test is: ', stats.kstest(residual, 'norm')[1])
    print('p value of Breusch–Pagan test is: ', sms.het_breuschpagan(result.resid, result.model.exog)[1])
    print('p value of White test is: ', sms.het_white(result.resid, result.model.exog)[1])

#make_mlr_with_summary(1,training_data_regression,1)

def make_mlr(days, training_data_regression, output_variable, poly):
    x = training_data_regression[:-24*days]
    y = training_data_regression[output_variable][24*days:]

    polynomial_features= PolynomialFeatures(degree=poly)

    x = polynomial_features.fit_transform(x)

    mlr = LinearRegression()
    mlr.fit(x, y)
    return mlr

mlr_models = []
for i in range(1,31): # develop mlr models for different day horizions (1-31)
    mlr_models.append(make_mlr(i,training_data_regression,output_variable,2))
    #print("Intercept: ", mlr_models[0].intercept_)
    #print("Coefficients:")
    #print(list(zip(training_data_regression, mlr_models[0].coef_)))

def make_forecasts_regression(start_date, number_of_days, lin_reg_data,mlr_models, poly):
    forecast_start = date_hour_list.index(start_date) - 24
    forecast_basis_day = lin_reg_data[forecast_start:forecast_start+24] # day used as basis for forecast

    polynomial_features= PolynomialFeatures(degree=poly)
    forecast_basis_day = polynomial_features.fit_transform(forecast_basis_day)

    predictions = []
    for i in range(number_of_days):
        predictions.extend(mlr_models[i].predict(forecast_basis_day))
    return predictions

#forecasts = make_forecasts_regression('2020-08-02-5',10,lin_reg_data,mlr_models,2)
#print(forecasts)


from .typing import Dict, Optional, List, Generator, Tuple
from contextlib import contextmanager
import sublime
import sublime_plugin

# about 80 chars per line implies maintaining a buffer of about 40kb per window
SERVER_PANEL_MAX_LINES = 500

OUTPUT_PANEL_SETTINGS = {
    "auto_indent": False,
    "draw_indent_guides": False,
    "draw_unicode_white_space": "none",
    "draw_white_space": "none",
    "fold_buttons": True,
    "gutter": True,
    "is_widget": True,
    "line_numbers": False,
    "lsp_active": True,
    "margin": 3,
    "match_brackets": False,
    "rulers": [],
    "scroll_past_end": False,
    "show_definitions": False,
    "tab_size": 4,
    "translate_tabs_to_spaces": False,
    "word_wrap": False
}

class PanelName:
    Diagnostics = "diagnostics"
    References = "references"
    Rename = "rename"
    LanguageServers = "language servers"

@contextmanager
def mutable(view: sublime.View) -> Generator:
    view.set_read_only(False)
    yield
    view.set_read_only(True)

def clear_undo_stack(view: sublime.View) -> None:
    clear_undo_stack = getattr(view, "clear_undo_stack", None)
    if not callable(clear_undo_stack):
        return
    # The clear_undo_stack method cannot be called from within a text command...
    sublime.set_timeout(clear_undo_stack)

class WindowPanelListener(sublime_plugin.EventListener):

    server_log_map = {}  # type: Dict[int, List[Tuple[str, str]]]

    def on_init(self, views: List[sublime.View]) -> None:
        for window in sublime.windows():
            self.server_log_map[window.id()] = []

    def on_new_window(self, window: sublime.Window) -> None:
        self.server_log_map[window.id()] = []

    def on_pre_close_window(self, window: sublime.Window) -> None:
        self.server_log_map.pop(window.id())

    def on_window_command(self, window: sublime.Window, command_name: str, args: Dict) -> None:
        if command_name in ('show_panel', 'hide_panel'):
            sublime.set_timeout(lambda: self.maybe_update_server_panel(window))

    def maybe_update_server_panel(self, window: sublime.Window) -> None:
        if is_server_panel_open(window):
            panel = ensure_server_panel(window)
            if panel:
                update_server_panel(panel, window.id())

def create_output_panel(window: sublime.Window, name: str) -> Optional[sublime.View]:
    panel = window.create_output_panel(name)
    settings = panel.settings()
    for key, value in OUTPUT_PANEL_SETTINGS.items():
        settings.set(key, value)
    return panel

def destroy_output_panels(window: sublime.Window) -> None:
    for field in filter(lambda a: not a.startswith('__'), PanelName.__dict__.keys()):
        panel_name = getattr(PanelName, field)
        panel = window.find_output_panel(panel_name)
        if panel and panel.is_valid():
            panel.settings().set("syntax", "Packages/Text/Plain text.tmLanguage")
            window.destroy_output_panel(panel_name)

def create_panel(window: sublime.Window, name: str, result_file_regex: str, result_line_regex: str,
                 syntax: str) -> Optional[sublime.View]:
    panel = create_output_panel(window, name)
    if not panel:
        return None
    if result_file_regex:
        panel.settings().set("result_file_regex", result_file_regex)
    if result_line_regex:
        panel.settings().set("result_line_regex", result_line_regex)
    panel.assign_syntax(syntax)
    # Call create_output_panel a second time after assigning the above
    # settings, so that it'll be picked up as a result buffer
    # see: Packages/Default/exec.py#L228-L230
    panel = window.create_output_panel(name)
    # All our panels are read-only
    panel.set_read_only(True)
    return panel

def ensure_panel(window: sublime.Window, name: str, result_file_regex: str, result_line_regex: str,
                 syntax: str) -> Optional[sublime.View]:
    return window.find_output_panel(name) or create_panel(window, name, result_file_regex, result_line_regex, syntax)

class LspClearPanelCommand(sublime_plugin.TextCommand):
    """
    A clear_panel command to clear the error panel.
    """
    def run(self, edit: sublime.Edit) -> None:
        with mutable(self.view):
            self.view.erase(edit, sublime.Region(0, self.view.size()))

class LspUpdatePanelCommand(sublime_plugin.TextCommand):
    """
    A update_panel command to update the error panel with new text.
    """

    def run(self, edit: sublime.Edit, characters: Optional[str] = "") -> None:
        # Clear folds
        self.view.unfold(sublime.Region(0, self.view.size()))

        with mutable(self.view):
            self.view.replace(edit, sublime.Region(0, self.view.size()), characters or "")

        # Clear the selection
        selection = self.view.sel()
        selection.clear()
        clear_undo_stack(self.view)

def ensure_server_panel(window: sublime.Window) -> Optional[sublime.View]:
    return ensure_panel(window, PanelName.LanguageServers, "", "", "Packages/LSP/Syntaxes/ServerLog.sublime-syntax")

def is_server_panel_open(window: sublime.Window) -> bool:
    return window.is_valid() and window.active_panel() == "output.{}".format(PanelName.LanguageServers)

def log_server_message(window: sublime.Window, prefix: str, message: str) -> None:
    window_id = window.id()
    if not window.is_valid() or window_id not in WindowPanelListener.server_log_map:
        return
    WindowPanelListener.server_log_map[window_id].append((prefix, message))
    list_len = len(WindowPanelListener.server_log_map[window_id])
    if list_len >= SERVER_PANEL_MAX_LINES:
        # Trim leading items in the list, leaving only the max allowed count.
        del WindowPanelListener.server_log_map[window_id][:list_len - SERVER_PANEL_MAX_LINES]
    panel = ensure_server_panel(window)
    if is_server_panel_open(window) and panel:
        update_server_panel(panel, window_id)

def update_server_panel(panel: sublime.View, window_id: int) -> None:
    panel.run_command("lsp_update_server_panel", {"window_id": window_id})

class LspUpdateServerPanelCommand(sublime_plugin.TextCommand):

    def run(self, edit: sublime.Edit, window_id: int) -> None:
        to_process = WindowPanelListener.server_log_map.get(window_id) or []
        WindowPanelListener.server_log_map[window_id] = []
        with mutable(self.view):
            new_lines = []
            for prefix, message in to_process:
                message = message.replace("\r\n", "\n")  # normalize Windows eol
                new_lines.append("{}: {}\n".format(prefix, message))
            if new_lines:
                self.view.insert(edit, self.view.size(), ''.join(new_lines))
                last_region_end = 0  # Starting from point 0 in the panel ...
                total_lines, _ = self.view.rowcol(self.view.size())
                for _ in range(0, max(0, total_lines - SERVER_PANEL_MAX_LINES)):
                    # ... collect all regions that span an entire line ...
                    region = self.view.full_line(last_region_end)
                    last_region_end = region.b
                erase_region = sublime.Region(0, last_region_end)
                if not erase_region.empty():
                    self.view.erase(edit, erase_region)
        clear_undo_stack(self.view)


from GameBot.server import app
from GameBot.games.game.game import Game
from GameBot.games.game.gamemanager import GameManager#
from GameBot.games.tictactoe.tictactoegame import TicTacToeGame
from flask import request, jsonify, url_for
from flask_cors import cross_origin
from urllib.parse import urljoin
import json

gameMapping = {
    "game": Game,
    "tictactoe": TicTacToeGame
}
gameManager = GameManager() # You have to call /tictactoe/create every time you save.

@app.route('/<game>/setState')
def setState(game):
    gameId = request.values.get("gameId")
    state = request.values.get("state")

    print(f"[debug routes/setState] state is {state}")

    newStateId = gameManager.games.get(gameId).state.addState(json.loads(state))
    print(f"[debug routes/setState] newStateId is {newStateId}")

    return jsonify({"stateId": newStateId})

@app.route('/<game>/getStateUIUrl')
@cross_origin()
def getStateUIUrl(game):
    gameId = request.values.get("gameId")
    stateId = request.values.get("stateId") # Optional, if the client requests it.

    newStateId = gameManager.games.get(gameId).state.lastState

    if stateId:
        newStateId = stateId

    return jsonify({"stateUIUrl": urljoin(request.url_root, url_for("stateUI", game=game, gameId=gameId, stateId=newStateId)) })

@app.route('/<game>/stateUI')
def stateUI(game):
    stateId = request.values.get("stateId") or ""
    gameId = request.values.get("gameId") or ""

    print(f"[debug stateUI]: gameId is {gameId}")

    if gameManager.games.get(gameId):
        return gameManager.games.get(gameId).stateUI(stateId)

    return {"render": False}

@app.route('/<game>/create/')                                   #Creates a game
def create(game):
    gameId = False
    if gameMapping.get(game):                                   #Make sure game exists
        gameId = gameManager.addGame(gameMapping.get(game)())   #Makes a new game and game id

    return jsonify({"gameId": gameId})


from flask_login import UserMixin

class User(UserMixin):
    def __init__(
        self,
        user_id,
        email,
        is_admin,
        name,
        profile_pic,
    ):
        self.id = user_id
        self.email = email
        self.is_admin = is_admin
        self.name = name
        self.profile_pic = profile_pic

    @staticmethod
    def get(user_id):
        from auth.helpers import database

        with database.get_cursor() as cursor:
            cursor.execute(
                'SELECT * FROM Users WHERE id = %s',
                (
                    user_id,
                )
            )
            user = cursor.fetchone()
            if not user:
                return None

            user = User(
                user_id=user['id'],
                email=user['email'],
                is_admin=not not user['is_admin'],
                name=user['name'],
                profile_pic=user['profile_pic'],
            )
            return user

    @staticmethod
    def create(
        user_id,
        email,
        is_admin,
        name,
        profile_pic,
    ):
        from auth.helpers import database

        with database.get_cursor(commit=True) as cursor:
            cursor.execute(
                'INSERT INTO Users (id, email, is_admin, name, profile_pic) VALUES (%s, %s, %s, %s, %s)',
                (
                    user_id,
                    email,
                    is_admin,
                    name,
                    profile_pic,
                ),
            )


import numpy as np
import cv2
from PIL import Image
import yolo as ml

cap = cv2.VideoCapture(0)
while(True): # 从摄像头中读取画面，while表示循环读取画面，也就是一张一张图片形成了一个视频
    ret, image = cap.read() # 设置每一张图片的颜色
    img_color = cv2.cvtColor(image, 0) # 显示窗口
        #cv2.imshow('window', img_color)
    #img_color=cv2.putText(img_color,str(i),(50,200),cv2.FONT_HERSHEY_SIMPLEX,1.2,(255,0,0),5)
    #img_result=ml.detectBinaryImage( Image.fromarray(cv2.cvtColor(img_color,cv2.COLOR_BGR2RGB)))
    #img_show = cv2.cvtColor(np.asarray(img_result),cv2.COLOR_RGB2BGR)
    img_result=ml.detection(cv2.cvtColor(img_color,cv2.COLOR_BGR2RGB))
    cv2.imshow('window', img_result) # 如果按下键盘上的 Q 就关闭窗口
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break;
cap.release()
cv2.destroyAllWindows()


class Account:

   def __init__(self,acc_no,name,balance):
      self.acc_no=acc_no
      self.name=name
      self.balance=balance

   def deposit_money(self,dep_amount):
      self.balance+=dep_amount
      return self.balance
   def withdraw_money(self,withdraw_amount):
      self.balance-=withdraw_amount
      if(self.balance>=1000):
         return self.balance
      return 0

if __name__=="__main__":

   acc_no = int(input("Enter A/C No: "))
   name = input("Enter Name Of A/C Holder: ")
   balance = int(input("Balance: "))
   account = Account(acc_no,name,balance)

   dep_or_withdraw=input("d or w")
   if(dep_or_withdraw=='d'):
      dep_amount=int(input())
      print(account.deposit_money(dep_amount))
   else:
      withdraw_amount=int(input())
      withdrawl=account.withdraw_money(withdraw_amount)
      if(withdrawl==0):print("Insufficient Funds")
      else:print(withdrawl)


from Crypto.Cipher import AES
from Crypto import Random
import binascii
key='1234567890!@#$%^'
iv= Random.new().read(16)

cipher1=AES.new(key,AES.MODE_CFB,iv)
encrypt_msg=iv+cipher1.encrypt('我是明文')
print('加密后的值为：',binascii.b2a_hex(encrypt_msg))

cipher2=AES.new(key,AES.MODE_CFB,iv)
decrypt_msg=cipher2.decrypt(encrypt_msg[16:])
print('解密后的值为：',decrypt_msg.decode('utf-8'))


import pygame

from BrickBreaker.Scenes.scene import Scene
from BrickBreaker.Shared import *

class PlayingGameScene(Scene):

    def __init__(self, game):
        super().__init__(game)

    def render(self):
        super().render()

        game = self.get_game()
        level = game.get_level()
        pad = game.get_pad()
        balls = game.get_balls()

        if level.get_amount_of_bricks_left() <= 0:
            for ball in balls:
                ball.set_motion(0)
                ball.update_position()

            level.load_next_level()

        if game.get_lives() <= 0:
            game.play_sound(GameConstants.SOUND_GAME_OVER)
            game.change_scene(GameConstants.GAME_OVER_SCENE)

        for ball in balls:
            for ball2 in balls:
                if ball != ball2 and ball.intersects(ball2):
                    ball.change_direction(ball2)

            for brick in game.get_level().get_bricks():
                if not brick.is_destroyed() and ball.intersects(brick):
                    game.play_sound(brick.get_hit_sound())
                    brick.hit()
                    level.brick_hit()
                    if brick.get_hit_sound() == 1:
                        game.increment_bonus()
                    game.increase_score(brick.get_hit_points())
                    ball.change_direction(brick)
                    break

            if ball.intersects(pad):
                game.play_sound(GameConstants.SOUND_HIT_WALL_OR_PAD)
                ball.change_direction(pad)

            ball.update_position()

            if ball.is_ball_dead():
                if len(balls) <= 1:
                    ball.set_motion(0)
                    game.reduce_life_by_one()
                    game.reset_bonus()
                    game.reset_pad()
                else:
                    balls.remove(ball)

            game.screen.blit(ball.get_image(), ball.get_position())

        for brick in game.get_level().get_bricks():
            if not brick.is_destroyed():
                game.screen.blit(brick.get_image(), brick.get_position())

        if pad.get_keyboard_status():

            pad.set_position((pad.get_position()[0], pad.get_position()[1]))
            if pad.right_is_pressed:
                pad.set_position((pad.get_position()[0] + 15, pad.get_position()[1]))
            if pad.left_is_pressed:
                pad.set_position((pad.get_position()[0] - 15, pad.get_position()[1]))

        if pad.get_mouse_status():
            pad.set_position((pygame.mouse.get_pos()[0], pad.get_position()[1]))

        game.screen.blit(pad.get_image(), pad.get_position())

        self.clear_text()

        self.add_text("Your score: " + str(game.get_score()), x=0, y=GameConstants.SCREEN_SIZE[1] - 60, size=30)

        self.add_text("Lives: " + str(game.get_lives()), x=0, y=GameConstants.SCREEN_SIZE[1] - 30, size=30)

        self.add_text(f"Bonus: x{str(game.get_bonus())}", x=GameConstants.SCREEN_SIZE[0] - 100,
                      y=GameConstants.SCREEN_SIZE[1] - 30, size=30)

    def handle_events(self, events):
        super().handle_events(events)
        game = self.get_game()
        pad = game.get_pad()

        for event in events:
            if event.type == pygame.QUIT:
                exit()

            if event.type == pygame.MOUSEBUTTONDOWN:
                for ball in self.get_game().get_balls()[-1:]:
                    ball.set_motion(1)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    for ball in self.get_game().get_balls()[-1:]:
                        ball.set_motion(1)
                if event.key == pygame.K_ESCAPE:
                    self.get_game().change_scene(GameConstants.MAIN_MENU_SCENE)

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    pad.left_pressed(True)
                if event.key == pygame.K_RIGHT:
                    pad.right_pressed(True)

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT:
                    pad.left_pressed(False)
                if event.key == pygame.K_RIGHT:
                    pad.right_pressed(False)