# Databricks notebook source
# MAGIC %run ./imports_variables

# COMMAND ----------

dbutils.widgets.text('count', '')
count = int(dbutils.widgets.get('count'))

# COMMAND ----------

import csv
import uuid
from random import *
import time
from pathlib import Path
from datetime import datetime

# count = 0
Path(event_source_path).mkdir(parents=True, exist_ok=True)

row_list = [ ["id", "amount", "ts"],
               [randint(1,7), randint(1,20), datetime.now()],
               [randint(8,20), randint(1,20), datetime.now()],
               [randint(1,7), randint(1,20), datetime.now()],
               [randint(1,7), randint(1,20), 999],
               [randint(1,7), randint(1,20)]
             ]
file_location = f'{event_source_path}/file_{count}.csv'

with open(file_location, 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(row_list)
    file.close()

count += 1
dbutils.fs.mv(f'file:{file_location}', f'dbfs:{file_location}')
time.sleep(5)
print(f'New CSV file created at dbfs:{file_location}. Contents:')

with open(f'/dbfs{file_location}', 'r') as file:
    reader = csv.reader(file, delimiter=' ')
    for row in reader:
      print(', '.join(row))
    file.close()


from flask import Flask, render_template, url_for, redirect, request
from datetime import datetime
from auth import *
from vk_api import VkApi
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
app = Flask(__name__)

vk_session = VkApi(token=TOKEN)
@app.route('/vk_stat/<int:group_id>')
def vk_stat(group_id):
    vk = vk_session.get_api()
    activity = {}
    ages = {}
    cities = []
    for i in vk.stats.get(group_id=group_id, app_id=7403595, extended=True, intervals_count=10):
        if 'activity' in i:
            for j in i['activity']:
                if j in activity:
                    activity[j] += 1
                else:
                    activity[j] = 1
        if i['reach']['reach'] != 0:
            for j in i['reach']['age']:
                if j['value'] not in ages:
                    ages[j['value']] = j['count']
                else:
                    ages[j['value']] += j['count']
            for j in i['reach']['cities']:
                if j['name'] not in cities:
                    cities.append(j['name'])
    return render_template('vk_stat.html', title='Vk Statistics', activity=activity, ages=ages, cities=cities)

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


from random import randint

n = randint(0, 100)
i = 0

print("Try to guess a number in the range of 1 to 100. You have 10 attempts.")

while True:
    a = int(input(f"Enter the number: "))
    if a == n:
        print(f'\nYou win! {a} is a secret number.')
        break
    if a < n:
        print('The mystery number is bigger than')
    else:
        print('The number is less than')
    i += 1

    if i == 10:
        print(f'You have lost. The number you have guessed {n}')
        break


import base64
import os
import logging
from krita import *
from krita_stable_diffusion.interface.interfaces.vertical_interface import VerticalInterface
from krita_stable_diffusion.settings import APPLICATION_ID
from krita_stable_diffusion.settings import DEFAULT_MODEL

class Base:
    """
    Extend this class to create a new tab for use in an interface.
    :param name: The name of the tab
    :param settings_key: The key of the settings to be used
    :param widget: The widget to add to the layout
    :param layout: The layout to add the widget to
    :param default_setting_values: The default values of the settings object
    """
    inserting_image = False
    krita_instance = None
    display_name = ""
    name = ""
    settings_key = ""
    widget = None
    layout = None
    default_setting_values = {}
    log_widget = None
    image_insert_timer = None
    progressbar_update_timer = None

    @property
    def color_mode(self):
        return self.config.value("color_mode", "RGBA")

    @property
    def resolution(self):
        return float(self.config.value("resolution", 300.0))

    @property
    def width(self):
        return int(self.config.value("width", 512))

    @property
    def height(self):
        return int(self.config.value("height", 512))

    @property
    def active_document(self):
        return self.krita.activeDocument()

    @property
    def active_node(self):
        return self.active_document.activeNode()

    @property
    def selection(self):
        return self.active_document.selection()

    @property
    def x(self):
        return 0 if self.selection is None else self.selection.x()

    @property
    def y(self):
        return 0 if self.selection is None else self.selection.y()

    @property
    def krita(self):
        if not self.krita_instance:
            self.krita_instance = Krita.instance()
        return self.krita_instance

    def string_to_binary(self, st):
        return ''.join(format(ord(i), '08b') for i in str(st))

    def build_prompt(self, data, image_type=None, style=None):
        if image_type and style:
            data["prompt"] = " ".join([
                f"{style} {image_type}",
                data["prompt"]
            ])
        return data

    def get_active_layer_binary(self, pos_x, pos_y):
        """
        Saves image to path
        :param path:
        :param is_mask:
        :return:
        """
        logging.info(f"saving layer...")
        item = self.active_document.activeNode()
        pixels = item.pixelData(pos_x, pos_y, self.width, self.height)
        image_data = QImage(
            pixels,
            self.width,
            self.height,
            QImage.Format_RGB32
        )
        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        buffer.open(QIODevice.WriteOnly)
        image_data.save(buffer, "PNG", -1)
        return bytes(byte_array)

    def get_mask(self, pos_x, pos_y):
        """
        Get the mask from the top mask layer
        :return: mask as bytes
        """
        mask = None
        node = self.active_document.activeNode()
        childNodes = node.childNodes()
        for childNode in childNodes:
            if childNode.type() == "transparencymask":
                mask = childNode
                break
        if mask is None:
            return None
        pixels = mask.pixelData(pos_x, pos_y, self.width, self.height)
        image_data = QImage(
            pixels,
            self.width,
            self.height,
            QImage.Format_Indexed8
        )

        image_data.invertPixels()

        byte_array = QByteArray()
        buffer = QBuffer(byte_array)
        buffer.open(QIODevice.WriteOnly)
        image_data.save(buffer, "PNG", -1)
        return bytes(byte_array)

    def handle_outpaint(self, data):
        """
        Get the pixels from the active layer based on the location of
        outpaint layer. Also create a mask based on the overlap.
        :param data:
        :return:
        """

        childNodes = self.active_document.topLevelNodes()
        for childNode in childNodes:
            name = childNode.name()
            # get layer named outpaint
            if name == "outpaint":
                node = childNode
                pos_x = node.position().x()
                pos_y = node.position().y()

                # select the pixels in the active layer
                item = self.active_document.activeNode()
                pixels = item.pixelData(pos_x, pos_y, self.width, self.height)

                # # create a QByteArray containing 512 * 512 * 4 bytes
                # # (4 bytes per pixel) - white pixels
                mask_pixels = QByteArray(b'\xff' * (self.width * self.height * 4))

                image_data = QImage(
                    pixels,
                    self.width,
                    self.height,
                    QImage.Format_ARGB32
                )
                byte_array = QByteArray()
                buffer = QBuffer(byte_array)
                buffer.open(QIODevice.WriteOnly)
                image_data.save(buffer, "PNG", -1)

                mask_image_data = QImage(
                    mask_pixels,
                    self.width,
                    self.height,
                    QImage.Format_RGB32
                )

                # iterate over the pixels in image_data
                # and set the mask_pixels pixels to black if the pixel is not transparent
                for x in range(self.width):
                    for y in range(self.height):
                        pixel = image_data.pixel(x, y)
                        if pixel != 0:
                            mask_image_data.setPixel(x, y, 0)

                mask_byte_array = QByteArray()
                mask_buffer = QBuffer(mask_byte_array)
                mask_buffer.open(QIODevice.WriteOnly)
                mask_image_data.save(mask_buffer, "PNG", -1)

                data["pixels"] = base64.b64encode(bytes(byte_array)).decode("utf-8")
                data["mask"] = base64.b64encode(bytes(mask_byte_array)).decode("utf-8")
                data["pos_x"] = pos_x
                data["pos_y"] = pos_y
        return data

    def handle_inpaint(self, data):
        """
        Get the pixels from the active layer and mask from its transparency mask
        :param data:
        :return:
        """
        pos_x = 0
        pos_y = 0
        pixels = base64.b64encode(
            self.get_active_layer_binary(pos_x, pos_y)
        ).decode("utf-8")

        # get mask from top mask layer
        mask = self.get_mask(pos_x, pos_y)
        if mask:
            data["mask"] = base64.b64encode(mask).decode("utf-8")
        else:
            data["mask"] = mask
        data["pixels"] = pixels
        return data

    def handle_img2img(self, data):
        """
        Get the pixels from the active layer.
        :param data:
        :return:
        """
        pos_x = 0
        pos_y = 0
        pixels = base64.b64encode(
            self.get_active_layer_binary(pos_x, pos_y)
        ).decode("utf-8")
        data["pixels"] = pixels
        return data

    def handle_button_press(self, request_type, **kwargs):
        """
        Callback for the generate button.
        :param _element: passed by the button but not used
        :return: None, sends request to stable diffusion
        """
        data = {}
        for k, v in self.default_setting_values.items():
            v = self.config.value(k, v)
            data[k] = v
        self.update_progressbar(request_type, 0, 0)

        # display status label
        Application.status_label.setText(
            "Loading (first load will take a while)"
        )

        # add config options to request data
        data = self.prep_config_options(request_type, data)

        # build the prompt based on request data
        data = self.build_prompt(
            data,
            kwargs.get("image_type", None),
            kwargs.get("style", None)
        )

        data["pos_x"] = 0
        data["pos_y"] = 0
        data["model_base_path"] = self.config.value("model_base_path", "")

        # handle request types that require image data to be sent
        if request_type == "outpaint":
            data = self.handle_outpaint(data)
        elif request_type in ["inpaint"]:
            data = self.handle_inpaint(data)
        elif request_type == "img2img":
            data = self.handle_img2img(data)

        # if there is no self.active_document, create one
        if not self.active_document:
            document = self.krita.createDocument(
                self.width,
                self.height,
                "StableDiffusion",
                self.color_mode,
                "U8",
                "",
                self.resolution
            )
            self.krita.activeWindow().addView(document)

            # activate the document
            self.krita.activeDocument().setActiveNode(
                self.krita.activeDocument().rootNode()
            )

        # send request to the server
        self.send(data, request_type)

    def update_progressbar(self, reqtype, max, val):
        try:
            progress_bar = None
            if reqtype == "txt2img":
                progress_bar = Application.txt2img_progress_bar
            elif reqtype == "img2img":
                progress_bar = Application.img2img_progress_bar
            elif reqtype == "inpaint":
                progress_bar = Application.inpaint_progress_bar
            elif reqtype == "outpaint":
                progress_bar = Application.outpaint_progress_bar
            if progress_bar:
                if progress_bar.element.maximum() != max:
                    progress_bar.setRange(0, max)
                if max != 0:
                    progress_bar.setvalue(val, max)
        except Exception as e:
            pass

    def update_image_insert(self):
        if len(Application.image_queue) > 0 and not self.inserting_image:
            self.inserting_image = True
            image = Application.image_queue.pop(0)
            self.insert_image(image)

    def progressbar_timed_update(self):
        self.progressbar_update_timer = QTimer()
        self.progressbar_update_timer.timeout.connect(lambda: self.update_progressbar(
            Application.cur_reqtype,
            Application.step_total,
            Application.cur_step
        ))
        self.progressbar_update_timer.start(100)

    def image_insert_timed_update(self):
        self.image_insert_timer = QTimer()
        self.image_insert_timer.timeout.connect(self.update_image_insert)
        self.image_insert_timer.start(100)

    def byte_array(self, image):
        """
        Convert QImage to QByteArray
        :param image:
        :return: QByteArray
        """
        bits = image.bits()
        bits.setsize(image.byteCount())
        return QByteArray(bits.asstring())

    def create_layer(self, name, visible=True, type="paintLayer"):
        """
        Creates a new layer in the active document
        :param name:
        :param type:
        :return: a reference to the new layer
        """
        document = self.active_document.createNode(name, type)
        self.root_node.addChildNode(document, None)
        return document

    def add_image_from_bytes(
            self,
            reqype,
            name,
            image_bytes,
            pos_x=0,
            pos_y=0,
    ):
        """
        Adds image from bytes
        :param name:
        :param image_bytes:
        :return:
        """
        image = QImage()
        image.loadFromData(image_bytes)

        if reqype == "outpaint":
            # get active layer
            layer = self.active_document.activeNode()
        else:
            layer = self.create_layer(name)
        layer.setPixelData(self.byte_array(image), pos_x, pos_y, self.width, self.height)

        # the layer is not visible until we refresh the projection
        self.active_document.refreshProjection()

        return layer

    @property
    def root_node(self):
        doc = self.krita.activeDocument()
        if not doc:
            raise Exception("NO ACTIVE DOCUMENT")
        try:
            root = doc.rootNode()
        except RuntimeError:
            print("runtime error")
            # check if doc has been deleted
            if not doc:
                print("NO ACTIVE DOCUMENT")
            # rootNode has been deleted, fix it
            doc.setRootNode(doc.createNode("root", "paintLayer"))
            root = doc.rootNode()
        return root

    def insert_image(self, image_response):
        """
        Insert an image into the document
        :param image: The image to insert
        :return: None
        """
        image = image_response["image"]
        reqtype = image_response["reqtype"]
        pos_x = image_response["pos_x"]
        pos_y = image_response["pos_y"]
        # convert base64 image to bytes+
        image_bytes = base64.b64decode(image)
        total_layers = len(self.root_node.childNodes()) + 1
        self.add_image_from_bytes(
            reqtype,
            f"Layer {total_layers}",
            image_bytes,
            pos_x,
            pos_y
        )
        self.inserting_image = False

    def send(self, options, request_type):
        """
        Send request to stable diffusion
        :param options: The options to send
        :param request_type: The type of request to send
        :return: None
        """
        Application.stablediffusion.client.message = {
            "action": request_type,
            "options": options,
        }

    message_log = []

    def log_message(self, message, level="info"):
        """
        Log a message to the log widget
        :param message: The message to log
        :param level: The level of the message
        :return: None
        """
        self.message_log.append(f"{level.upper()} {message}")
        if self.log_widget:
            self.log_widget.widget.setPlaceholderText(
                "\n".join(self.message_log)
            )

    def tab(self):
        return self.widget, self.display_name

    def prep_config_options(self, request_type, data):
        # add config options
        do_nsfw_filter = self.config.value("do_nsfw_filter", True)
        do_watermark = self.config.value("do_watermark", True)
        data["do_nsfw_filter"] = False if do_nsfw_filter == 0 else True
        data["do_watermark"] = False if do_watermark == 0 else True

        available_models = None
        model_version = self.config.value(f"{request_type}_model_version", "v1")
        data["version"] = model_version
        if model_version == "v1":
            available_models = Application.available_models_v1
        elif model_version == "v2":
            available_models = Application.available_models_v2
        elif model_version == "v1 (community)":
            available_models = Application.available_models_custom_v1
        else:
            available_models = Application.available_models_custom_v2

        data["model_path"] = self.config.value("model_path", "")

        if available_models:
            model_name = self.config.value(f"{request_type}_model", 0)
            for index in range(len(available_models)):
                available_name = available_models[index]["name"]
                available_path = available_models[index]["path"]
                if available_name == model_name:
                    data["model_path"] = available_path
                    data[f"{request_type}_model"] = os.path.join(
                        available_path
                    )
                    break
        else:
            data["model"] = DEFAULT_MODEL

        self.config.setValue("log", Application.stablediffusion.log)
        return data

    def initialize_settings(self):
        """
        Create tab specific settings
        :return:
        """
        self.settings_key = f"ksd_{self.name}_settings"
        Application.__setattr__(self.settings_key, QSettings(
            QSettings.IniFormat,
            QSettings.UserScope,
            "krita",
            APPLICATION_ID
        ))
        self.config = Application.__getattribute__(self.settings_key)

    def reset_default_values(self):
        # set default values
        for k, v in self.default_setting_values.items():
            self.config.setValue(k, v)

    def initialize_interfaces(self, interfaces):
        if len(interfaces) == 0:
            return
        self.layout = VerticalInterface(interfaces=interfaces)
        self.widget = QWidget()
        self.widget.setLayout(self.layout)

    def __init__(self, interfaces):
        Application.__setattr__("update_progressbar", self.update_progressbar)
        Application.__setattr__("connected_to_sd", False)
        #Application.__setattr__("log_message", self.send)
        Application.__setattr__("app", self)
        # get steps from config
        self.initialize_settings()
        Application.__setattr__("cur_reqtype", None)
        Application.__setattr__("step_total", 0)
        Application.__setattr__("cur_step", 0)
        Application.__setattr__("image_queue", [])
        self.initialize_interfaces(interfaces)
        self.progressbar_timed_update()
        self.image_insert_timed_update()


"""
Additional methods for the Building class.
Used for building energy rating (BER)
"""

class Mixin:

    def check_apartment_position(self):
        """ Check if the apartments are "top", "middle" or "bottom" """
        # check apartment position
        for apartment_obj in self.apartment_dict.values():
            apartment_obj.check_position(self.num_floor)

    def rate_building(self):
        """ Rate buildings according to the 5280 israeli standard  """

        # Rate each building individually
        for apartment_obj in self.apartment_dict.values():
            if apartment_obj.is_core == False:
                apartment_obj.rate_apartment(climate_zone_building=self.climate_zone)

        # Make the average of the grade of apartment according to the 5280
        for apartment_obj in self.apartment_dict.values():
            if apartment_obj.is_core == False:
                self.grade_value += apartment_obj.grade_value * apartment_obj.area / self.apartment_area

        # Give the final rating (in letter) according to the grade
        if self.grade_value < 0:
            self.rating = "F"
        elif self.grade_value < 1:
            self.rating = "E"
        elif self.grade_value < 2:
            self.rating = "D"
        elif self.grade_value < 3:
            self.rating = "C"
        elif self.grade_value < 4:
            self.rating = "B"
        elif self.grade_value < 5:
            self.rating = "A"
        else:
            self.rating = "A+"


"""
최소 대금
https://www.codeup.kr/problem.php?id=2001

time spent : 10min
"""

pasta = []
for _ in range(3):
    a = int(input())
    pasta.append(a)

juice = []
for _ in range(2):
    b = int(input())
    juice.append(b)
result = (min(pasta) + min(juice))*1.1
print("%.1f" %result)


import openai
import streamlit as st
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import QAEmbeddingsDemo

openai.api_key = st.secrets["OPENAI_API_KEY"]
openai_embeddings_model = st.secrets["OPENAI_EMBEDDINGS_MODEL"]
db_url = st.secrets["POSTGRES_DATABASE_URL"]

st.set_page_config(page_title="Storing QA Embeddings Demo")

st.info(
    f"Using {openai_embeddings_model} model to change modify OPENAI_EMBEDDINGS_MODEL in .streamlit/secrets.toml file",
    icon="ℹ",
)

engine = create_engine(db_url)
Session = sessionmaker(bind=engine)
session = Session()

def generate_embeddings(prompt):
    return openai.Embedding.create(model=openai_embeddings_model, input=prompt)

default_question = """\
What's the color of the sky?
"""

default_answer = """\
The sky is blue.
"""

try:
    with st.form("storing_qa_embeddings_form"):
        question = st.text_area("Enter question:", value=default_question, height=100)
        answer = st.text_area("Enter answer:", value=default_answer, height=100)

        submitted = st.form_submit_button("Generate Embeddings and Save")
        if submitted:
            question = question.strip()
            answer = answer.strip()
            embeddings = generate_embeddings(question)
            embedding = embeddings["data"][0]["embedding"]
            new_record = QAEmbeddingsDemo(
                answer=answer, question=question, question_embedding_vector=embedding
            )
            session.add(new_record)
            session.commit()
            st.success("Successfully saved embeddings")
except Exception as e:
    session.rollback()
    st.error(f"Failed to save embeddings: {e}")
finally:
    session.close()


# https://www.acmicpc.net/problem/1390
# days[] 가 idx 날에 문제 해결하면 1로 저장시킴
# 점수가 큰 순서대로 정렬한뒤에 포문돌려서 넣는건데
#  마감일 순서대로 -1씩 빼면서 해결 안된 날이 있으면 그 날 해결하고 이미 다른 과제를 하는 거면 그 전날을 살펴서 빈 날에 과제를 한다.
# 이렇게 하면 점수가 큰 순서대로 진행하고 (1차 포문)
# 각 과제별로 마감일의 역순으로 빈 날에 과제를 해결할 수 있다.

n = int(input())
graph = []
for _ in range(n):
  graph.append(list(map(int, input().split())))

# 점수가 큰 순서대로 정렬
print(graph)
graph.sort(key=lambda x:x[1], reverse=True)
print(graph)

score = 0
days = [0]*1001
for i in graph:
  for j in range(i[0], 0, -1): #과제별로 남은일수 for문 ex. 3일 남았으면 3, 2, 1로 포문을 돌린다. 그래서 days[3]에 해당 위치가 0이면 과제를 해결하고(3일차에 과제를 푼다) 아니면 days[2], 즉 2일차에 과제를 푸는 식으로 줄여간다.
    # print('i,j:', i,j)
    if days[j] == 0: # 과제 해결 안했으면 해결
      days[j] = 1
      score += i[1]
      # print('jjjj:',j)
      break

print(score)


from typing import TYPE_CHECKING

from ...file_utils import (
    _BaseLazyModule,
    is_tokenizers_available,
    is_torch_available,
)

_import_structure = {
    "configuration_dkplm": ["DkplmConfig"],
    "tokenization_dkplm": ["BasicTokenizer", "DkplmTokenizer", "WordpieceTokenizer"],
}

if is_tokenizers_available():
    _import_structure["tokenization_dkplm_fast"] = ["DkplmTokenizerFast"]

if is_torch_available():
    _import_structure["modeling_dkplm"] = [
        "DKPLM_PRETRAINED_MODEL_ARCHIVE_LIST",
        "DkplmForMaskedLM",
        "DkplmForMultipleChoice",
        "DkplmForNextSentencePrediction",
        "DkplmForPreTraining",
        "DkplmForQuestionAnswering",
        "DkplmForSequenceClassification",
        "DkplmForTokenClassification",
        "DkplmLayer",
        "DkplmLMHeadModel",
        "DkplmModel",
        "DkplmPreTrainedModel",
        # "load_tf_weights_in_dkplm",
    ]
if TYPE_CHECKING:
    # from .configuration_dkplm import DKPLM_PRETRAINED_CONFIG_ARCHIVE_MAP, DkplmConfig
    from .configuration_dkplm import DkplmConfig
    from .tokenization_dkplm import BasicTokenizer, DkplmTokenizer, WordpieceTokenizer

    if is_tokenizers_available():
        from .tokenization_dkplm_fast import DkplmTokenizerFast

    if is_torch_available():
        from .modeling_dkplm import (
            # DKPLM_PRETRAINED_MODEL_ARCHIVE_LIST,
            DkplmForMaskedLM,
            DkplmForMultipleChoice,
            DkplmForNextSentencePrediction,
            DkplmForPreTraining,
            DkplmForQuestionAnswering,
            DkplmForSequenceClassification,
            DkplmForTokenClassification,
            DkplmLayer,
            DkplmLMHeadModel,
            DkplmModel,
            DkplmPreTrainedModel,
            # load_tf_weights_in_dkplm,
        )
else:
    import importlib
    import os
    import sys

    class _LazyModule(_BaseLazyModule):
        """
        Module class that surfaces all objects but only performs associated imports when the objects are requested.
        """

        __file__ = globals()["__file__"]
        __path__ = [os.path.dirname(__file__)]

        def _get_module(self, module_name: str):
            return importlib.import_module("." + module_name, self.__name__)

    sys.modules[__name__] = _LazyModule(__name__, _import_structure)


import numpy as np

def rle_encode(arr):
    if len(arr) == 0:
        return [], [], []

    x = np.copy(arr)
    first_dismatch = np.array(x[1:] != x[:-1])
    distmatch_positions = np.append(np.where(first_dismatch), len(x)-1)
    rle = np.diff(np.append(-1, distmatch_positions))
    values = [x[i] for i in np.cumsum(np.append(0, rle))[:-1]]
    return rle, values

def hv_rle(img, axis=1):
    '''
    img: binary image
    axis: 0 for rows, 1 for cols
    '''
    rle, values = [], []

    if axis == 1:
        for i in range(img.shape[1]):
            col_rle, col_values = rle_encode(img[:, i])
            rle.append(col_rle)
            values.append(col_values)
    else:
        for i in range(img.shape[0]):
            row_rle, row_values = rle_encode(img[i])
            rle.append(row_rle)
            values.append(row_values)

    return rle, values

def rle_decode(starts, lengths, values):
    starts, lengths, values = map(np.asarray, (starts, lengths, values))
    ends = starts + lengths
    n = ends[-1]

    x = np.full(n, np.nan)
    for lo, hi, val in zip(starts, ends, values):
        x[lo:hi] = val
    return x

def hv_decode(rle, values, output_shape, axis=1):
    starts = [[int(np.sum(arr[:i])) for i in range(len(arr))] for arr in rle]

    decoded = np.zeros(output_shape, dtype=np.int32)
    if axis == 1:
        for i in range(decoded.shape[1]):
            decoded[:, i] = rle_decode(starts[i], rle[i], values[i])
    else:
        for i in range(decoded.shape[0]):
            decoded[i] = rle_decode(starts[i], rle[i], values[i])

    return decoded

def calculate_pair_sum(arr):
    if len(arr) == 1:
        return list(arr)
    else:
        res = [arr[i] + arr[i + 1] for i in range(0, len(arr) - 1, 2)]
        if len(arr) % 2 == 1:
            res.append(arr[-2] + arr[-1])
        return res

def get_most_common(rle):
    pair_sum = [calculate_pair_sum(col) for col in rle]

    flattened = []
    for col in pair_sum:
        flattened += col

    most_common = np.argmax(np.bincount(flattened))
    return most_common

def most_common_bw_pattern(arr, most_common):
    if len(arr) == 1:
        # print("Empty")
        return []
    else:
        res = [(arr[i], arr[i + 1]) for i in range(0, len(arr) - 1, 2)
               if arr[i] + arr[i + 1] == most_common]

        if len(arr) % 2 == 1 and arr[-2] + arr[-1] == most_common:
            res.append((arr[-2], arr[-1]))
        # print(res)
        return res


from os import getenv

from dotenv import load_dotenv

load_dotenv()

API_ID = int(getenv("API_ID"))
API_HASH = getenv("API_HASH")

TOKEN = getenv("TOKEN")
MONGO_DB_URL = getenv("MONGO_DB_URL", None)

OWNER_ID = int(getenv("OWNER_ID", 5938660179))
SUPPORT_CHAT = getenv("SUPPORT_CHAT", "https://t.me/FallenAssociation")

LOGGER_ID = getenv("LOGGER_ID", "-1001819078701")
DEV_USERS = set(int(x) for x in getenv("DEV_USERS", "").split())


import copy
from math import comb
from tkinter import *
import numpy as np
root = Tk()
root.geometry('800x660+1+1')
root.config(bg="#0f0f0f")
root.title("Геометрическое моделирование")
canv = Canvas(bg='white')
canv.pack(fill=BOTH,expand=1)
points = []
def click(event):
    print("X:" , event.x , "Y:", event.y)
    canv.create_oval(event.x, event.y, event.x+6, event.y+6, width=0, fill='red')
    points.append([event.x, event.y])

def clear():
    canv.delete('all')
    points.clear()

def lagrange():
    # x = np.array([0, 1, 2, 3, 4])
    # y = np.array([0, -3, 0, 0, 0])
    x = []
    y = []
    for i in range(len(points)):
        x.append(points[i][0])
        y.append(points[i][1])
    x = np.array(x)
    y = np.array(y)

    def lagrange_poli(x, y, t):
        p = 0
        for j in range(len(y)):
            p1 = 1
            p2 = 1
            for i in range(len(x)):
                if i == j:
                    p1 = p1 * 1
                    p2 = p2 * 1
                else:
                    p1 = p1 * (t - x[i])
                    p2 = p2 * (x[j] - x[i])
            p = p + y[j] * p1 / p2
        return p

    x_solve = np.linspace(np.min(x), np.max(x), 100)
    y_solve = [lagrange_poli(x, y, i) for i in x_solve]

    for i in range(len(y_solve)):
        if i != len(x_solve) - 1:
            canv.create_line(x_solve[i], y_solve[i], x_solve[i + 1], y_solve[i + 1])
def beze():
    def beze_poly(i, n, t):
        return comb(n, i) * (t ** i) * (1 - t) ** (n - i)

    def beze_curve(points, nTimes=1000):
        nPoints = len(points)
        xPoints = np.array([p[0] for p in points])
        yPoints = np.array([p[1] for p in points])

        t = np.linspace(0.0, 1.0, nTimes)

        polynomial_array = np.array([beze_poly(i, nPoints - 1, t) for i in range(0, nPoints)])

        xvals = np.dot(xPoints, polynomial_array)
        yvals = np.dot(yPoints, polynomial_array)

        return xvals, yvals

    xvals, yvals = beze_curve(points, nTimes=1000)
    for i in range(len(xvals)):
        if i != len(xvals) -1:
            canv.create_line(xvals[i],yvals[i],xvals[i+1],yvals[i+1])

def ermit():
    dt = 0.02
    X = []
    Y = []
    # Input.
    string_xv = list(str(xeditv.get()).split(" "))
    int_xv = [int(i) for i in string_xv]
    xpointsv = np.array(int_xv)

    string_yv = list(str(yeditv.get()).split(" "))
    int_yv = [int(i) for i in string_yv]
    ypointsv = np.array(int_yv)
    n = 0
    lev = []
    l1v = []
    while n < len(xpointsv):
        l1v.append(xpointsv[n])
        l1v.append(ypointsv[n])
        l2v = copy.deepcopy(l1v)
        lev.append(l2v)
        l1v.clear()
        n += 1
    vectors = lev
    for i in range(len(points) - 1):
        t = 0
        while t <= 1:
            if i != len(points) - 1:
                t += dt
                x = points[i][0] * (2 * t ** 3 - 3 * t ** 2 + 1) + points[i + 1][0] * (-2 * t ** 3 + 3 * t ** 2) + \
                    (vectors[i][0]-points[i][0]) * (
                            t ** 3 - 2 * t ** 2 + t) + (vectors[i + 1][0]-points[i + 1][0]) * (t ** 3 - t ** 2)
                X.append(x)
                y = points[i][1] * (2 * t ** 3 - 3 * t ** 2 + 1) + points[i + 1][1] * (-2 * t ** 3 + 3 * t ** 2) + \
                    (vectors[i][1]-points[i][1]) * (
                            t ** 3 - 2 * t ** 2 + t) + (vectors[i + 1][1]-points[i + 1][1]) * (t ** 3 - t ** 2)
                Y.append(y)
            if i == len(points) - 2:
                t += dt
                x = points[i][0] * (2 * t ** 3 - 3 * t ** 2 + 1) + points[-1][0] * (-2 * t ** 3 + 3 * t ** 2) + \
                    (vectors[i][0]-points[i][0]) * (
                            t ** 3 - 2 * t ** 2 + t) + (vectors[-1][0]-points[-1][0]) * (t ** 3 - t ** 2)
                X.append(x)
                y = points[i][1] * (2 * t ** 3 - 3 * t ** 2 + 1) + points[-1][1] * (-2 * t ** 3 + 3 * t ** 2) + \
                    (vectors[i][1]-points[i][1]) * (
                            t ** 3 - 2 * t ** 2 + t) + (vectors[-1][1]-points[-1][1]) * (t ** 3 - t ** 2)
                Y.append(y)
    for i in range(len(X)):
        if i != len(X) - 1:
            canv.create_line(X[i], Y[i], X[i + 1], Y[i + 1])
def b_spline():
    global x, y
    import scipy.interpolate as si
    P = [points[0]]
    P.extend(points)
    P.append(points[-1])
    P.append(points[-1])
    t = 0
    degree = int(sedit.get())

    def N_1(t):
        tmin = 0
        tmax = 1
        dt = 0.1
        t_i = []
        while tmin <= tmax:
            t_i.append(tmin)
            tmin += dt
        for i in range(len(t_i) - 2):
            if t >= t_i[i] and t <= t_i[i + 1]:
                return (t - t_i[i]) / (t_i[i + 2] - t_i[i])
            if t >= t_i[i + 1] and t <= t_i[i + 2]:
                return (t_i[i + 2] - t) / (t_i[i + 2] - t_i[i + 1])

    def N_2(t):
        tmin = 0
        tmax = 1
        dt = 0.1
        t_i = []
        while tmin <= tmax:
            t_i.append(tmin)
            tmin += dt
        for i in range(len(t_i) - 3):
            if t >= t_i[i] and t <= t_i[i + 1]:
                # print(((t-t_i[i])**2/(t_i[i+2]-t_i[i])*(t_i[i+1]-t_i[i])))
                return ((t - t_i[i]) ** 2 / (t_i[i + 2] - t_i[i]) * (t_i[i + 1] - t_i[i]))
            if t >= t_i[i + 1] and t <= t_i[i + 2]:
                # print(((t-t_i[i])*(t_i[i+2]-t) / (t_i[i + 2] - t_i[i+1])*(t_i[i + 2] - t_i[i])) + ((t-t_i[i+1])*(t_i[i+3]-t) / (t_i[i + 3] - t_i[i+1])*(t_i[i + 2] - t_i[i + 1])))
                return ((t - t_i[i]) * (t_i[i + 2] - t) / (t_i[i + 2] - t_i[i + 1]) * (t_i[i + 2] - t_i[i])) + (
                            (t - t_i[i + 1]) * (t_i[i + 3] - t) / (t_i[i + 3] - t_i[i + 1]) * (t_i[i + 2] - t_i[i + 1]))

    def N_3(t):
        tmin = 0
        tmax = 1
        dt = 0.1
        t_i = []
        while tmin <= tmax:
            t_i.append(tmin)
            tmin += dt
        for i in range(len(t_i) - 3):
            if t >= t_i[i] and t <= t_i[i + 1]:
                # print(((t-t_i[i])**2/(t_i[i+2]-t_i[i])*(t_i[i+1]-t_i[i])))
                return ((t - t_i[i])  / (t_i[i + 2] - t_i[i]) * (t_i[i + 1] - t_i[i]))*N_2(t)
            if t >= t_i[i + 1] and t <= t_i[i + 2]:
                # print(((t-t_i[i])*(t_i[i+2]-t) / (t_i[i + 2] - t_i[i+1])*(t_i[i + 2] - t_i[i])) + ((t-t_i[i+1])*(t_i[i+3]-t) / (t_i[i + 3] - t_i[i+1])*(t_i[i + 2] - t_i[i + 1])))
                return ((t - t_i[i]) / (t_i[i + 2] - t_i[i]) *N_2(t) + (
                        (t_i[i + 2 +1] - t) / (t_i[i + 2 +1] - t_i[i + 1])*N_2(t)))

    X = []
    Y = []
    x = 0
    y = 0
    for i in range(len(points)):
        # set_point(points[i][0],points[i][1])
        while t <= 0.9:
            if int(sedit.get()) == 1:
                x += points[i][0] * N_1(t)
                X.append(x)
                y += points[i][1] * N_1(t)
                Y.append(y)
                t += 0.1
            if int(sedit.get()) == 2:
                x += points[i][0] * N_2(t)
                X.append(x)
                y += points[i][1] * N_2(t)
                Y.append(y)
                t += 0.1
            if int(sedit.get()) == 3:
                x += points[i][0] * N_3(t)
                X.append(x)
                y += points[i][1] * N_3(t)
                Y.append(y)
                t += 0.1

    def bspline_add_points(cv, n=100, degree=3, periodic=False):
        cv = np.asarray(cv)
        count = len(cv)

        if periodic:
            factor, fraction = divmod(count + degree + 1, count)
            cv = np.concatenate((cv,) * factor + (cv[:fraction],))
            count = len(cv)
            degree = np.clip(degree, 1, degree)

        else:
            degree = np.clip(degree, 1, count - 1)

        kv = None
        if periodic:
            kv = np.arange(0 - degree, count + degree + degree - 1)
        else:
            kv = np.clip(np.arange(count + degree + 1) - degree, 0, count - degree)

        u = np.linspace(periodic, (count - degree), n)

        return np.array(si.splev(u, (kv, cv.T, degree))).T

    p = bspline_add_points(P, n=100, degree=degree, periodic=False)
    X, Y = p.T
    for i in range(len(X)):
        if i != len(X) - 1:
            canv.create_line(X[i], Y[i], X[i + 1], Y[i + 1])
def catmull_rom():
   # P = [[1, 0], [1, 0], [1, 0], [2, 0], [3, 0], [4, 3], [5, 0], [5, 0], [5, 0]]
    P = [points[0]]
    P.extend(points)
    P.append(points[-1])
    P.append(points[-1])
    X = []
    Y = []
    for i in range(len(P) - 1):
        t = 0
        while t <= 1:
            if i != len(P) - 4:
                t += 0.01
                x = 1 / 2 * (-t * (1 - t) ** 2 * P[i][0] + (2 - 5 * t ** 2 + 3 * t ** 3) * P[i + 1][0] + t * (
                            1 + 4 * t - 3 * t ** 2) * P[i + 2][0] - t ** 2 * (1 - t) * P[i + 3][0])
                X.append(x)
                y = 1 / 2 * (-t * (1 - t) ** 2 * P[i][1] + (2 - 5 * t ** 2 + 3 * t ** 3) * P[i + 1][1] + t * (
                            1 + 4 * t - 3 * t ** 2) * P[i + 2][1] - t ** 2 * (1 - t) * P[i + 3][1])
                Y.append(y)
            if i == len(P) - 4:
                t += 0.01
                x = 1 / 2 * (-t * (1 - t) ** 2 * P[i][0] + (2 - 5 * t ** 2 + 3 * t ** 3) * P[i + 1][0] + t * (
                        1 + 4 * t - 3 * t ** 2) * P[i + 2][0] - t ** 2 * (1 - t) * P[i + 3][0])
                X.append(x)
                y = 1 / 2 * (-t * (1 - t) ** 2 * P[i][1] + (2 - 5 * t ** 2 + 3 * t ** 3) * P[i + 1][1] + t * (
                        1 + 4 * t - 3 * t ** 2) * P[i + 2][1] - t ** 2 * (1 - t) * P[i + 3][1])
                Y.append(y)
                break
        if i == len(P) - 4:
            break
    for i in range(len(X)):
        if i != len(X) -1:
            canv.create_line(X[i],Y[i],X[i+1],Y[i+1])

btn = Button(root, text="Очистить полотно", command=clear, width=75, bg="#0f0f0f", fg="red")
btn.pack(side=TOP)
btn1 = Button(root, text="Интерполирующая кривая Лагранжа", command=lagrange, width=75, bg="#0f0f0f", fg="red")
btn1.pack(side=TOP)
btn1 = Button(root, text="Аппроксимирующая кривая Безье", command=beze, width=75, bg="#0f0f0f", fg="red")
btn1.pack(side=TOP)
btn2 = Button(root, text="Интерполирующая кривая Эрмита", command=ermit, width=75, bg="#0f0f0f", fg="red")
btn2.pack(side=TOP)
btn1 = Button(root, text="Аппроксимирующая кривая B-сплайн", command=b_spline, width=75, bg="#0f0f0f", fg="red")
btn1.pack(side=TOP)
btn1 = Button(root, text="Интерполирующая кривая Катмулл-Ром", command=catmull_rom, width=75, bg="#0f0f0f", fg="red")
btn1.pack(side=TOP)
lbl = Label(root, text="Введите степень B-сплайна", bg="#0f0f0f", fg="red")
lbl.pack(side=TOP)
sedit = Entry(root, width=90)
sedit.pack(side=TOP)

lbl = Label(root, text="Введите координаты векторов (для Эрмита)", bg="#0f0f0f", fg="red")
lbl.pack(side=TOP)

xeditv = Entry(root, width=90)
xeditv.pack(side=TOP)

yeditv = Entry(root, width=90)
yeditv.pack(side=TOP)

canv.bind('<1>',click)                   # <---
root.mainloop()


from pyspark.sql import SparkSession
import pandas
import sys

user_declared_state = sys.argv[1]
print(user_declared_state, 'state:::::::::::::')

df_mapping = pandas.read_csv('/home/raja/Desktop/Ek_Step/Up text book/State_district.csv')
df_mapping = df_mapping.loc[df_mapping['state'] == user_declared_state]
city_list = list(df_mapping['district'])

spark = SparkSession.builder.appName('UpTextbook').getOrCreate()

df1 = spark.read.csv("/home/raja/Desktop/Ek_Step/Up text book/oct-2022/oct 18/18th Oct UP Textbook - QR Code Scans "
                     "18th Oct 2022.csv", header=True)

df4 = df1.filter(df1["derived_loc_district"].isin(city_list)).select("state_slug", "derived_loc_district",
                                                                     "SUM(total_count)")
df4.repartition(1).write.mode('overwrite').format('csv').option('header', True)\
    .save("/home/raja/Desktop/Ek_Step/Up text book/oct-2022/oct 18/QR")


#! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py mcb.pyw save <keyword> - Saves clipboard to keyword.
#        py mcb.pyw <keyword> - Loads keyword to clipboard.
#        py mcb.pyw list - Loads all keywords to clipboard.
#        py mcb.pyw del <saved keyword> - Delete saved keyword.
#        py mcb.pyw del - Delete all saved keywords.

import shelve, pyperclip, sys

# shelve - Manage shelves of pickled objects.
# To summarize the interface (key is a string, data is an arbitrary object):
#
#         import shelve
#         d = shelve.open(filename) # open, with (g)dbm filename -- no suffix
#
#         d[key] = data   # store data at key (overwrites old data if
#                         # using an existing key)
#         data = d[key]   # retrieve a COPY of the data at key (raise
#                         # KeyError if no such key) -- NOTE that this
#                         # access returns a *copy* of the entry!
#         del d[key]      # delete data stored at key (raises KeyError
#                         # if no such key)
#         flag = key in d # true if the key exists
#         list = d.keys() # a list of all existing keys (slow!)
#
#         d.close()       # close it

mcbShelf = shelve.open('mcb')

# Save clipboard content.
# sys.argv[] 是用来获取命令行参数的，sys.argv[0] 表示代码本身文件路径，所以参数从 1 开始
# len(sys.argv) == 3 的意思是命令行有两个参数，且第一个参数为「save」忽略大小写
# 例如命令行格式为「py mcb.pyw save quiz」命令是「mcb.pyw」，参数一sys.argv[1] = save，参数二sys.argv[2] = quiz
if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
    # mcbShelf[quiz] = 'We'll have a quiz at the end of the show.'
    mcbShelf[sys.argv[2]] = pyperclip.paste()

if len(sys.argv) == 3 and sys.argv[1].lower() == 'del' and (sys.argv[2] in mcbShelf):
    del mcbShelf[sys.argv[2]]

# 一个参数的命令，如果参数为「list」输出所有 mcbShelf 的 key 到 clipboard
# 如果参数为 mcbShelf 中的一个 key，输出对应的 value 到 clipboard
elif len(sys.argv) == 2:
    # List keywords and load content.
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
    elif sys.argv[1].lower() == 'del':
        for k in mcbShelf.keys():
            del mcbShelf[k]
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])
mcbShelf.close()


#!/usr/bin/env python2

import argparse
import boto3
import datetime
import urllib
import math
import os
import logging
import gzip
import datetime
import calendar
import logging
import StringIO
import multiprocessing
import Queue
import random
import functools

logger = logging.getLogger('make_speeds')
logger.setLevel(logging.INFO)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(fmt='%(asctime)s %(levelname)s %(message)s'))
logger.addHandler(handler)

# import make_speeds after logger has been setup
import make_speeds

valhalla_tiles = [{'level': 2, 'size': 0.25}, {'level': 1, 'size': 1.0}, {'level': 0, 'size': 4.0}]

def url_suffix(tile_level, tile_index):
  tile_set = filter(lambda x: x['level'] == tile_level, valhalla_tiles)[0]
  max_index = int(360.0/tile_set['size'] * 180.0/tile_set['size']) - 1
  num_dirs = int(math.ceil(len(str(max_index)) / 3.0))
  suffix = list(str(tile_index).zfill(3 * num_dirs))
  for i in range(0, num_dirs):
    suffix.insert(i * 3 + i, '/')
  suffix = '/' + str(tile_level) + ''.join(suffix)
  return suffix

def split(l, n):
  size = int(math.ceil(len(l)/float(n)))
  cutoff = len(l) % n
  result = []
  pos = 0
  for i in range(0, n):
    end = pos + size if cutoff == 0 or i < cutoff else pos + size - 1
    result.append(l[pos:end])
    pos = end
  return result

def interrupt_wrapper(func):
  try:
    func()
  except (KeyboardInterrupt, SystemExit):
    logger.error('Interrupted or killed')

def upload(speed_bucket, level, index, week, speed_tiles):
  logger.info('Uploading data to bucket: ' + speed_bucket)
  client = boto3.client('s3')
  prefix = week + '/'.join(url_suffix(int(level), int(index)).split('/')[:-1])
  for tile in speed_tiles:
    key = prefix + '/' + tile.split('/')[-1] + '.gz'
    logger.info('Uploading ' + tile + ' as ' + key)
    zipped = StringIO.StringIO()
    with open(tile, 'rb') as f_in, gzip.GzipFile(mode='wb',fileobj=zipped) as f_out:
      f_out.write(f_in.read())
    client.put_object(
      ACL='public-read',
      Bucket=speed_bucket,
      ContentType='application/octet-stream',
      ContentEncoding='gzip',
      Body=zipped.getvalue(),
      Key=key)

def load(histograms, sub_segments, info, lengths, loaded):
  segments = {}
  while True:
    try:
      file_name = histograms.get()
      #finished if we get the sentinel
      if not file_name:
        break
      loaded.put(file_name)
      make_speeds.addSegments(file_name, info, lengths, segments)
    except (KeyboardInterrupt, SystemExit) as e:
      raise e
    except Exception as e:
      logger.error('Failed to load segments from %s' % file_name)

  #send back the info
  sub_segments.put(segments)

def convert(level, index, week, osmlr_version, histograms, concurrency):
  url = 'http://s3.amazonaws.com/osmlr-tiles/' + osmlr_version + '/pbf' + url_suffix(level, index) + '.osmlr'
  logger.info('Fetching osmlr tile: ' + url)
  osmlr = str(level) + '_' + str(index) + '.osmlr'
  urllib.URLopener().retrieve(url, osmlr)

  logger.info('Getting segment lengths from osmlr')
  lengths = make_speeds.getLengths(osmlr)

  date = datetime.datetime.strptime(week + '/1','%Y/%W/%w')
  start = calendar.timegm(date.timetuple())
  info = {'rangeStart': start, 'rangeEnd': start + 604800, 'unitSize': 604800, 'entrySize': 3600,
    'description': 'Hourly speeds for the week starting on ' + str(date), 'level': level, 'index': index}

  logger.info('Accumulating segment speeds from histograms')
  #we share the segments dict in a process safe way
  sub_segments = multiprocessing.Queue()
  loaded = multiprocessing.Queue()
  processes = []
  #start them up and wait for them to get all the results back
  for i in xrange(concurrency):
    histograms.put(False)
  for i in xrange(concurrency):
    bound = functools.partial(load, histograms, sub_segments, info, lengths, loaded)
    processes.append(multiprocessing.Process(target=interrupt_wrapper, args=(bound,)))
    processes[-1].start()

  #then harvest all the sub_segments
  segments = {}
  for i in xrange(concurrency):
    #get out the segments and merge them all together
    sub = sub_segments.get()
    while len(sub):
      seg_id = sub.iterkeys().next()
      hours = sub.pop(seg_id)
      #since each histogram is a specific hour no two dicts will have the same hour
      segments.setdefault(seg_id, {}).update(hours)
    logger.info('Merged result segments from sub process %d' % i)

  #then make some tiles
  logger.info('Creating speed tiles')
  prefix = url_suffix(int(level), int(index)).split('/')[-1]
  return make_speeds.createSpeedTiles(lengths, prefix + '.spd', 10000, prefix + '.nex', True, segments, info), loaded, osmlr

def fetch(histogram_bucket, keys, results):
  session = boto3.session.Session()
  resource = session.resource('s3')
  for key in keys:
    try:
      dest = key.replace('/', '_')
      resource.Object(histogram_bucket, key).download_file(dest)
      if os.path.isfile(dest):
        logger.info('Downloaded s3://' + histogram_bucket + '/' + key)
        results.put(dest)
    except (KeyboardInterrupt, SystemExit) as e:
      raise e
    except Exception as e:
      pass

def download(histogram_bucket, tile_level, tile_index, week, concurrency):
  #we need to get all the histograms for all the hours of this week
  date = datetime.datetime.strptime(week + '/1','%Y/%W/%w')
  logger.info('Downloading files for week ' + '{d.year}/{d.month}/{d.day} tile {l}/{t}.fb'.format(d=date, l=tile_level, t=tile_index))
  keys = []
  for hour in xrange(0, 24 * 7):
    key = '{d.year}/{d.month}/{d.day}/{d.hour}/{l}/{t}.fb'.format(d=(date + datetime.timedelta(hours=hour)), l=tile_level, t=tile_index)
    keys.append(key)
  random.shuffle(keys)
  keys = split(keys, concurrency)

  processes = []
  downloaded = multiprocessing.Queue()
  for i in xrange(concurrency):
    bound = functools.partial(fetch, histogram_bucket, keys[i], downloaded)
    processes.append(multiprocessing.Process(target=interrupt_wrapper, args=(bound,)))
    processes[-1].start()
  for p in processes:
    if p.is_alive():
      p.join()
  return downloaded

def add_tiles(tiles, tile_level, tile_index, max_level):
  #keep this one
  tiles.append((tile_level, tile_index))
  #add the subtiles
  if tile_level < max_level:
    level = filter(lambda x: x['level'] == tile_level, valhalla_tiles)[0]
    next_level = filter(lambda x: x['level'] == tile_level + 1, valhalla_tiles)[0]
    per_row = int(360 / level['size'])
    row = tile_index / per_row
    col = tile_index - row * per_row
    scale = int(level['size'] / next_level['size'])
    row *= scale
    col *= scale
    per_row = int(360 / next_level['size'])
    #add the children recursively
    for y in range(row, row + scale):
      for x in range(col, col + scale):
        add_tiles(tiles, next_level['level'],  y*per_row + x, max_level)

if __name__ == '__main__':
  #build args
  parser = argparse.ArgumentParser()
  parser.add_argument('--environment', type=str, help='The environment prod or dev to use when computing bucket names and batch job queues and definitions', required=True)
  parser.add_argument('--tile-level', type=int, help='The tile level used to get the input data from the histogram bucket', required=True)
  parser.add_argument('--tile-index', type=int, help='The tile index used to get the input data from the histogram bucket', required=True)
  parser.add_argument('--week', type=str, help='The week used to get the input data from the histogram bucket', required=True)
  parser.add_argument('--concurrency', type=int, help='The week used to get the input data from the histogram bucket', default=1)
  parser.add_argument('--max-tile-level', type=int, help='The max tile level to generate speed tiles for. Must be at least 0 and can go up to 2', default=1)
  parser.add_argument('--osmlr-version', type=str, help='The version of osmlr to fetch when creating speed tiles', required=True)
  args = parser.parse_args()

  #generate the list of the parent tile and all its subtiles, level 0 and 1 only right now
  tiles = []
  add_tiles(tiles, args.tile_level, args.tile_index, args.max_tile_level)

  #need this to submit jobs
  batch_client = boto3.client('batch')
  histogram_bucket = 'datastore-output-' + args.environment
  speed_bucket = 'speedtiles-' + args.environment
  job_queue = 'referencetiles-' + args.environment
  job_def = 'referencetiles-' + args.environment

  try:
    #for each tile
    for tile in tiles:
      logger.info('Histogram input bucket: ' + histogram_bucket)
      logger.info('Speedtile output bucket: ' + speed_bucket)
      logger.info('Tile level: ' + str(tile[0]))
      logger.info('Tile index: ' + str(tile[1]))
      logger.info('Week: ' + args.week)
      logger.info('OSMLR: ' + args.osmlr_version)
      #go get the histogram data
      histograms = download(histogram_bucket, tile[0], tile[1], args.week, args.concurrency)
      if not histograms.empty():
        #make the speed tile
        speed_tiles, histograms, osmlr = convert(tile[0], tile[1], args.week, args.osmlr_version, histograms, args.concurrency)
        #move the speed tile to its destination
        upload(speed_bucket, tile[0], tile[1], args.week, speed_tiles)
        #create the corresponding referencetile job
        job_name = '_'.join([args.week.replace('/', '-'), str(tile[0]), str(tile[1])])
        job = {'environment': args.environment, 'tile_level': str(tile[0]), 'tile_index': str(tile[1]), 'week': args.week}
        logger.info('Submitting reference tile job ' + job_name)
        logger.info('Job parameters ' + str(job))
        submitted = batch_client.submit_job(
          jobName = job_name,
          jobQueue = job_queue,
          jobDefinition = job_def,
          parameters = job,
          containerOverrides={
            'memory': 8192,
            'vcpus': 2,
            'command': ['/scripts/ref-tile-work.py', '--environment', 'Ref::environment', '--end-week', 'Ref::week', '--weeks', '52', '--tile-level', 'Ref::tile_level', '--tile-index', 'Ref::tile_index']
          }
        )
        logger.info('Job %s was submitted and got id %s' % (job_name, submitted['jobId']))
        #clean up the files
        histograms.put(False)
        while True:
          f = histograms.get()
          if not f:
            break
          os.remove(f)
        for f in speed_tiles + [osmlr]:
          os.remove(f)
      else:
        logger.info('No histogram data')

    logger.info('Run complete')
  except (KeyboardInterrupt, SystemExit):
    logger.error('Interrupted or killed')


from __future__ import annotations
import logging
import re
from typing import TYPE_CHECKING, List, Optional, Union
from glob import glob

from opentrons.config import IS_ROBOT, IS_LINUX
from opentrons.drivers.rpi_drivers import types, interfaces, usb, usb_simulator
from opentrons.hardware_control.emulation.module_server.helpers import (
    listen_module_connection,
)
from opentrons.hardware_control.modules.module_calibration import (
    ModuleCalibrationOffset,
    load_module_calibration_offset,
    save_module_calibration_offset,
)
from opentrons.hardware_control.modules.types import ModuleType
from opentrons.types import Point
from .types import AionotifyEvent, BoardRevision, OT3Mount
from . import modules

if TYPE_CHECKING:
    from .api import API
    from .ot3api import OT3API

log = logging.getLogger(__name__)

MODULE_PORT_REGEX = re.compile("|".join(modules.MODULE_TYPE_BY_NAME.keys()), re.I)

class AttachedModulesControl:
    """
    A class to handle monitoring module attachment, capturing the physical
    USB port information and finally building a module object.
    """

    def __init__(
        self,
        api: Union["API", "OT3API"],
        usb: interfaces.USBDriverInterface,
    ) -> None:
        self._available_modules: List[modules.AbstractModule] = []
        self._api = api
        self._usb = usb

    @classmethod
    async def build(
        cls,
        api_instance: Union["API", "OT3API"],
        board_revision: BoardRevision,
    ) -> AttachedModulesControl:
        usb_instance = (
            usb.USBBus(board_revision)
            if not api_instance.is_simulator and IS_ROBOT
            else usb_simulator.USBBusSimulator()
        )
        mc_instance = cls(api=api_instance, usb=usb_instance)

        if not api_instance.is_simulator:
            # Do an initial scan of modules.
            await mc_instance.register_modules(mc_instance.scan())
            if not IS_ROBOT:
                # Start task that registers emulated modules.
                api_instance.loop.create_task(
                    listen_module_connection(mc_instance.register_modules)
                )

        return mc_instance

    @property
    def available_modules(self) -> List[modules.AbstractModule]:
        return self._available_modules

    async def build_module(
        self,
        port: str,
        usb_port: types.USBPort,
        type: modules.ModuleType,
        sim_model: Optional[str] = None,
    ) -> modules.AbstractModule:
        return await modules.build(
            port=port,
            usb_port=usb_port,
            type=type,
            simulating=self._api.is_simulator,
            hw_control_loop=self._api.loop,
            execution_manager=self._api._execution_manager,
            sim_model=sim_model,
        )

    async def unregister_modules(
        self, mods_at_ports: List[modules.ModuleAtPort]
    ) -> None:
        """
        De-register Modules.

        Remove any modules that are no longer found by aionotify.
        """
        removed_modules = []
        for mod in mods_at_ports:
            for attached_mod in self.available_modules:
                if attached_mod.port == mod.port:
                    removed_modules.append(attached_mod)
        for removed_mod in removed_modules:
            try:
                self._available_modules.remove(removed_mod)
            except ValueError:
                log.exception(
                    f"Removed Module {removed_mod} not found in attached modules"
                )
        for removed_mod in removed_modules:
            log.info(
                f"Module {removed_mod.name()} detached from port {removed_mod.port}"
            )
            await removed_mod.cleanup()
        self._available_modules = sorted(
            self._available_modules, key=modules.AbstractModule.sort_key
        )

    async def register_modules(
        self,
        new_mods_at_ports: Optional[List[modules.ModuleAtPort]] = None,
        removed_mods_at_ports: Optional[List[modules.ModuleAtPort]] = None,
    ) -> None:
        """
        Register Modules.

        Upon system recognition of a module being plugged in, we should
        register that module and de-register any modules that are
        no longer found on the system.
        """
        if new_mods_at_ports is None:
            new_mods_at_ports = []
        if removed_mods_at_ports is None:
            removed_mods_at_ports = []

        # destroy removed mods
        await self.unregister_modules(removed_mods_at_ports)
        self._new_mods_at_ports = new_mods_at_ports
        unsorted_mods_at_port = self._usb.match_virtual_ports(new_mods_at_ports)

        # build new mods
        for mod in unsorted_mods_at_port:
            new_instance = await self.build_module(
                port=mod.port,
                usb_port=mod.usb_port,
                type=modules.MODULE_TYPE_BY_NAME[mod.name],
            )
            self._available_modules.append(new_instance)
            log.info(
                f"Module {mod.name} discovered and attached"
                f" at port {mod.port}, new_instance: {new_instance}"
            )
        self._available_modules = sorted(
            self._available_modules, key=modules.AbstractModule.sort_key
        )

    def scan(self) -> List[modules.ModuleAtPort]:
        """Scan for connected modules and return list of
        tuples of serial ports and device names
        """
        if IS_ROBOT and IS_LINUX:
            devices = glob("/dev/ot_module*")
        else:
            devices = []

        discovered_modules = []

        for port in devices:
            symlink_port = port.split("dev/")[1]
            module_at_port = self.get_module_at_port(symlink_port)
            if module_at_port:
                discovered_modules.append(module_at_port)

        log.debug("Discovered modules: {}".format(discovered_modules))
        return discovered_modules

    @staticmethod
    def get_module_at_port(port: str) -> Optional[modules.ModuleAtPort]:
        """Given a port, returns either a ModuleAtPort
        if it is a recognized module, or None if not recognized.
        """
        match = MODULE_PORT_REGEX.search(port)
        if match:
            name = match.group().lower()
            if name not in modules.MODULE_TYPE_BY_NAME:
                log.warning(f"Unexpected module connected: {name} on {port}")
                return None
            return modules.ModuleAtPort(port=f"/dev/{port}", name=name)
        return None

    async def handle_module_appearance(self, event: AionotifyEvent) -> None:
        """Only called upon availability of aionotify. Check that
        the file system has changed and either remove or add modules
        depending on the result.

        Args:
            event: The event passed from aionotify.

        Returns:
            None
        """
        maybe_module_at_port = self.get_module_at_port(event.name)
        new_modules = None
        removed_modules = None
        if maybe_module_at_port is not None:
            if hasattr(event.flags, "DELETE"):
                removed_modules = [maybe_module_at_port]
                log.info(f"Module Removed: {maybe_module_at_port}")
            elif hasattr(event.flags, "CREATE"):
                new_modules = [maybe_module_at_port]
                log.info(f"Module Added: {maybe_module_at_port}")
            try:
                await self.register_modules(
                    removed_mods_at_ports=removed_modules,
                    new_mods_at_ports=new_modules,
                )
            except Exception:
                log.exception("Exception in Module registration")

    def get_module_by_module_id(
        self, module_id: str
    ) -> Optional[modules.AbstractModule]:
        """Returns the module with the matching serial id."""
        found_module: Optional[modules.AbstractModule] = None
        for module in self.available_modules:
            if module.device_info["serial"] == module_id:
                found_module = module
                break
        return found_module

    def load_module_offset(
        self, module_type: ModuleType, module_id: str
    ) -> Optional[ModuleCalibrationOffset]:
        log.info(f"Loading module offset for {module_type} {module_id}")
        return load_module_calibration_offset(module_type, module_id)

    def save_module_offset(
        self,
        module: ModuleType,
        module_id: str,
        mount: OT3Mount,
        slot: str,
        offset: Point,
        instrument_id: Optional[str] = None,
    ) -> Optional[ModuleCalibrationOffset]:
        log.info(f"Saving module {module} {module_id} offset: {offset} for slot {slot}")
        save_module_calibration_offset(
            offset, mount, slot, module, module_id, instrument_id
        )
        return load_module_calibration_offset(module, module_id)


import sys
import os
import time
import json
from numpy import random
import speech_recognition as sr
from gtts import gTTS
from playsound import playsound
import special_commands

def load_json(file):
    with open(file, encoding='utf-8') as f:
        return json.loads(f.read())

def findResponse(commands, command):
    for key in commands.keys():
        if key.lower() in command.lower():
            return commands.get(key)
    return '-'

def listen(lang):
    r = sr.Recognizer()

    with sr.Microphone() as source:
        audio = r.listen(source)
        command = ''

        try:
            command = r.recognize_google(audio, language=lang)
        except sr.UnknownValueError:
            print('I don\'t understand')
        except sr.RequestError:
            print('Request error!')

        print(command)
        return command

def speak(text, lang):
    tts = gTTS(text, lang=lang.split('-')[0])
    file = f'tts-{time.time()}.mp3'
    tts.save(file)
    playsound(file)
    os.remove(file)

def response(commands, command, lang):
    found = findResponse(commands, command)

    if(found != "-"):
        if(type(found) == list):
            choise = random.choice(found)
            print(choise)
            speak(choise, lang)
        elif(type(found) == dict):
            unformatted = found.get('txt')
            function_name = found.get('fun').get('name')
            function_param = found.get('fun').get('param')
            fun = getattr(special_commands, function_name)
            r = fun(function_param) if function_param  else fun()
            text = unformatted.format(r)
            print(text)
            speak(text, lang)
    else:
        getattr(special_commands, 'searchInGoogle')(command)
        print(commands.get(found))
        speak(commands.get(found), lang)

def main(argv):
    lang = 'en-EN'

    if(len(argv) > 1):
        lang = str(argv[1])

    command_file = f'./commands/{lang}.json'
    commands = load_json(command_file)
    #print(commands)

    while True:
        print("...")
        command = listen(lang)
        response(commands, command, lang)

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


from tkinter import *
from tkinter import ttk
from tkinter import tix
from tkinter import messagebox
import banco_2
import os
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter, A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.platypus import SimpleDocTemplate,Image
import webbrowser
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
from tkcalendar import Calendar, DateEntry

# defs

def popular2():
    tv2.delete(*tv2.get_children())
    vquery = "SELECT * FROM tb_nomes ORDER BY ID"
    linhas=banco_2.dql(vquery)
    for i in linhas:
        tv2.insert("","end",values=i)

def buscar():
    tv2.delete(*tv2.get_children())
    vquery="SELECT * FROM tb_nomes WHERE nome LIKE '%"+nome_entry.get()+"%'"
    linhas=banco_2.dql(vquery)
    for i in linhas:
        tv2.insert("","end",values=i)

def printTudo():
    webbrowser.open("ListaGeral.pdf")

def imprimirTudo():
    valBarra(10000)
    try:
        vquery = "SELECT * FROM tb_nomes"
        linhas=banco_2.dql(vquery)
        cnv=canvas.Canvas("ListaGeral.pdf")
        cnv.setFont("Helvetica-Bold",24)
        cnv.drawString(200,790,'Cadastro de Clientes')

        cnv.setFont("Helvetica-Bold",12)
        cnv.drawString(40,740,'ID: ')
        cnv.drawString(70,740,'Nome: ')
        cnv.drawString(200,740,'Telefone: ')
        cnv.drawString(300,740,'UF: ')
        cnv.drawString(340,740,'Cidade: ')
        cnv.drawString(430,740,'Assinante: ')
        cnv.drawString(510,740,'Data: ')

        cnv.setFont("Helvetica",12)
        x = 40
        y = 700
        for i in linhas:
            id = i[0]
            nome = i[1]
            fone = i[2]
            estado= i[3]
            cidade = i[4]
            ass= i[5]
            data= i[6]
            cnv.drawString(x, y, str(id))
            cnv.drawString(x + 30, y, nome)
            cnv.drawString(x + 160, y, fone)
            cnv.drawString(x + 260, y, str(estado))
            cnv.drawString(x + 300, y, str(cidade))
            cnv.drawString(x + 420, y, str(ass))
            cnv.drawString(x + 470, y, str(data))
            y -= 20
        cnv.rect(20,720,550,3,fill=True,stroke=False)
        cnv.showPage()
        cnv.save()
        printTudo()
    except:
        messagebox.showerror(title="ERRO",message="Erro ao Gerar PDF")
        return
    var_barra.set(0)

def printCliente():
    webbrowser.open("cliente.pdf")

def geraRelatório():
    c=canvas.Canvas("cliente.pdf")
    codigo = codigo_entry.get()
    nome = nome_entry.get()
    telefone = telefone_entry.get()
    cidade = cidade_entry.get()
    estado = estado_entry.get()
    ass = text1.get()
    data = entry_data.get()
    c.setFont("Helvetica-Bold",24)
    c.drawString(200,790,'Ficha do Cliente')

    c.setFont("Helvetica-Bold",18)
    c.drawString(50,700,'ID: ')
    c.drawString(50,670,'Nome: ')
    c.drawString(50,640,'Telefone: ')
    c.drawString(50,610,'Cidade: ')
    c.drawString(50,580,'UF: ')
    c.drawString(50,540,'Assinante: ')
    c.drawString(50,500,'Data: ')

    c.setFont("Helvetica",18)
    c.drawString(150,700,codigo)
    c.drawString(150,670,nome)
    c.drawString(150,640,telefone)
    c.drawString(150,610,cidade)
    c.drawString(150,580,estado)
    c.drawString(150,540,ass)
    c.drawString(150,500,data)

    c.rect(20,470,550,5,fill=True,stroke=False)

    c.showPage()
    c.save()
    printCliente()

def valBarra(m):
    cont=0
    etapas=m/100
    while cont<etapas:
        cont+=10
        i=0
        while i<1000000:
            i+=1
        var_barra.set(cont)
        app.update()

def limpar():
    codigo_entry.delete(0,END)
    nome_entry.delete(0,END)
    telefone_entry.delete(0,END)
    cidade_entry.delete(0,END)
    estado_entry.set(" ")
    text1.set("Não")
    entry_data.delete(0,END)

def novo():
    if nome_entry.get()=="" or telefone_entry.get()=="" or estado_entry.get()==" " or cidade_entry.get()=="" or entry_data.get()=="":
        messagebox.showinfo(title="ERRO",message="Adicione os valores")
        return
    try:
        vquery = "INSERT INTO tb_nomes (nome,fone,Estado,Cidade,assinante,data) VALUES ('"+nome_entry.get()+"','"+telefone_entry.get()+"','"+estado_entry.get()+"','"+cidade_entry.get()+"','"+text1.get()+"','"+entry_data.get()+"')"
        banco_2.dml(vquery)
    except:
        messagebox.showerror(title="ERRO",message="Erro ao Inserir")
        return
    popular2()
    limpar()
    nome_entry.focus()

def duploClick(event):
    limpar()
    tv2.selection()
    for i in tv2.selection():
        col1,col2,col3,col4,col5,col6,col7=tv2.item(i,'values')
        codigo_entry.insert(END,col1)
        nome_entry.insert(END,col2)
        telefone_entry.insert(END,col3)
        estado_entry.set(col4)
        cidade_entry.insert(END,col5)
        text1.set(col6)
        entry_data.insert(END,col7)

def apagar():
    codigo = codigo_entry.get()
    vid=-1
    itemSelection=tv2.selection()[0]
    valores=tv2.item(itemSelection,"values")
    vid=valores[0]
    try:
        vquery = "DELETE FROM tb_nomes WHERE id="+vid
        banco_2.dml(vquery)
        messagebox.showinfo(title="SUCESSO",message="Valores deletados!")
    except:
        messagebox.showwarning(title="ERRO",message="Erro ao deletar")
        return
    tv2.delete(itemSelection)

def alterar():
    codigo = codigo_entry.get()
    nome = nome_entry.get()
    telefone = telefone_entry.get()
    estado = estado_entry.get()
    cidade=cidade_entry.get()
    ass = text1.get()
    data = entry_data.get()
    vid=-1
    itemSelection=tv2.selection()[0]
    valores=tv2.item(itemSelection,"values")
    vid=valores[0]
    try:
        vquery = "UPDATE tb_nomes SET nome = '"+nome+"', fone = '"+telefone+"',Estado = '"+estado+"', Cidade = '"+cidade+"', assinante = '"+ass+"', data = '"+data+"' WHERE id="+vid
        banco_2.dml(vquery)
        messagebox.showinfo(title="SUCESSO",message="Valores alterados!")
    except:
        messagebox.showerror(title="ERRO",message="Erro ao alterar")
        return
    popular2()
    limpar()

def Menus():
    menubar = Menu(app,tearoff=0)
    app.config(menu=menubar)
    filemenu=Menu(menubar,tearoff=0)
    filemenu2=Menu(menubar,tearoff=0)

    def quit(): app.destroy()

    menubar.add_cascade(label= "Opções",menu=filemenu)
    menubar.add_cascade(label= "Sobre",menu=filemenu2)

    filemenu.add_command(label="Sair",command=quit)
    filemenu.add_command(label="Imprimir Dados",command=imprimirTudo)
    filemenu.add_command(label="Ficha do Cliente",command=geraRelatório)
    filemenu2.add_command(label="Info.")

def dashboard():
    #dashboard

    lb_dash = Label(frame_3,text="Relatório Geral",fg ='black',font=('verdana',12,'bold'))
    lb_dash.place(relx=0,rely=0)

    # clientes

    cont = "SELECT COUNT(nome) FROM tb_nomes"
    valor1=banco_2.dql(cont)

    frame_cl = Frame(frame_3,bd=4,background='white')
    frame_cl.place(relx=0,rely=0.08,relwidth=0.3,relheight=0.2)
    lb_cl = Label(frame_cl,text="Número de Clientes",fg ='black',font=('verdana',8,'bold'),background='white')
    lb_cl.place(relx=0.1,rely=0)
    frame_qcl = Frame(frame_cl,background='blue')
    frame_qcl.place(relx=0,rely=0,relwidth=0.05,relheight=0.25)
    lb_cl_valor = Label(frame_cl,text=str(valor1[0][0])+" Clientes",fg ='blue',font=('verdana',10,'bold'),background='white')
    lb_cl_valor.place(relx=0.25,rely=0.5)

    # assinantes

    cont_ass = "SELECT COUNT(nome) FROM tb_nomes WHERE assinante = 'Sim'"
    valor2=banco_2.dql(cont_ass)

    frame_ass = Frame(frame_3,bd=4,background='white')
    frame_ass.place(relx=0.31,rely=0.08,relwidth=0.3,relheight=0.2)
    lb_ass = Label(frame_ass,text="Número Assinantes",fg ='black',font=('verdana',8,'bold'),background='white')
    lb_ass.place(relx=0.1,rely=0)
    frame_qass = Frame(frame_ass,background='blue')
    frame_qass.place(relx=0,rely=0,relwidth=0.05,relheight=0.25)
    lb_ass_valor = Label(frame_ass,text=str(valor2[0][0])+" Assinantes",fg ='blue',font=('verdana',10,'bold'),background='white')
    lb_ass_valor.place(relx=0.25,rely=0.5)

    # clientes/ UF

    uf = "SELECT COUNT(nome),Estado FROM tb_nomes GROUP BY Estado"
    valor3=banco_2.dql(uf)

    frame_uf = Frame(frame_3,bd=4,background='white')
    frame_uf.place(relx=0,rely=0.30,relwidth=1,relheight=0.6)
    lb_uf = Label(frame_uf,text="Clientes / UF",fg ='black',font=('verdana',8,'bold'),background='white')
    lb_uf.place(relx=0.05,rely=0)
    frame_quf = Frame(frame_uf,background='blue')
    frame_quf.place(relx=0,rely=0,relwidth=0.02,relheight=0.13)

    list_est = []
    list_nome = []
    for i in valor3:
        list_nome.append(i[0])
        list_est.append(i[1])

    figura = plt.Figure(figsize=(10, 2.5),dpi=60)
    ax=figura.add_subplot(111)

    ax.bar(list_est,list_nome)
    totals=[]
    c=0
    for i in ax.patches:
        ax.text(i.get_x()+.4,i.get_height()+.05,str(list_nome[c]),fontsize=12,fontstyle='italic',verticalalignment='baseline',color='black')
        c+=1

    ax.patch.set_facecolor('#FFFFFF')
    ax.spines['bottom'].set_color('#CCCCCC')
    ax.spines['bottom'].set_linewidth(1)
    ax.spines['right'].set_linewidth(0)
    ax.spines['top'].set_linewidth(0)
    ax.spines['left'].set_color('#CCCCCC')
    ax.spines['left'].set_linewidth(1)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.tick_params(bottom=False,left=False)
    ax.set_axisbelow(True)
    ax.yaxis.grid(True,color='#EEEEEE')
    ax.xaxis.grid(False)

    canva = FigureCanvasTkAgg(figura,frame_uf)
    canva.get_tk_widget().place(relx=0,rely=0.20)

def calendario():
    def print_cal():
        dataIni = calendario1.get_date()
        calendario1.destroy()
        entry_data.delete(0,END)
        entry_data.insert(END,dataIni)
        calData.destroy()

    calendario1 = Calendar(frame_1,fg="gray75",bg="blue",font=("Times",'9','bold'),locale='pt_br')
    calendario1.place(relx=0.4,rely=0.1)
    calData = Button(frame_1,text="Inserir Data",command=print_cal)
    calData.place(relx=0.55,rely=0.85,height=25,width=100)

# INTERFACE INICIAL

pastaApp = os.path.dirname(__file__)

app = tix.Tk()
app.title("Sistema de Cadastros")
app.geometry("700x500")
app.resizable(True,True)
app.maxsize(width=900,height=700)
app.minsize(width=500,height=400)

# ABAS

nb=ttk.Notebook(app)
nb.place(relx=0,rely=0,relwidth=1,relheight=1)

tb1=Frame(nb,background="#dde")
tb2=Frame(nb,background="#dde")

nb.add(tb1,text="Cadastro")
nb.add(tb2,text="Relatório")

# Frames Cadastro
frame_1 = Frame(tb1,bd=4,highlightbackground='black',highlightthickness=3,bg='#99ABB5')
frame_1.place(relx=0.02,rely=0.02,relwidth=0.96,relheight=0.46)

frame_2 = Frame(tb1,bd=4,highlightbackground='black',highlightthickness=3)
frame_2.place(relx=0.02,rely=0.5,relwidth=0.96,relheight=0.46)

frame_3 = Frame(tb2,bd=4,highlightbackground='black',highlightthickness=3)
frame_3.place(relx=0.02,rely=0.02,relwidth=0.96,relheight=0.8)

Menus()

# Progress bar
var_barra=DoubleVar()
var_barra.set(0)

pb=ttk.Progressbar(tb1,variable=var_barra,maximum=100)
pb.place(x=0,y=0,relwidth=1,height=5)

# Botões
canvas_bt = Canvas(frame_1,bd=0,bg='#1e3743',highlightbackground='gray',highlightthickness=5)
canvas_bt.place(relx=0.19,rely=0.08,relwidth=0.22,relheight=0.19)

bt_limpar = Button(frame_1,text="Limpar", bd=2,bg='#107db2',activebackground='#108ecb',activeforeground='white',fg='white',font=('verdana',8,'bold'),command=limpar)
bt_limpar.place(relx=0.2,rely=0.1,relwidth=0.1,relheight=0.15)
bt_buscar = Button(frame_1,text="Buscar", bd=2,bg='#107db2',activebackground='#108ecb',activeforeground='white',fg='white',font=('verdana',8,'bold'),command=buscar)
bt_buscar.place(relx=0.3,rely=0.1,relwidth=0.1,relheight=0.15)

canvas_bt2 = Canvas(frame_1,bd=0,bg='#1e3743',highlightbackground='gray',highlightthickness=5)
canvas_bt2.place(relx=0.59,rely=0.08,relwidth=0.32,relheight=0.19)

bt_novo = Button(frame_1,text="Novo", bd=2,bg='#107db2',activebackground='#108ecb',activeforeground='white',fg='white',font=('verdana',8,'bold'),command=novo)
bt_novo.place(relx=0.6,rely=0.1,relwidth=0.1,relheight=0.15)
bt_alterar = Button(frame_1,text="Alterar", bd=2,bg='#107db2',activebackground='#108ecb',activeforeground='white',fg='white',font=('verdana',8,'bold'),command=alterar)
bt_alterar.place(relx=0.7,rely=0.1,relwidth=0.1,relheight=0.15)
bt_apagar = Button(frame_1,text="Apagar", bd=2,bg='#107db2',activebackground='#108ecb',activeforeground='white',fg='white',font=('verdana',8,'bold'),command=apagar)
bt_apagar.place(relx=0.8,rely=0.1,relwidth=0.1,relheight=0.15)

#Calendario

bt_calendario = Button(frame_1,text="Data",fg="blue",font=('verdana',8,'bold'),command=calendario)
bt_calendario.place(relx=0.05,rely=0.87,relwidth=0.08,relheight=0.1)
entry_data = Entry(frame_1,width=10)
entry_data.place(relx=0.14,rely=0.87,relwidth=0.1,relheight=0.1)

#balloons

balao_limpar = tix.Balloon(frame_1)
balao_limpar.bind_widget(bt_limpar,balloonmsg="Limpar todos as caixas de texto")
balao_buscar = tix.Balloon(frame_1)
balao_buscar.bind_widget(bt_buscar,balloonmsg="Filtra a tabela com os valores da entrada 'Nome'")
balao_novo = tix.Balloon(frame_1)
balao_novo.bind_widget(bt_novo,balloonmsg="Adiciona os valores digitados ao banco de dados")
balao_alterar = tix.Balloon(frame_1)
balao_alterar .bind_widget(bt_alterar,balloonmsg="Edita os valores de cadastro do cliente selecionado")
balao_apagar = tix.Balloon(frame_1)
balao_apagar .bind_widget(bt_apagar,balloonmsg="Deleta o cliente selecionado do banco de dados")

# Labels e Entrys

dashboard()

# codigo
lb_codigo = Label(frame_1,text="Código",fg='darkblue',bg='#99ABB5')
lb_codigo.place(relx=0.05,rely=0.05)

codigo_entry = Entry(frame_1)
codigo_entry.place(relx=0.05,rely=0.15,relwidth=0.08)

# nome

lb_nome = Label(frame_1,text="Nome",fg='darkblue',bg='#99ABB5')
lb_nome.place(relx=0.05,rely=0.35)

nome_entry = Entry(frame_1)
nome_entry.place(relx=0.05,rely=0.45,relwidth=0.5)

# telefone

lb_telefone = Label(frame_1,text="Telefone",fg='darkblue',bg='#99ABB5')
lb_telefone.place(relx=0.05,rely=0.6)

telefone_entry = Entry(frame_1)
telefone_entry.place(relx=0.05,rely=0.7,relwidth=0.2)

# cidade

lb_cidade = Label(frame_1,text="Cidade",fg='darkblue',bg='#99ABB5')
lb_cidade.place(relx=0.45,rely=0.60)

cidade_entry = Entry(frame_1)
cidade_entry.place(relx=0.45,rely=0.7,relwidth=0.3)

# estado

listEstados=[" ","AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS","MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC","SE","SP","TO"]

lb_estado = Label(frame_1,text="Estado",fg='darkblue',bg='#99ABB5')
lb_estado.place(relx=0.3,rely=0.60)

estado_entry=ttk.Combobox(frame_1,values=listEstados,state="readonly")
estado_entry.set(" ")
estado_entry.place(relx=0.3,rely=0.7,relwidth=0.1)

# assinante

vass=IntVar()

lb_ass = Label(frame_1,text="Assinante?",fg='darkblue',bg='#99ABB5')
lb_ass.place(relx=0.64,rely=0.35)

text1 = StringVar()

text1.set('Não')

cb_assin=Checkbutton(frame_1, textvariable = text1, variable = text1,
                          offvalue = 'Não',
                          onvalue = 'Sim',bg='#99ABB5')
cb_assin.place(relx=0.64,rely=0.45)

# treeview Cadastro
tv2=ttk.Treeview(frame_2,columns=('id','nome','fone','estado','cidade','assinante','data'),show='headings',height=10)
tv2.column('id',minwidth=0,width=30)
tv2.column('nome',minwidth=0,width=100)
tv2.column('fone',minwidth=0,width=115)
tv2.column('estado',minwidth=0,width=50)
tv2.column('cidade',minwidth=0,width=80)
tv2.column('assinante',minwidth=0,width=20)
tv2.column('data',minwidth=0,width=40)
tv2.heading('id',text='ID')
tv2.heading('nome',text='Nome')
tv2.heading('fone',text='Telefone')
tv2.heading('estado',text='Estado')
tv2.heading('cidade',text='Cidade')
tv2.heading('assinante',text='Ass.')
tv2.heading('data',text='Data')
tv2.place(relx=0.01,rely=0.01,relwidth=0.95,relheight=0.98)
scroll = Scrollbar(frame_2,orient='vertical')
tv2.configure(yscroll=scroll.set)
scroll.place(relx=0.96,rely=0.01,relwidth=0.04,relheight=0.98)
popular2()
tv2.bind("<Double-1>",duploClick)

# FIM
app.mainloop()


import unittest
from server.logic.database.edge_database import EdgeDatabase
from pymongo import MongoClient
from server.config import DATABASE_CONNECTION
from server.config import DATABASE_SCHEME_EDGE_RATING

class DatabaseTestCase(unittest.TestCase):
    def setUp(self):
        """
        Set up database class and instruct to use test database.
        """
        self.database = EdgeDatabase()
        self.database.__database_name__ = "servertest"

    def tearDown(self):
        """
        Wipe test database.
        """
        client = MongoClient(DATABASE_CONNECTION['host'], DATABASE_CONNECTION['port'])
        db = client[self.database.__database_name__]
        db.authenticate(DATABASE_CONNECTION['user'], DATABASE_CONNECTION['password'])
        collection = db[DATABASE_CONNECTION['collection_rating']]
        collection.drop()
        client.close()

    def test_save_new_and_add_rating(self):
        """
        Tests all functionality of save_new() and add_rating().
        """
        edge_from = 4
        edge_to = 5
        rating = 2

        # test save_new on clean database
        self.database.save_new(edge_from, edge_to)
        self.assertTrue(self.check_edge_in_database(edge_from, edge_to, 0, 0))

        # test add_rating on 1 item database
        self.database.add_rating(edge_from, edge_to, rating)
        self.assertTrue(self.check_edge_in_database(edge_from, edge_to, rating, 1))

        # test save_new doesn't overwrite
        self.database.save_new(edge_from, edge_to)
        self.assertTrue(self.check_edge_in_database(edge_from, edge_to, rating, 1))

        edge_from_v2 = 8
        edge_to_v2 = 6

        # test save_new on non-empty database
        self.database.save_new(edge_from_v2, edge_to_v2)
        self.assertTrue(self.check_edge_in_database(edge_from, edge_to, rating, 1))
        self.assertTrue(self.check_edge_in_database(edge_from_v2, edge_to_v2, 0, 0))

        edge_from_v3 = 6
        edge_to_v3 = 6
        rating_v3 = 45

        # test add_rating on multiple item database
        self.database.add_rating(edge_from_v3, edge_to_v3, rating_v3)
        self.assertTrue(self.check_edge_in_database(edge_from, edge_to, rating, 1))
        self.assertTrue(self.check_edge_in_database(edge_from_v2, edge_to_v2, 0, 0))
        self.assertTrue(self.check_edge_in_database(edge_from_v3, edge_to_v3, rating_v3, 1))

    def test_load_methods(self):
        """
        Tests all functionality for get_average_rating(), get_amount_voted(), get_edge().
        Assumes the save methods are working correctly.
        """
        edge_from_v1 = 4
        edge_to_v1 = 8
        rating_v1 = 6
        self.database.save_new(edge_from_v1, edge_to_v1)

        # test for zero edge
        self.assertEqual(0.0, self.database.get_average_rating(edge_from_v1, edge_to_v1))
        self.assertEqual(0, self.database.get_amount_voted(edge_from_v1, edge_to_v1))
        self.assertTupleEqual((0, 0, 0), self.database.get_edge(edge_from_v1, edge_to_v1))

        # test for non existing edge
        self.assertEqual(0.0, self.database.get_average_rating(987, 1564))
        self.assertEqual(0, self.database.get_amount_voted(987, 1564))
        self.assertIsNone(self.database.get_edge(987, 1564))

        self.database.add_rating(edge_from_v1, edge_to_v1, rating_v1)

        # test for 1 added rating
        self.assertEqual(rating_v1, self.database.get_average_rating(edge_from_v1, edge_to_v1))
        self.assertEqual(1, self.database.get_amount_voted(edge_from_v1, edge_to_v1))
        self.assertTupleEqual((rating_v1, 1, rating_v1), self.database.get_edge(edge_from_v1, edge_to_v1))

    def test_bulk_methods(self):
        """
        Tests all functionality for save_new_list(), add_rating_list(), get_all_edges().
        """
        edge_from_v1 = 6
        edge_to_v1 = 7
        rating_v1 = 9

        edge_from_v2 = 9
        edge_to_v2 = 4
        rating_v2 = 5

        list_v1 = []
        list_v1.append((edge_from_v1, edge_to_v1, 0, 0))
        list_v1.append((edge_from_v2, edge_to_v2, 0, 0))

        self.database.save_new_list(list_v1)

        # check both edges in database
        self.assertTrue(self.check_edge_in_database(edge_from_v1, edge_to_v1, 0, 0))
        self.assertTrue(self.check_edge_in_database(edge_from_v2, edge_to_v2, 0, 0))

        list_v2 = []
        list_v2.append((edge_from_v1, edge_to_v1, rating_v1))
        list_v2.append((edge_from_v2, edge_to_v2, rating_v2))

        self.database.add_rating_list(list_v2)

        # check both edges in database
        self.assertTrue(self.check_edge_in_database(edge_from_v1, edge_to_v1, rating_v1, 1))
        self.assertTrue(self.check_edge_in_database(edge_from_v2, edge_to_v2, rating_v2, 1))

        all_edges = self.database.get_all_edges()

        # check tuples returned
        self.assertTupleEqual((rating_v1, 1, rating_v1), all_edges[edge_from_v1, edge_to_v1])
        self.assertTupleEqual((rating_v2, 1, rating_v2), all_edges[edge_from_v2, edge_to_v2])

    def check_edge_in_database(self, edge_from, edge_to, total_rating, amount_voted):
        """
        Utility method for direct checking if an edge is in the database.
        :return True if an edge with the given parameters is in the database, False otherwise
        """
        client = MongoClient(DATABASE_CONNECTION['host'], DATABASE_CONNECTION['port'])
        db = client[self.database.__database_name__]
        db.authenticate(DATABASE_CONNECTION['user'], DATABASE_CONNECTION['password'])
        collection = db[DATABASE_CONNECTION['collection_rating']]

        query = {DATABASE_SCHEME_EDGE_RATING['edge_from']: edge_from,
                 DATABASE_SCHEME_EDGE_RATING['edge_to']: edge_to,
                 DATABASE_SCHEME_EDGE_RATING['total_rating']: total_rating,
                 DATABASE_SCHEME_EDGE_RATING['amount_voted']: amount_voted}

        result = collection.find_one(query)
        client.close()

        if result is None:
            # nothing is found
            return False
        else:
            return True


from turtle import Turtle
import random

sasuke = Turtle()

colours = ["CornflowerBlue", "DarkOrchid", "IndianRed", "DeepSkyBlue", "LightSeaGreen", "wheat", "SlateGray", "SeaGreen"]

def draw_shape(num_sides):
    angle = 360 / num_sides
    for _ in range(num_sides):
        sasuke.forward(100)
        sasuke.right(angle)

for shape_side_n in range(3, 10):
    sasuke.color(random.choice(colours))
    draw_shape(shape_side_n)


import time
from threading import Thread

import win32api
import win32con
from pyautogui import *

import keypress
import PathFinder
import ImageRecognition

bot_click_cords = {
    "right": (1020, 550),
    "left": (895, 550),
    "up": (955, 485),
    "down": (955, 615)
}
room_start_cords = {
    "dungeon": (30, 10)
}

class Bot:
    def __init__(self):
        self.bot_cords = [28, 11]
        self.status_t1 = False
        self.bot = None
        self.target_location = None
        self.last_move = None
        self.t1 = Thread(target=self.find_path)

    def move(self, direction):
        if direction == "right":
            self.bot_cords[0] = self.bot_cords[0] + 1
            keypress.press("d")

        if direction == "left":
            self.bot_cords[0] = self.bot_cords[0] - 1
            keypress.press("a")

        if direction == "up":
            self.bot_cords[1] = self.bot_cords[1] - 1
            keypress.press("w")

        if direction == "down":
            self.bot_cords[1] = self.bot_cords[1] + 1
            keypress.press("s")

    def click(self, direction):
        x = bot_click_cords[direction][0]
        y = bot_click_cords[direction][1]

        win32api.SetCursorPos((x, y))
        time.sleep(0.05)
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)  # Press mouse down
        time.sleep(0.05)  # Wait for the game to register the click
        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)  # Release mouse

    def attack(self, repeat):
        cords = self.target_location  # Enemy direction in coordinates
        print(f"Attacking: {cords}")
        for i in range(repeat):
            if cords[0] == 1:
                self.click("left")

            if cords[0] == -1:
                self.click("right")

            if cords[1] == 1:
                self.click("up")

            if cords[1] == -1:
                self.click("down")

            time.sleep(1.6)

    def start_t1(self):
        if self.t1.is_alive():
            pass
        else:
            print("starting t1")
            self.status_t1 = True
            self.t1 = Thread(target=self.find_path)
            self.t1.start()
            print("t1 started")

    def stop_t1(self):
        self.status_t1 = False

    def find_path(self):
        while self.status_t1:
            self.bot = PathFinder.Visualization()
            self.bot.main(True, "Dungeon.txt")
            self.status_t1 = False
        print("t1 stopped")

    def add_start(self, x, y):
        return self.bot.add_start(x, y)

    def add_end(self, x, y):
        return self.bot.add_end(x, y)

    def clear_path_and_load(self, file):
        self.bot.clear_path_and_load(file)

    def start_finding(self):
        return self.bot.start_finding()

    def get_path(self):
        return self.bot.get_path()

    def is_bot(self):
        return self.bot

    def move_bot_to_cords(self, cords):  # cords are path to enemy
        current_x, current_y = cords[0]  # Bot is currently here
        if len(cords) == 1:
            return 0
        if len(cords) == 2:  # If enemy is 1 block away from bot
            self.target_location = (cords[0][0] - cords[1][0], cords[0][1] - cords[1][1])  # Is direction where enemy is
            return 1

        cords.pop(0)  # Remove bot location from move list

        self.target_location = cords.pop(-1)  # Remove target location from cords and add it to target_location
        self.target_location = (cords[-1][0] - self.target_location[0], cords[-1][1] - self.target_location[1])
        print(f"Path: {cords} Target: {self.target_location}")
        for x, y in cords:
            print(f"Moving to {x, y}")
            if x < current_x:
                self.move("left")
                self.last_move = "left"

            if x > current_x:
                self.move("right")
                self.last_move = "right"

            if y < current_y:
                self.move("up")
                self.last_move = "up"

            if y > current_y:
                self.move("down")
                self.last_move = "down"

            current_x, current_y = x, y
            time.sleep(0.5)
        return 1

    def get_entity_cords(self):
        pixel_cords = ImageRecognition.get_targets()  # Get list of coordinates in pixels
        cords = [0, 0]
        last_distance = 999
        for x, y in pixel_cords:

            x += 22  # correcting image location to entity location
            y += 76

            x = 960 - x  # calculating distance to bot
            y = 550 - y  # old 580

            x = x / 65  # dividing by game block width to get coordinates
            y = y / 65

            x = round(x)   # Round values
            y = round(y)

            distance = abs(x) + abs(y)  # Calculating manhattan distance between 0, 0 and x, y

            if distance < last_distance:  # If distance is less than last distance, change current cords
                cords[0] = x
                cords[1] = y

            last_distance = distance

        cords[0] = self.bot_cords[0] - cords[0]  # Calculating real coordinates
        cords[1] = self.bot_cords[1] - cords[1]
        print(f"Closest enemy: {cords}")
        return cords

    def calculate_direction(self, cords):
        cords = (self.bot_cords[0] - cords[0], self.bot_cords[1] - cords[1])
        return cords

    def get_drops(self):
        drop_list = ImageRecognition.get_drops()
        return drop_list

    def collect_drops(self, drops):
        count = 0
        if len(drops) > 0:
            for x, y in drops:
                count += 1
                win32api.SetCursorPos((x + 5, y + 5))
                time.sleep(0.1)
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)  # Press mouse down
                time.sleep(0.1)  # Wait for the game to register the click
                win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)  # Release mouse
                if count > 15:
                    return

def run_bot():
    bot = Bot()
    bot.start_t1()

    run = True
    time.sleep(5)

    while run:
        finished = False
        find_target = True
        find_path = False
        move_to_target = False
        check_enemy = False
        attack = False
        collect = False

        while bot.is_bot():
            while find_target:
                print("Finding target...")
                entity_cords = bot.get_entity_cords()
                if len(entity_cords) > 0:
                    print(f"Found target: {entity_cords} and adding start and end location")
                    print(f"Bot cords: {bot.bot_cords}")
                    if bot.bot_cords[0] == entity_cords[0] and bot.bot_cords[1] == entity_cords[1]:
                        print(f"Making last move: {bot.last_move}")
                        if bot.last_move == "right":
                            bot.move("left")
                        if bot.last_move == "left":
                            bot.move("right")
                        if bot.last_move == "up":
                            bot.move("down")
                        if bot.last_move == "down":
                            bot.move("up")
                        continue
                    if bot.add_start(bot.bot_cords[0], bot.bot_cords[1]) == 1 and bot.add_end(entity_cords[0], entity_cords[1]) == 1:
                        print("Added start")
                        print("Added end")
                        find_path = True
                        find_target = False
                time.sleep(1)

            while find_path:
                print("Finding path to target")
                if bot.start_finding():
                    path = bot.get_path()
                    print(f"Found path: {path}")
                    if path:
                        move_to_target = True
                        find_path = False
                time.sleep(1)

            while move_to_target:
                print(f"move_to_target {path}")
                if bot.move_bot_to_cords(path) == 1:
                    bot.clear_path_and_load("Dungeon.txt")
                    check_enemy = True
                    move_to_target = False
                else:
                    find_target = True
                    move_to_target = False

            while check_enemy:
                print("Checking if enemy is still there")
                entity_cords = bot.get_entity_cords()
                print(f"Got cords {entity_cords}")
                if bot.calculate_direction(entity_cords) == bot.target_location:
                    print("Enemy is still there")
                    attack = True
                    check_enemy = False
                else:
                    print("Enemy is not there")
                    attack = False
                    collect = False
                    check_enemy = False

                    find_target = True

            while attack:
                print("Attacking enemy")
                bot.attack(2)
                collect = True
                attack = False

            while collect:
                drops = bot.get_drops()
                print(f"Collecting loot: {drops}")
                if drops:
                    bot.collect_drops(drops)
                finished = True
                collect = False

            if finished:
                print("Finished cycle")
                print("Waiting...")

                finished = False
                find_target = True
                time.sleep(2)

            print("Waiting...")
            time.sleep(1)

if __name__ == '__main__':
    run_bot()


from django.test import TestCase
from django.core.urlresolvers import reverse

from .models import Category
# Create your tests here.

class CategoryTest(TestCase):
	def create_category(self, category_id = "113", resource_uri = "https://www.eventbriteapi.com/v3/categories",
						name = "Arts", name_localized = "Arts", short_name = "Arts",
						short_name_localized = "Arts"):
		return Category.objects.create(category_id=category_id, resource_uri=resource_uri, name=name, name_localized=name_localized,
									   short_name=short_name, short_name_localized=short_name_localized)

	def test_category_creation(self):
		a = self.create_category()
		self.assertTrue(isinstance(a, Category))

	def test_category_list_view(self):
		a = self.create_category()
		url = reverse('show_cats')
		resp = self.client.get(url)

		self.assertEqual(resp.status_code, 200)
		self.assertIn(a.category_id, resp.content)
		self.assertIn(a.name, resp.content)