"""Test conversation chain and memory."""
import pytest
from langchain_core.memory import BaseMemory
from langchain_core.prompts.prompt import PromptTemplate

from langchain.chains.conversation.base import ConversationChain
from langchain.memory.buffer import ConversationBufferMemory
from langchain.memory.buffer_window import ConversationBufferWindowMemory
from langchain.memory.summary import ConversationSummaryMemory
from tests.unit_tests.llms.fake_llm import FakeLLM

def test_memory_ai_prefix() -> None:
    """Test that ai_prefix in the memory component works."""
    memory = ConversationBufferMemory(memory_key="foo", ai_prefix="Assistant")
    memory.save_context({"input": "bar"}, {"output": "foo"})
    assert memory.buffer == "Human: bar\nAssistant: foo"

def test_memory_human_prefix() -> None:
    """Test that human_prefix in the memory component works."""
    memory = ConversationBufferMemory(memory_key="foo", human_prefix="Friend")
    memory.save_context({"input": "bar"}, {"output": "foo"})
    assert memory.buffer == "Friend: bar\nAI: foo"

def test_conversation_chain_works() -> None:
    """Test that conversation chain works in basic setting."""
    llm = FakeLLM()
    prompt = PromptTemplate(input_variables=["foo", "bar"], template="{foo} {bar}")
    memory = ConversationBufferMemory(memory_key="foo")
    chain = ConversationChain(llm=llm, prompt=prompt, memory=memory, input_key="bar")
    chain.run("foo")

def test_conversation_chain_errors_bad_prompt() -> None:
    """Test that conversation chain raise error with bad prompt."""
    llm = FakeLLM()
    prompt = PromptTemplate(input_variables=[], template="nothing here")
    with pytest.raises(ValueError):
        ConversationChain(llm=llm, prompt=prompt)

def test_conversation_chain_errors_bad_variable() -> None:
    """Test that conversation chain raise error with bad variable."""
    llm = FakeLLM()
    prompt = PromptTemplate(input_variables=["foo"], template="{foo}")
    memory = ConversationBufferMemory(memory_key="foo")
    with pytest.raises(ValueError):
        ConversationChain(llm=llm, prompt=prompt, memory=memory, input_key="foo")

@pytest.mark.parametrize(
    "memory",
    [
        ConversationBufferMemory(memory_key="baz"),
        ConversationBufferWindowMemory(memory_key="baz"),
        ConversationSummaryMemory(llm=FakeLLM(), memory_key="baz"),
    ],
)
def test_conversation_memory(memory: BaseMemory) -> None:
    """Test basic conversation memory functionality."""
    # This is a good input because the input is not the same as baz.
    good_inputs = {"foo": "bar", "baz": "foo"}
    # This is a good output because these is one variable.
    good_outputs = {"bar": "foo"}
    memory.save_context(good_inputs, good_outputs)
    # This is a bad input because there are two variables that aren't the same as baz.
    bad_inputs = {"foo": "bar", "foo1": "bar"}
    with pytest.raises(ValueError):
        memory.save_context(bad_inputs, good_outputs)
    # This is a bad input because the only variable is the same as baz.
    bad_inputs = {"baz": "bar"}
    with pytest.raises(ValueError):
        memory.save_context(bad_inputs, good_outputs)
    # This is a bad output because it is empty.
    with pytest.raises(ValueError):
        memory.save_context(good_inputs, {})
    # This is a bad output because there are two keys.
    bad_outputs = {"foo": "bar", "foo1": "bar"}
    with pytest.raises(ValueError):
        memory.save_context(good_inputs, bad_outputs)

@pytest.mark.parametrize(
    "memory",
    [
        ConversationBufferMemory(memory_key="baz"),
        ConversationSummaryMemory(llm=FakeLLM(), memory_key="baz"),
        ConversationBufferWindowMemory(memory_key="baz"),
    ],
)
def test_clearing_conversation_memory(memory: BaseMemory) -> None:
    """Test clearing the conversation memory."""
    # This is a good input because the input is not the same as baz.
    good_inputs = {"foo": "bar", "baz": "foo"}
    # This is a good output because there is one variable.
    good_outputs = {"bar": "foo"}
    memory.save_context(good_inputs, good_outputs)

    memory.clear()
    assert memory.load_memory_variables({}) == {"baz": ""}


from PyQt5.QtWidgets import QTextBrowser
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt
import markdown

class Intro(QTextBrowser):
    def __init__(self):
        super().__init__()
        markdown_content = """
#### 请事先使用Qualcomm DbgCfgTool apk或是MTK DebugLogger apk软件录制log， 而且DbgCfgTool或是DebugLogger需要纪录到时间(例如: DbgCfgTool apk要将Log Output Format设定成threadtime)，否则此工具无法解析。
此工具是用来从log中撷取出每张照片带有特定关键字的log资讯。
适合使用的时机: 需要连续拍摄很多张照片，并分析某几张照片的AF对焦行为。例如: AF lab大量测试、外拍有拍摄大量照片的情况。
"""
        html = markdown.markdown(markdown_content)
        self.setHtml(html)
        self.setStyleSheet(
            """
            font-family:微软正黑体;
            font-weight: bold;
            font-size: 15pt;
            """
        )
        self.viewport().setCursor(QCursor(Qt.IBeamCursor))


#!/usr/bin/env python3
import cv2
import numpy as np
import math
from imutils import paths
import argparse
from skimage import exposure

#le a imagem
image = cv2.imread("imagem5.png")
original = image.copy()

#transforma pra escala de cinza
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imwrite("gray.png", gray)

#faz contrast_streatching
p2, p98 = np.percentile(gray, (2, 98))
img_rescale = exposure.rescale_intensity(gray, in_range=(p2, p98))

#binariza a imagem
thresh =  cv2.threshold(img_rescale, 0, 255,
    cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cv2.imwrite("thresh.png", thresh)

#engrossa? a imagem
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
erosion = cv2.erode(thresh, kernel,iterations = 2)
cv2.imwrite("erosion.png", erosion)

#afina a imagem
#erosion = cv2.erode(dilation,kernel,iterations = 2)
#cv2.imwrite("Erosion.png", erosion)

#engorssa? novamente
dilation = cv2.dilate(erosion,kernel,iterations = 2)
cv2.imwrite("Dilation.png", dilation)

#afina dnv
erosion = cv2.erode(dilation,kernel,iterations = 1)
cv2.imwrite("Erosionf.png", erosion)

mask = erosion
cv2.imwrite("mask.png", mask)

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3,3))
opening = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
close = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=2)

cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]

num = 0
idx = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    idx+=1
    new_img=image[y:y+h,x:x+w]
    #cv2.imwrite(str(num) + "_" + str(idx) + '.png', new_img)

area_min = 700
area_max = 6500
area_med = 2000
area_conexao = 2700
cromossomos = 0
x1= 0
x2= 0

#faz os contornos
for c in cnts:
    area = cv2.contourArea(c)
    if (area < area_max) and (area > area_min):
        cv2.drawContours(original, [c], -1, (36,255,12), 2)
        cromossomos += 1
        x2 +=1
        if area > area_conexao:
            print(area)
            print(area_med)
            cromossomos += math.ceil(area / area_med)
            print(math.ceil(area / area_med))
            x1+=1

print('Cromossomos: {}'.format(cromossomos))
print(x1)
print(x2)

cv2.imwrite("close.png", close)
cv2.imwrite("original.png", original)
cv2.imwrite("filename.png", close)

cv2.waitKey()
cv2.destroyAllWindows()


import subprocess, sys, time, tempfile, yaml, os, requests, pytest, signal, json, inspect, random
from PIL import Image

brave_processes = {}
DEFAULT_PORT=5000

@pytest.fixture #(scope="module")
def run_brave(config_file=None, port=None):
    def _run_brave(config_file=None, port=None):
        cmd = './brave.py'
        if (config_file):
            cmd += ' -c ' + config_file
        if port:
            cmd = 'PORT=%d %s' % (port, cmd)
        global brave_processes
        brave_processes[config_file] = subprocess.Popen(cmd, shell=True)
        time.sleep(1)
    yield _run_brave
    if port:
        print('Stopping Brave on port %d...' % port)
    else:
        print('Stopping Brave...')
    global brave_processes
    for config_file, process in brave_processes.items():
        process.send_signal(signal.SIGINT)
    brave_processes = {}

def api_get(path, port=DEFAULT_PORT, stream=False):
    url = 'http://localhost:%d%s' % (port, path)
    return requests.get(url, stream=stream)

def api_post(path, data, port=DEFAULT_PORT):
    url = 'http://localhost:%d%s' % (port, path)
    return requests.post(url, data=json.dumps(data))

def api_put(path, data, port=DEFAULT_PORT):
    url = 'http://localhost:%d%s' % (port, path)
    return requests.put(url, data=json.dumps(data))

def api_delete(path, port=DEFAULT_PORT):
    url = 'http://localhost:%d%s' % (port, path)
    return requests.delete(url)

brave_process = None

@pytest.fixture
def create_config_file():

    created_config_files = []

    def _create_config_file(config):
        fp = tempfile.NamedTemporaryFile(delete=False)
        fp.write(yaml.dump(config).encode())
        fp.close()
        created_config_files.append(fp)
        return fp

    yield _create_config_file
    for fp in created_config_files:
        os.unlink(fp.name)

def check_brave_is_running():
    global brave_processes
    for config_file, process in brave_processes.items():
        assert process.poll() == None

def check_return_value(return_value):
    global brave_processes
    for config_file, process in brave_processes.items():
        assert process.poll() == return_value

def assert_inputs_in_playing_state(json_response):
    if 'inputs' in json_response:
        for input in json_response['inputs']:
            assert input['state'] == 'PLAYING', 'Input in %s state, not PLAYING: %s' % (input['state'], str(input))

def assert_outputs_in_playing_state(json_response):
    if 'outputs' in json_response:
        for output in json_response['outputs']:
            assert output['state'] == 'PLAYING', 'Output in %s state, not PLAYING: %s' % (output['state'], str(output))

def assert_mixers_in_playing_state(json_response):
    if 'mixers' in json_response:
        for mixer in json_response['mixers']:
            assert mixer['state'] == 'PLAYING', 'Mixer in %s state, not PLAYING: %s' % (mixer['state'], str(mixer))

def assert_everything_in_playing_state(json_response=None, port=DEFAULT_PORT):
    if json_response is None:
        response = api_get('/api/all', port=port)
        json_response = response.json()

    assert_inputs_in_playing_state(json_response)
    assert_outputs_in_playing_state(json_response)
    assert_mixers_in_playing_state(json_response)

def delete_if_exists(name):
    try:
        os.unlink(name)
    except FileNotFoundError:
        pass

def test_directory():
    return os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))

temp_directory = None
def get_temp_directory():
    global temp_directory
    if not temp_directory:
        temp_directory = tempfile.TemporaryDirectory()
    return temp_directory.name

def create_output_image_location():
    img_file = get_temp_directory() + '/image' + str(random.randint(100000,200000)) + '.jpg'
    return img_file

OUTPUT_VIDEO_LOCATION = '/tmp/test.mp4'
def get_output_video_location():
    return OUTPUT_VIDEO_LOCATION

def create_output_video_location():
    global OUTPUT_VIDEO_LOCATION
    delete_if_exists(OUTPUT_VIDEO_LOCATION)
    return OUTPUT_VIDEO_LOCATION

def add_output(details, status_code=200):
    response = api_put('/api/outputs', details)
    assert response.status_code == status_code, 'Expected status code %s but got %s, body was:%s' % (status_code, response.status_code, response.json())
    time.sleep(0.5)
    return response.json()

def delete_output(id, expected_status_code=200):
    response = api_delete('/api/outputs/' + str(id))
    assert response.status_code == expected_status_code
    time.sleep(0.2)

def update_output(id, updates, expected_status_code=200):
    response = api_post('/api/outputs/' + str(id), updates)
    assert response.status_code == expected_status_code, 'Expected status code %s but got %s, body was:%s' % (expected_status_code, response.status_code, response.json())
    time.sleep(0.2)

def add_overlay(details, status_code=200):
    response = api_put('/api/overlays', details)
    assert response.status_code == status_code, 'Status code to make overlay was %d' % response.status_code

def delete_overlay(overlay_id):
    response = api_delete('/api/overlays/%d' % overlay_id)
    assert response.status_code == 200, 'Status code to delete overlay was %d' % response.status_code

def update_overlay(overlay_id, details, status_code=200):
    response = api_post('/api/overlays/' + str(overlay_id), details)
    assert response.status_code == status_code, 'Expected status code %s but got %s, body was:%s' % (status_code, response.status_code, response.text)

def set_mixer_state(mixer_id, state, status_code=200):
    response = api_post('/api/mixers/' + str(mixer_id), {'state': state})
    assert response.status_code == status_code, 'Expected status code %s but got %s, body was:%s' % (status_code, response.status_code, response.json())

def assert_outputs(outputs, check_playing_state=True):
    response = api_get('/api/all')
    assert response.status_code == 200
    if check_playing_state:
        assert_everything_in_playing_state(response.json())
    assert len(outputs) == len(response.json()['outputs'])

    # Chcek /api/outputs - should be the same
    response = api_get('/api/outputs')
    assert response.status_code == 200
    assert len(outputs) == len(response.json())

    for count, expected_output in enumerate(outputs):
        actual_output = response.json()[count]
        for (key, value) in expected_output.items():
            if key == 'props':
                for (props_key, props_value) in expected_output.items():
                    assert props_key in actual_output
                    assert props_value == actual_output[props_key], 'For output %s, for key %s, expected %s but got %s' % (expected_output['id'], props_key, props_value, actual_output[props_key])
            else:
                assert value == actual_output[key], 'Key "%s" expected to be "%s", but was "%s"' % (key, value, actual_output[key])

def assert_mixers(mixers):
    # Check /api/all
    response = api_get('/api/all')
    assert response.status_code == 200
    assert_everything_in_playing_state(response.json())
    assert len(mixers) == len(response.json()['mixers'])

    # Check /api/mixers - should be the same
    response = api_get('/api/mixers')
    assert response.status_code == 200
    assert len(mixers) == len(response.json())

    for count, expected_mixer in enumerate(mixers):
        actual_mixer = response.json()[count]
        for (key, value) in expected_mixer.items():
            if key == 'props':
                for (props_key, props_value) in expected_mixer.items():
                    assert props_key in actual_mixer
                    assert props_value == actual_mixer[props_key], 'For mixer %s, for key %s, expected %s but got %s' % (expected_mixer['id'], props_key, props_value, actual_mixer[props_key])
            else:
                assert value == actual_mixer[key], 'Key "%s" expected to be "%s", but was "%s"' % (key, value, actual_mixer[key])

def assert_overlays(overlays):

    # Chcek /api/all
    response = api_get('/api/all')
    assert response.status_code == 200
    assert_inputs_in_playing_state(response.json())
    assert_mixers_in_playing_state(response.json())
    assert len(overlays) == len(response.json()['overlays'])

    # Chcek /api/overlays - should be the same
    response = api_get('/api/overlays')
    assert response.status_code == 200
    assert len(overlays) == len(response.json())

    for count, expected_overlay in enumerate(overlays):
        actual_overlay = response.json()[count]
        for (key, value) in expected_overlay.items():
            assert key in actual_overlay
            assert value == actual_overlay[key], 'Key "%s" expected to be "%s", but was "%s"' % (key, value, actual_overlay[key])

def add_input(details, status_code=200):
    response = api_put('/api/inputs', details)
    assert response.status_code == status_code, 'Expected status code %s but got %s, body was:%s' % (status_code, response.status_code, response.json())
    return response.json()

def delete_input(id, expected_status_code=200):
    response = api_delete('/api/inputs/' + str(id))
    assert response.status_code == expected_status_code
    time.sleep(0.2)

def update_input(id, updates, expected_status_code=200, port=DEFAULT_PORT):
    response = api_post('/api/inputs/' + str(id), updates, port)
    assert response.status_code == expected_status_code
    time.sleep(0.2)

def add_mixer(details):
    response = api_put('/api/mixers', details)
    assert response.status_code == 200
    time.sleep(0.2)
    return response.json()

def update_mixer(id, updates, expected_status_code=200):
    response = api_post('/api/mixers/' + str(id), updates)
    assert response.status_code == expected_status_code
    time.sleep(0.2)

def assert_inputs(inputs, check_playing_state=True):
    response = api_get('/api/all')
    assert response.status_code == 200
    if check_playing_state:
        assert_everything_in_playing_state(response.json())
    assert len(inputs) == len(response.json()['inputs']), 'Expected %d inputs but got %d' % (len(inputs), len(response.json()['inputs']))

    # Test /api/inputs as well as /api/all:
    response = api_get('/api/inputs')
    assert response.status_code == 200
    assert len(inputs) == len(response.json())

    for count, expected_input in enumerate(inputs):
        actual_input = response.json()[count]
        for (key, value) in expected_input.items():
            assert key in actual_input
            if key == 'props':
                for (key, value) in expected_input.items():
                    assert key in actual_input
                    assert value == actual_input[key]
            else:
                assert value == actual_input[key], 'For key "%s", expected "%s" but got "%s"' % (key, value, actual_input[key])

def delete_mixer(id, expected_status_code=200):
    response = api_delete('/api/mixers/' + str(id))
    assert response.status_code == expected_status_code
    time.sleep(0.2)

def cut_to_source(uid, mixer_id, status_code=200, details={}):
    response = api_post('/api/mixers/%d/cut_to_source' % mixer_id, {**details, 'uid': uid})
    assert response.status_code == status_code, 'Whilst cutting to source %s, expected status code %s but got %s, body was:%s' % (uid, status_code, response.status_code, response.text)
    time.sleep(0.5)

def overlay_source(uid, mixer_id, status_code=200, details={}):
    response = api_post('/api/mixers/%d/overlay_source' % mixer_id, {**details, 'uid': uid})
    assert response.status_code == status_code, 'Whilst overlaying source %s, expected status code %s but got %s, body was:%s' % (uid, status_code, response.status_code, response.json())
    time.sleep(0.5)

def remove_source(uid, mixer_id, status_code=200):
    response = api_post('/api/mixers/1/remove_source', {'uid': uid})
    assert response.status_code == status_code, 'Whilst removing source %s, expected status code %s but got %s, body was:%s' % (uid, status_code, response.status_code, response.json())
    time.sleep(0.5)

def assert_image_file_color(output_image_location, expected_color):
    im = Image.open(output_image_location)
    assert_image_color(im, expected_color)

def get_raw_image_for_output(output_id, port=DEFAULT_PORT):
    response = api_get('/api/outputs/%d/body' % output_id, stream=True, port=port)
    assert response.status_code == 200
    im = Image.open(response.raw)
    return im

def assert_image_output_color(output_id, expected_color, port=DEFAULT_PORT):
    assert_image_color(get_raw_image_for_output(output_id, port), expected_color)

def restart_brave(params):
    response = api_post('/api/restart', params)
    assert response.status_code == 200, 'Invalid status code %d, response %s' % (response.status_code, response.text)
    print('Restart of Brave complete')

def assert_image_color(im, expected_color):
    '''
    Given an image and a color tuple, asserts the image is made up solely of that color.
    '''
    assert im.format == 'JPEG'
    assert im.size == (640, 360)
    assert im.mode == 'RGB'

    # Select a few pixels to check:
    dimensions = [(0,0), (100,0), (0,100), (100,100), (im.size[0]-1, im.size[1]-1)]
    for dimension in dimensions:
        assert_image_color_at_dimension(im, dimension, expected_color)

def assert_image_color_at_dimension(im, dimension, expected):
    # NAMES = ['red', 'green', 'blue']
    PERMITTED_RANGE=10
    actual = im.getpixel(dimension)
    p = actual
    for i in range(len(expected)):
        assert (expected[i]-PERMITTED_RANGE) < actual[i] < (expected[i]+PERMITTED_RANGE), \
            'Color was %s but expected %s (within range of %d)' % (actual, expected, PERMITTED_RANGE)


from setuptools import setup, Extension, find_packages

from Cython.Build import cythonize

ext_modules = [Extension("gripspy.util.checksum", ["gripspy/util/checksum.pyx"]),
               Extension("gripspy.util.coincidence", ["gripspy/util/coincidence.pyx"])]

setup(
    name='gripspy',
    version='0.1',
    author='Albert Y. Shih',
    author_email='ayshih@gmail.com',
    packages=find_packages(),
    package_data={'gripspy.science': ['asicmap/*.txt', 'cms/*.npz']},
    install_requires=['numpy',
                      'scipy',
                      'matplotlib',
                      'cython',
                      'scikit-image',
                      'astropy'],
    ext_modules = cythonize(ext_modules, annotate=True, compiler_directives={'embedsignature': True}),
    url='',
    license='See LICENSE.txt',
    description='',
    long_description=open('README.md').read(),
)


"""Endpoints for running models"""
import logging
from typing import List, Optional, Union, Type, Tuple

from accept_types import AcceptableType  # type: ignore
from fastapi import (
    APIRouter,
    BackgroundTasks,
    Body,
    Response,
    Request,
    Depends,
    UploadFile,
    File,
    Header,
    HTTPException,
)
import pandas as pd
from pydantic.types import UUID

from . import default_get_responses
from .. import models, utils
from ..auth import get_user_id
from ..storage import StorageInterface
from ..queuing import QueueManager

logger = logging.getLogger(__name__)
router = APIRouter()

job_links = {
    "Get Job": {
        "operationId": "get_job_jobs__job_id__get",
        "parameters": {"job_id": "$response.body#/object_id"},
    },
    "Delete Job": {
        "operationId": "delete_job_jobs__job_id__delete",
        "parameters": {"job_id": "$response.body#/object_id"},
    },
    "Get Job Status": {
        "operationId": "get_job_status_jobs__job_id__status_get",
        "parameters": {"job_id": "$response.body#/object_id"},
    },
    "Get Job Results": {
        "operationId": "get_job_results_jobs__job_id__results_get",
        "parameters": {"job_id": "$response.body#/object_id"},
    },
    "Compute Job": {
        "operationId": "compute_job_jobs__job_id__compute_post",
        "parameters": {"job_id": "$response.body#/object_id"},
    },
}

@router.post(
    "/",
    response_model=models.StoredObjectID,
    responses={
        **default_get_responses,
        409: {},
        201: {"links": job_links},
    },
    status_code=201,
)
async def create_job(
    response: Response,
    request: Request,
    job_parameters: models.JobParametersType = Body(
        ..., example=models.JOB_PARAMS_EXAMPLE
    ),
    storage: StorageInterface = Depends(StorageInterface),
) -> models.StoredObjectID:
    """Create a new job"""
    with storage.start_transaction() as st:
        system = st.get_system(job_parameters.system_id)
        job = models.Job(system_definition=system.definition, parameters=job_parameters)
        id_ = st.create_job(job)
        response.headers["Location"] = request.url_for("get_job", job_id=id_.object_id)
        return id_

@router.post("/check", responses={201: {}, 401: {}, 403: {}, 422: {}}, status_code=201)
async def check_job(
    job_parameters: models.JobParametersType = Body(
        ..., example=models.JOB_PARAMS_EXAMPLE
    ),
):
    pass

@router.get("/", response_model=List[models.StoredJob], responses=default_get_responses)
async def list_jobs(
    storage: StorageInterface = Depends(StorageInterface),
) -> List[models.StoredJob]:
    with storage.start_transaction() as st:
        return st.list_jobs()

@router.get(
    "/{job_id}",
    response_model=models.StoredJob,
    responses={**default_get_responses, 200: {"links": job_links}},
)
async def get_job(
    job_id: UUID, storage: StorageInterface = Depends(StorageInterface)
) -> models.StoredJob:
    with storage.start_transaction() as st:
        return st.get_job(job_id)

@router.get(
    "/{job_id}/status", response_model=models.JobStatus, responses=default_get_responses
)
async def get_job_status(
    job_id: UUID,
    storage: StorageInterface = Depends(StorageInterface),
    qm: QueueManager = Depends(QueueManager),
) -> models.JobStatus:
    with storage.start_transaction() as st:
        db_status = st.get_job_status(job_id)
    if db_status.status == "queued":
        q_status = qm.job_status(job_id)
        if q_status is not None:
            return q_status
    return db_status

@router.delete(
    "/{job_id}", status_code=204, responses={**default_get_responses, 204: {}}
)
async def delete_job(
    job_id: UUID,
    background_tasks: BackgroundTasks,
    storage: StorageInterface = Depends(StorageInterface),
    qm: QueueManager = Depends(QueueManager),
):
    with storage.start_transaction() as st:
        st.delete_job(job_id)
    background_tasks.add_task(qm.delete_job, job_id)

class ArrowResponse(Response):
    media_type = "application/vnd.apache.arrow.file"

class CSVResponse(Response):
    media_type = "text/csv"

def _get_return_type(
    accept: Optional[str],
) -> Tuple[Union[Type[CSVResponse], Type[ArrowResponse]], str]:
    if accept is None:
        accept = "*/*"
    type_ = AcceptableType(accept)

    if type_.matches("text/csv"):
        return CSVResponse, "text/csv"
    elif type_.matches("application/vnd.apache.arrow.file"):
        return ArrowResponse, "application/vnd.apache.arrow.file"
    else:
        raise HTTPException(
            status_code=406,
            detail="Only 'text/csv' or 'application/vnd.apache.arrow.file' acceptable",
        )

@router.get(
    "/{job_id}/data/{data_id}",
    response_class=CSVResponse,
    responses={
        **default_get_responses,
        406: {},
        204: {"description": "Data object exists but no data has been uploaded."},
        200: {
            "content": {
                "application/vnd.apache.arrow.file": {},
                "text/csv": {
                    "example": """time,performance
2020-01-01 00:00:00+00:00,0
2020-01-01 01:00:00+00:00,1
"""
                },
            },
            "description": "Return the data as an Apache Arrow file or a CSV.",
        },
    },
)
async def get_job_data(
    job_id: UUID,
    data_id: UUID,
    storage: StorageInterface = Depends(StorageInterface),
    accept: Optional[str] = Header(None),
) -> Union[CSVResponse, ArrowResponse, Response]:
    resp, meta_type = _get_return_type(accept)
    with storage.start_transaction() as st:
        meta, data = st.get_job_data(job_id, data_id)
    if not meta.definition.present or len(data) == 0:
        return Response(status_code=204)
    return _convert_job_data(data, meta.definition.data_format, meta_type, resp)

def _convert_job_data(data, data_format, requested_mimetype, response_class):
    if requested_mimetype == data_format:
        return response_class(data)
    elif (
        data_format == "application/vnd.apache.arrow.file"
        and requested_mimetype == "text/csv"
    ):
        try:
            df = utils.read_arrow(data)
        except HTTPException:
            logger.exception("Read arrow failed")
            raise HTTPException(
                status_code=500,
                detail=(
                    "Unable to convert data saved as Apache Arrow format, "
                    "try retrieving as application/vnd.apache.arrow.file and converting"
                ),
            )
        csv = df.to_csv(None, index=False)
        return response_class(csv)
    else:
        raise HTTPException(
            status_code=400,
            detail=(f"Unable to convert from {data_format} to {requested_mimetype}"),
        )

@router.post(
    "/{job_id}/data/{data_id}",
    responses={**default_get_responses, 415: {}},
    response_model=models.DataParsingStats,
)
async def post_job_data(
    job_id: UUID,
    data_id: UUID,
    file: UploadFile = File(
        ...,
        description=(
            "A single file in CSV format or Apache Arrow file format (default). "
            "Specify the Content-Type of the file as either 'text/csv' or "
            "'application/vnd.apache.arrow.file' as appropriate. Files with a "
            "Content-Type of 'application/octet-stream' (curl default) will be "
            "parsed as if they are Apache Arrow files."
        ),
    ),
    storage: StorageInterface = Depends(StorageInterface),
) -> models.DataParsingStats:
    """Upload specified data for the job. If the upload is of
    reference/original weather or performance, an attempt will be made to
    shift the data by whole years to match the time range specified for
    the job. Use this functionality with caution."""
    read_fnc = utils.verify_content_type(file.content_type)
    with storage.start_transaction() as st:
        job = st.get_job(job_id)
    try:
        data_obj = list(filter(lambda x: x.object_id == data_id, job.data_objects))[0]
    except IndexError:
        raise HTTPException(status_code=404, detail="Job data upload denied")
    expected_columns = data_obj.definition.data_columns
    df = read_fnc(file.file)
    await file.close()
    utils.validate_dataframe(df, expected_columns)
    if isinstance(
        job.definition.parameters, models.CompareMonthlyReferenceActualJobParameters
    ):
        adjusted_df, data_stats = _adjust_monthly_series(df)
    else:
        allow_time_shift = data_obj.definition.type in (
            models.JobDataTypeEnum.reference_weather,
            models.JobDataTypeEnum.reference_performance,
            models.JobDataTypeEnum.reference_performance_dc,
        )
        adjusted_df, data_stats = _adjust_standard_timeseries(
            job, df, expected_columns, allow_time_shift
        )
    arrow_bytes = utils.dump_arrow_bytes(utils.convert_to_arrow(adjusted_df))
    with storage.start_transaction() as st:
        st.add_job_data(
            job_id,
            data_id,
            file.filename,
            "application/vnd.apache.arrow.file",
            arrow_bytes,
        )
    return data_stats

def _adjust_monthly_series(
    df: pd.DataFrame,
) -> Tuple[pd.DataFrame, models.DataParsingStats]:
    df = utils.standardize_months(df)
    stats = models.DataParsingStats(
        number_of_expected_rows=12,
        number_of_extra_rows=0,
        number_of_missing_rows=0,
        data_periods=dict(expected="monthly", uploaded="monthly"),
        extra_times=[],
        missing_times=[],
        number_of_missing_values=[],
    )
    return df, stats

def _adjust_standard_timeseries(
    job: models.StoredJob,
    df: pd.DataFrame,
    expected_columns: List[str],
    allow_time_shift: bool,
) -> Tuple[pd.DataFrame, models.DataParsingStats]:
    try:
        uploaded_period = str(
            pd.tseries.frequencies.to_offset(  # type: ignore
                df["time"].diff().mode().iloc[0]  # type: ignore
            )
        )
    except Exception:  # pragma: no cover
        uploaded_period = "Unknown"
    time_params: models.JobTimeindex = (
        job.definition.parameters.time_parameters  # type: ignore
    )
    periods = models.DataPeriods(
        expected=str(time_params._time_range.freq),  # type: ignore
        uploaded=uploaded_period,
    )

    # will fail w/o time column
    df, extra_times, missing_times = utils.reindex_timeseries(
        df, time_params, allow_time_shift
    )
    percent_missing = len(missing_times) / len(df.index) * 100
    if percent_missing > 10:
        raise HTTPException(
            status_code=400,
            detail=(
                f"Over {percent_missing:0.2f}% of rows were missing from the "
                "data upload to conform to the job's stated time index."
            ),
        )
    dft = df[expected_columns].set_index("time")
    missing_vals = (
        dft.loc[dft.index.difference(missing_times)]  # type: ignore
        .isna()
        .sum(axis=0)
        .to_dict()
    )
    return (
        df,
        models.DataParsingStats(
            number_of_expected_rows=len(df.index),
            number_of_extra_rows=len(extra_times),
            number_of_missing_rows=len(missing_times),
            data_periods=periods,
            extra_times=extra_times,
            missing_times=missing_times,
            number_of_missing_values=missing_vals,
        ),
    )

@router.post(
    "/{job_id}/compute", status_code=202, responses={**default_get_responses, 202: {}}
)
async def compute_job(
    job_id: UUID,
    background_tasks: BackgroundTasks,
    storage: StorageInterface = Depends(StorageInterface),
    user: str = Depends(get_user_id),
    qm: QueueManager = Depends(QueueManager),
):
    with storage.start_transaction() as st:
        st.queue_job(job_id)
    background_tasks.add_task(qm.enqueue_job, job_id, user)

@router.get(
    "/{job_id}/results",
    responses=default_get_responses,
    response_model=List[models.StoredJobResultMetadata],
)
async def list_job_results(
    job_id: UUID,
    storage: StorageInterface = Depends(StorageInterface),
):
    with storage.start_transaction() as st:
        return st.list_job_results(job_id)

@router.get(
    "/{job_id}/results/{result_id}",
    responses={
        **default_get_responses,
        406: {},
        200: {
            "content": {
                "application/vnd.apache.arrow.file": {},
                "text/csv": {
                    "example": """time,performance
2020-01-01 00:00:00+00:00,0
2020-01-01 01:00:00+00:00,1
"""
                },
                "application/json": {},
            },
            "description": (
                "Return the job result as an Apache Arrow file or a CSV."
                " If an error occured, this will always return application/json"
                " with further details."
            ),
        },
    },
)
async def get_job_result(
    job_id: UUID,
    result_id: UUID,
    storage: StorageInterface = Depends(StorageInterface),
    accept: Optional[str] = Header(None),
) -> Union[CSVResponse, ArrowResponse, Response]:
    # once queing is figured out, this will need to also probably
    # return JSON describing any errors
    resp, meta_type = _get_return_type(accept)
    with storage.start_transaction() as st:
        meta, data = st.get_job_result(job_id, result_id)
    if meta.definition.type == models.JobResultTypeEnum.error:
        return Response(content=data, media_type=meta.definition.data_format)
    return _convert_job_data(data, meta.definition.data_format, meta_type, resp)


from rest_framework.decorators import api_view
from rest_framework.response import Response
from aidaijia_coupon.models import CouponCandidate, Coupon
from aidaijia_coupon.serializers import CouponCandidateSerializer, CouponSerializer

@api_view(['POST'])
def create_coupon(request):
    queryset = CouponCandidate.objects.filter(used=0)
    serializer = CouponCandidateSerializer(queryset, many=True)
    coupon_candidate_id = serializer.data[0].get("id")
    coupon_candidate_url = serializer.data[0].get("url")

    data = {"used": 1}
    queryset = CouponCandidate.objects.get(id=coupon_candidate_id)
    serializer = CouponCandidateSerializer(queryset, data=data)
    if serializer.is_valid():
        serializer.save()
    else:
        return Response(serializer.errors, status=400)

    data = {"url": coupon_candidate_url}
    serializer = CouponSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=201)
    else:
        return Response(serializer.errors, status=400)

@api_view(['GET'])
def retrieve_coupon(request,pk):
    queryset = Coupon.objects.get(id=pk)
    serializer = CouponSerializer(queryset)
    return Response(serializer.data)


#9. Среди натуральных чисел, которые были введены, найти наибольшее по сумме цифр. Вывести на экран это число и сумму его цифр.

# Блок-схема- алгоритм (открывать в google chrome) https://www.figma.com/file/4JKpq2355IVJeax2BC1sNl/HW2-Task9?node-id=0%3A1

def test():
    assert calculate(
        '1245 123 298 2353 223') == f'Число: 298, макс. сумма 19', 'incorrect'
    assert calculate(
        '6245 523 018 2343 293') == f'Число: 6245, макс. сумма 17', 'incorrect'
    assert calculate('1234') == f'Число: 1234, макс. сумма 10', 'incorrect'
    assert calculate('-1234') == f'\nОШИБКА: Введите числа', 'incorrect'
    assert calculate('ff') == f'\nОШИБКА: Введите числа', 'incorrect'
    assert calculate(' ') == f'\nОШИБКА: Введите числа', 'incorrect'
    assert calculate('') == f'\nОШИБКА: Введите числа', 'incorrect'
    print('Test: OK\n')

def calculate(value):
    num_dict={}
    sum_list=[]
    try:
        value=list(map(int, value.split(' ')))
        for l in value:
            sum_l = 0
            for s in str(l):
                sum_l += int(s)
            sum_list.append(sum_l)
            num_dict[sum_l]=l
        sum_list.sort()
        max_sum=sum_list[-1]
        return f'Число: {num_dict[max_sum]}, макс. сумма {max_sum}'
    except ValueError:
        return f'\nОШИБКА: Введите числа'

test()
print(calculate(input('Введите числа через пробел:\n')))


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

import urllib3
import json
import certifi
import shutil
import sys

def getPdfLinks(d):
    urls = []
    titles = []
    print("Getting links")
    for i in d:
        url = 'https://hacker-news.firebaseio.com/v0/item/' + str(i)  + '.json?print=pretty'
        r = http.request('GET', url)
        df=json.loads(r.data.decode('utf-8'))
        if '[pdf]' in df['title'].lower():
            url = df['url']
            urls.append(url)
            titles.append(df['title'])
            i=len(urls)
            print(str(i), "Title:", titles[i-1])#, "\n   Url:", urls[i-1], '\n')
    return urls,titles

def getIndices(alles=False):
    if alles:
        return [i for i in range(1,(len(titles)+1))]

    print("Give titles to fetch")
    nums = input().split(" ")

    if "all" in nums:
        nums2 = [i for i in range(1, len(titles)+1)]

        for f in nums:
            if str(f)[0] == '-':
                nums2.remove(int(f[1:]))
        return nums2
    return nums

if "--all" in sys.argv:
    alles=True
else:
    alles=False

http = urllib3.PoolManager(cert_reqs='CERT_REQUIRED', ca_certs=certifi.where())
r = http.request('GET', 'https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty')

d = json.loads(r.data.decode('utf-8'))

urls, titles = getPdfLinks(d)

nums = getIndices(alles)

for n in nums:
    try:
        print("Fetching pdf number", str(n))
        fn=('/docker/'+(titles[int(n)-1].replace('[pdf]', '').replace('?', '').replace('/', '').replace('\\', '').replace('"', '').replace('“', ''))+'.pdf').replace(' .', '.')
        req = http.request('GET', urls[int(n)-1], assert_same_host=False, preload_content=False,timeout=60)
        if req.status != 200:
            print("Problem with url", urls[int(n)-1], " got status", req.status)
            continue
        with open(fn, 'wb') as f:
           shutil.copyfileobj(req, f)
        req.release_conn()
    except Exception as e:
        print("Failed, title:", titles[int(n)-1], "url", urls[int(n)-1], "and error: ", e)


from django.urls import path

from apps.trabajoFinalApp import views

app_name = 'gestion'
urlpatterns = [
    path('alumno/', views.alumno, name='alumno'),
    path('alumno/proyecto/estado/', views.proyecto_create, name='proyecto_create'),
    path('alumno/proyecto/entrega/', views.proyecto_entrega, name='proyecto_entrega'),
    path('docente/', views.docente, name='docente'),
    path('cstf/', views.cstf, name='cstf'),
    path('cstf/evaluacion/', views.cstf_evaluacion, name='cstf_evaluacion'),
    path('tribunal/', views.tribunal, name='tribunal'),
    path('tribunal/evaluacion/ptf/', views.tribunal_evaluacion_ptf, name='tribunal_evaluacion_ptf'),
    path('tribunal/evaluacion/borrador/', views.tribunal_evaluacion_borrador, name='tribunal_evaluacion_borrador'),
    path('tribunal/evaluacion/final/', views.tribunal_evaluacion_final, name='tribunal_evaluacion_final'),
    path('administrador/', views.administrador, name='administrador'),
    #path('administrador/estadisticas', views.administrador_estadisticas, name='administrador_estadisticas'),
    #path('administrador/estadisticas/listado/proyectos', views.proyecto_lista, name='proyecto_lista'),
    path('administrador/alumno/alta/', views.administrador_alumno_alta, name='administrador_alumno_alta'),
    path('administrador/docente/alta/', views.administrador_docente_alta, name='administrador_docente_alta'),
    path('administrador/asesor/alta/', views.administrador_asesor_alta, name='administrador_asesor_alta'),
    path('administrador/cstf/nuevo/', views.registro_cstf, name='registro_cstf'),
    path('administrador/tribunal/nuevo/', views.tribunal_nuevo, name='tribunal_nuevo'),
    path('administrador/proyecto/nuevo/', views.administrador_proyecto_alta, name='administrador_proyecto_alta'),
    path('administrador/proyecto/modificar/', views.administrador_proyecto_modificar, name='administrador_proyecto_modificar'),
    path('administrador/integrante/alumno/', views.administrador_integrante_alumno, name='administrador_integrante_alumno'),
    path('administrador/integrante/director/', views.director_cambio, name='director_cambio'),
    path('administrador/movimientos/lista/', views.movimiento_lista, name='movimiento_lista'),
    path('administrador/movimientos/lista/detalle/', views.movimiento_detalle, name='movimiento_detalle'),
    path('administrador/estadisticas/', views.administrador_estadisticas, name='administrador_estadisticas'),
    path('administrador/estadisticas/lista_ptf/', views.proyecto_lista, name='proyecto_lista'),
    path('administrador/estadisticas/lista_tribunal/', views.tribunal_proyecto_lista, name='tribunal_proyecto_lista'),
]


import re
from nltk.stem import PorterStemmer

# Load vocabulary
vocabulary = []
with open('vocab.txt', 'r') as f:
    lines = f.readlines()
    vocabulary = [line[:-1] for line in lines]

def process_email(email_contents):
    """ preprocesses a the body of an email and returns a list of word_indices """
    global vocabulary

    # ----- Preprocess email -----

    # Lower case
    email_contents = email_contents.lower()

    # Remove all HTML
    html = re.compile(r'<[^<>]+>')
    email_contents = html.sub('', email_contents)

    # Handle numbers
    numbers = re.compile(r'[0-9]+')
    email_contents = numbers.sub('number', email_contents)

    # Handle URLs
    urls = re.compile(r'(http|https)://[^\s]*')
    email_contents = urls.sub('httpaddr', email_contents)

    # Email
    email_addresses = re.compile(r'[^\s]+@[^\s]+')
    email_contents = email_addresses.sub('emailaddr', email_contents)

    # Dollar sign
    dollar_sign = re.compile(r'[$]+')
    email_contents = dollar_sign.sub('dollar', email_contents)

    # ----- Tokenize email -----
    tokens = []
    words = re.split(r"\s|\@|\$|\/|\#|\.|\-|\:|\&|\*|\+|\=|\[|\]|\?|\!|\(|\)|\{|\}|\,|\'|\'|\"|\>|\_|\<|\;|\%", email_contents)

    stemmer = PorterStemmer()

    for word in words:
        # Remove nonalphanumeric characters
        alphanumeric = re.compile(r'[^a-zA-Z0-9]')
        word = alphanumeric.sub('', word)

        # Stem the word
        word = stemmer.stem(word)

        # Get index if it exists
        if word in vocabulary:
            tokens.append(vocabulary.index(word))

    return tokens

if __name__ == '__main__':
    # Run a test.
    # Note: the indexes are all 1 lower than the exercise, because Python is 0-indexed.
    with open('emailSample1.txt', 'r') as email:
        email_contents = email.read()
        tokens = process_email(email_contents)
        print(tokens)


import rospy

from control_msgs.msg import JointControllerState as JS
from sensor_msgs.msg import JointState
import message_filters

def callbackPan(data):
    js = JointState()
    js.header.stamp = rospy.Time.now();
    js.name = ["head_yaw_joint"]
    js.position = [data.process_value]

    pubPan.publish(js)

def callbackTilt(data):
    js = JointState()
    js.header.stamp = rospy.Time.now();
    js.name = ["head_pitch_joint"]
    js.position = [data.process_value]

    pubTilt.publish(js)
'''
def callback(panData, tiltData):
    print panData.current_pos
    js = JointState()
    js.header.stamp = rospy.Time.now()
    js.name = ["pan", "tilt"]
    js.position = [panData.current_pos, tiltData.current_pos]

    pub.publish(js)
'''
if __name__ == '__main__':
    rospy.init_node('tf_pantilt_listener')

 #   pan_sub = message_filters.Subscriber('/pan_controller/state', JS)
 #   tilt_sub = message_filters.Subscriber('tilt_controller/state', JS)
 #   ts = message_filters.TimeSynchronizer([pan_sub, tilt_sub],  0.05)
 #   ts.registerCallback(callback)
    rospy.Subscriber("/alice/pan_controller/state", JS, callbackPan)
    rospy.Subscriber("/alice/tilt_controller/state", JS, callbackTilt)
    pubPan = rospy.Publisher('/alice/panJointState', JointState, queue_size=1)
    pubTilt = rospy.Publisher('/alice/tiltJointState', JointState, queue_size=1)

    rospy.spin()


import time
import math
from functools import reduce
from logging import getLogger

logger = getLogger(__name__)

class Scheduler:

    def __init__(self, jobs):
        """
        Create a new Scheduler.

        >>> s = Scheduler([Job(1, max, 100, 200)])
        >>> for jobs in s:
        ...    time.sleep(s.tick_duration)

        :param jobs: Sequence of jobs to schedule
        """
        periodicities = {job.periodicity for job in jobs}
        self.tick_duration = reduce(lambda x, y: math.gcd(x, y),
                                    periodicities)
        self._ticks = self.find_minimum_ticks_required(self.tick_duration,
                                                       periodicities)
        self._jobs = jobs
        self._current_tick = 0
        logger.debug('Scheduler has {} ticks, each one is {} seconds'.
                     format(self._ticks, self.tick_duration))

    @staticmethod
    def find_minimum_ticks_required(tick_duration, periodicities):
        """Find the minimum number of ticks required to execute all jobs
        at once."""
        ticks = 1
        for periodicity in reversed(sorted(periodicities)):
            if ticks % periodicity != 0:
                ticks *= int(periodicity / tick_duration)
        return ticks

    def __iter__(self):
        return self

    def __next__(self):
        jobs = [job for job in self._jobs
                if ((self._current_tick * self.tick_duration)
                    % job.periodicity) == 0
                ]
        if jobs:
            logger.debug('Tick {}, scheduled {}'.
                         format(self._current_tick, jobs))
        self._current_tick += 1
        if self._current_tick >= self._ticks:
            self._current_tick = 0
        for job in jobs:
            job()
        return jobs

    def run(self):
        """Shorthand for iterating over all jobs forever.

        >>> print_time = lambda: print(time.time())
        >>> s = Scheduler([Job(1, print_time)])
        >>> s.run()
        1470146095.0748773
        1470146096.076028
        """
        for _ in self:
            time.sleep(self.tick_duration)

class Job:

    def __init__(self, periodicity, func, *func_args, **func_kwargs):
        """
        Create a new Job to be scheduled and run periodically.

        :param periodicity: Number of seconds to wait between job runs
        :param func: callable that perform the job action
        :param func_args: arguments of the callable
        :param func_kwargs: keyword arguments of the callable
        """
        if not callable(func):
            raise ValueError('func attribute must be callable')
        self.periodicity = periodicity
        self.func = func
        self.func_args = func_args
        self.func_kwargs = func_kwargs

    def __repr__(self):
        try:
            name = self.func.__name__
        except AttributeError:
            name = 'unknown'
        return '<Job {} every {} seconds>'.format(name,
                                                  self.periodicity)

    def __call__(self, *args, **kwargs):
        self.func(*self.func_args, **self.func_kwargs)


# Data Source
import yfinance as yf
# Data viz
import plotly.graph_objs as go
import streamlit as st

st.title("Crypto App Buy and Sell Decision")
crypto_mapping = {"DOGE": "DOGE-INR", "ETHEREUM": "ETH-INR", "BITCOIN": "BTC-INR", "KUSAMA": "KSM-INR", "BINANCE": "BNB-INR",
                  "LITECOIN": "LTC-INR", "FILECOIN": "FIL-INR", "SOLANA": "SOL1-INR", "BITTORRENT": "BTT1-INR", "TRON": "TRX-INR",
                  "RIPPLE": "XRP-INR", "VECHAIN": "VET-INR", "MATIC": "MATIC-INR", "CARDANO": "ADA-INR", "EOS": "EOS-INR", "YEARN.FINANCE": "YFI-INR",
                  "MAKER": "MKR-INR", "COMPOUND": "COMP-INR", "POLKADOT": "DOT1-INR", "SYNTHETIX": "SNX-INR", "AVALANCHE": "AVAX-INR",
                  "DECENTRALAND": "MANA-INR", "SIACOIN": "SC-INR", "ZILIQA": "ZIL-INR", "RAVEN": "RVN-INR", "ICP": "ICP1-INR", "CURVE": "CRV-INR",
                  "SUSHI": "SUSHI-INR", "COSMOS": "ATOM1-INR", "STELLAR": "XLM-INR", "AAVE": "AAVE-INR", "GRAPH": "GRT2-INR", "HEDERA": "HBAR-INR"}

crypto_list = [None, "DOGE", "ETHEREUM", "BITCOIN", "KUSAMA", "BINANCE", "LITECOIN", "FILECOIN", "SOLANA", "BITTORRENT", "TRON", "RIPPLE", "VECHAIN",
               "MATIC", "CARDANO", "EOS", "YEARN.FINANCE", "MAKER", "COMPOUND", "POLKADOT", "SYNTHETIX", "AVALANCHE", "DECENTRALAND", "SIACOIN", "ZILIQA",
               "RAVEN", "ICP", "CURVE", "SUSHI", "COSMOS", "STELLAR", "AAVE", "GRAPH", "HEDERA"]
selected_crypto = st.selectbox('Select Crypto', crypto_list)

if selected_crypto:
    crypto = crypto_mapping[selected_crypto]
    # Importing market data
    data = yf.download(tickers=crypto, period='8d', interval='90m')

    # Adding Moving average calculated field
    data['MA5'] = data['Close'].rolling(5).mean()
    data['MA20'] = data['Close'].rolling(20).mean()

    # declare figure
    fig = go.Figure()

    # Candlestick
    fig.add_trace(go.Candlestick(x=data.index,
                                 open=data['Open'],
                                 high=data['High'],
                                 low=data['Low'],
                                 close=data['Close'], name='market data'))

    # Add Moving average on the graph
    fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], line=dict(
        color='blue', width=1.5), name='Long Term MA'))
    fig.add_trace(go.Scatter(x=data.index, y=data['MA5'], line=dict(
        color='orange', width=1.5), name='Short Term MA'))

    # Updating X axis and graph
    # X-Axes
    fig.update_xaxes(
        rangeslider_visible=True,
        rangeselector=dict(
            buttons=list([
                dict(count=3, label="3d", step="day", stepmode="backward"),
                dict(count=5, label="5d", step="day", stepmode="backward"),
                dict(count=7, label="WTD", step="day", stepmode="todate"),
                dict(step="all")
            ])
        )
    )
    fig.update_layout(
        title={
            'text': crypto,
            'y': 0.9,
            'x': 0.5,
            'xanchor': 'center',
            'yanchor': 'top'})

    # Show
    # fig.show()
    st.plotly_chart(fig)


# importing the module
import pandas as pd
import pymongo

uri = "mongodb://localhost:27017/"
client = pymongo.MongoClient(uri)
mydb =  client["nsrit"]
fields = mydb["pandasData"]
print(client)
# reading the files
f1 = pd.read_excel('results_data\combined_cse3-1.xls',sheet_name='combined')
f2 = pd.read_excel('results_data\cse3-1 results.xls',sheet_name='cse3-1 results')
sd1 = pd.DataFrame()
sd2 = pd.DataFrame()
f3 = pd.DataFrame()
sd1 = f1[["Roll","Caste","SSC_Percentage","Inter_Percentage","Mobile_No.","Email"]].to_dict("records")
sd2 = f2[["Roll","Student_Name","Percentage","Total_Backlogs"]].to_dict("records")
# merging the files
#f3 = pd.merge(left = sd1,right = sd2, on = "Roll.No", how = "outer")
# creating a new file

fields.insert_many(sd1)
fields.insert_many(sd2)
print("success")
#f5.to_excel('Results.xls', index = False)
ans =fields.find_one()
print(ans)


from typing import Any, Callable, Optional

from reactivex import Observable, abc, typing
from reactivex.disposable import Disposable

def from_callback_(
    func: Callable[..., Callable[..., None]],
    mapper: Optional[typing.Mapper[Any, Any]] = None,
) -> Callable[[], Observable[Any]]:
    """Converts a callback function to an observable sequence.

    Args:
        func: Function with a callback as the last argument to
            convert to an Observable sequence.
        mapper: [Optional] A mapper which takes the arguments
            from the callback to produce a single item to yield on next.

    Returns:
        A function, when executed with the required arguments minus
        the callback, produces an Observable sequence with a single value of
        the arguments to the callback as a list.
    """

    def function(*args: Any) -> Observable[Any]:
        arguments = list(args)

        def subscribe(
            observer: abc.ObserverBase[Any],
            scheduler: Optional[abc.SchedulerBase] = None,
        ) -> abc.DisposableBase:
            def handler(*args: Any) -> None:
                results = list(args)
                if mapper:
                    try:
                        results = mapper(args)
                    except Exception as err:  # pylint: disable=broad-except
                        observer.on_error(err)
                        return

                    observer.on_next(results)
                else:
                    if len(results) <= 1:
                        observer.on_next(*results)
                    else:
                        observer.on_next(results)

                    observer.on_completed()

            arguments.append(handler)
            func(*arguments)
            return Disposable()

        return Observable(subscribe)

    return function

__all__ = ["from_callback_"]


'''Crie um programa onde 4 jogadores joguem um dado e tenham
resultados aleatórios. Guarde esses resultados em um dicionário. No final,
coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior
número no dado.'''
from random import randint
from time import sleep
from operator import itemgetter
dados = dict()
for i in range(1, 5):
	dados[i] = randint(1, 6)
print('-=' * 15)
for k, v in dados.items():
	print(f'Jogador{k} tirou {v}')
	sleep(1)
classificao = []
classificao = sorted(dados.items(), key=itemgetter(1), reverse= True)
print('*' * 30)
print(f'{" CAMPEÃO ":*^30}')
print('*' * 30)
for i, v in enumerate(classificao):
	print(f"{i + 1}º lugar jogador{v[0]} --> {v[1]} ******")
	sleep(0.5)
print('*' * 30)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct  8 14:47:44 2020

@author: mason
"""

import streamlit as st
import pickle
import xgboost
import pandas as pd
import numpy as np

with open('imdb_xgb.pickle','rb') as read_file:
    xgb = pickle.load(read_file)

with open('df_test.pickle','rb') as read_file:
    df_test = pickle.load(read_file)

with open('df_train.pickle','rb') as read_file:
    df_train = pickle.load(read_file)

with open('y_test.pickle','rb') as read_file:
    y_test = pickle.load(read_file)

with open('dir_means.pickle','rb') as read_file:
    dir_means = pickle.load(read_file)

with open('wri_means.pickle','rb') as read_file:
    wri_means = pickle.load(read_file)

with open('cast_means.pickle','rb') as read_file:
    cast_means = pickle.load(read_file)

st.title('Domestic Gross Revenue Predictor')

st.markdown('## Enter Movie Parameters:')

budget = st.number_input('Budget:',min_value=0, value=0, step=1)

runtime = st.number_input('Runtime (in minutes):', min_value=0, value=0, step=1)

days = st.number_input('Number of Days After Release Date:', min_value=0, value=360, step=1)

Ratings = ['R', 'PG-13', 'PG']
rating = st.selectbox('Select a Rating:', Ratings)

genres = ['Horror', 'Crime', 'Thriller', 'Sci-Fi', 'Romance', 'Action',
          'Fantasy', 'Adventure', 'Drama', 'Animation', 'Family']
gen = st.multiselect('Genre(s):', genres)

directors = st.multiselect('Directors:', dir_means['directors'])
writers = st.multiselect('Writers:', wri_means['writers'])
cast = st.multiselect('Cast:', cast_means['cast'])

try:
    director_ranks = []
    for director in directors:
        director_ranks.append(int(dir_means[dir_means['directors']==director].dir_rank))
        dir_rank = max(director_ranks)
except:
    None

try:
    writer_ranks = []
    for writer in writers:
        writer_ranks.append(int(wri_means[wri_means['writers']==writer].wri_rank))
        wri_rank = max(writer_ranks)
except:
    None

try:
    cast_ranks = []
    for actor in cast:
        cast_ranks.append(int(cast_means[cast_means['cast']==actor].cast_rank))
        cast_rank = max(cast_ranks)
except:
    None

st.markdown('## Domestic Gross Revenue Prediction:')
try:
    df = pd.DataFrame(columns=df_train.columns)
    df.loc[0] = [np.uint8(bool('Horror' in gen)),
                 np.int64(wri_rank),
                 np.int64(dir_rank),
                 np.float64(budget),
                 np.uint8(bool('Crime' in gen)),
                 np.uint8(bool('Thriller' in gen)),
                 np.uint8(bool('Sci-Fi' in gen)),
                 np.float64(runtime),
                 np.uint8(bool(rating == 'PG-13')),
                 np.uint8(bool('Romance' in gen)),
                 np.int64(cast_rank),
                 np.uint8(bool(rating == 'PG')),
                 np.uint8(bool('Action' in gen)),
                 np.uint8(bool('Fantasy' in gen)),
                 np.int64(days),
                 np.uint8(bool(rating == 'R')),
                 np.uint8(bool('Adventure' in gen)),
                 np.uint8(bool('Drama' in gen)),
                 np.uint8(bool('Animation' in gen)),
                 np.uint8(bool('Family' in gen))]

    df_merged = pd.concat([df_test, df], axis=0)

    predict = xgb.predict(df_merged)

    gross = (np.exp(predict[-1])*100000).round(2)
    st.header(str(gross))
except:
    st.write('')


import threading
import logging
from queue import Queue, Full
from .match import Matcher
from .notification import Message

class Checker:
    def __init__(self, name, expr, path, interval, threshold, users, counter, notification):
        self.name = name
        self.expr = expr
        self.path = path
        self.interval = interval
        self.threshold = threshold
        self.users = users
        self.counter = counter
        self.__event = threading.Event()
        self.notification = notification
        self.matcher = Matcher(name, expr)

    def check(self):
        while not self.__event.is_set():
            self.__event.wait(self.interval * 60)
            count = self.counter.get(name=self.name)
            self.counter.clean(self.name)
            if count >= self.threshold[0]:
                if count < self.threshold[1] or self.threshold[1] < 0:
                    self.notify('{0} matched {1} times in {2}min'.format(self.name, count, self.interval))

    def start(self):
        threading.Thread(self.check, name='checker-{0}'.format(self.name)).start()

    def notify(self, count):
        for user in self.users:
            message = Message(user, self.name, self.path, count)
            self.notification.notify(message)

    def stop(self):
        self.__event.set()

class CheckerChain:
    def __init__(self, queue, counter):
        self.queue = queue
        self.counter = counter
        self.checkers = {}
        self.queues = {}
        self.events = {}
        self.line = None
        self.__event = threading.Event()
        self.__cond = threading.Condition()

    def _match(self, checker):
        while not self.events[checker.name].is_set():
            line = self.queues[checker.name]
            if self.checkers[checker.name].matcher.match(line):
                self.counter.inc(checker.name)

    def match(self, checker):
        queue = Queue()
        self.queues[checker.name] = queue
        threading.Thread(target=self._match, args=(checker, )).start()
        while not self.events[checker.name].is_set():
            with self.__cond:
                self.__cond.wait()
                try:
                    queue.put_nowait(self.line)
                except Full:
                    logging.error("match queue for {0} full".format(checker.name))

    def add_checker(self, checker):
        self.checkers[checker.name] = checker
        checker.start()
        event = threading.Event()
        self.events[checker.name] = event
        threading.Thread(target=self.match, args=(checker, )).start()

    def remove_checker(self, name):
        if name in self.events.keys():
            self.events[name].set()
            self.checkers[name].stop()
            self.events.pop(name)
            self.checkers.pop(name)

    def start(self):
        while not self.__event.is_set():
            self.line = self.queue.get()
            self.__cond.notify_all()

    def stop(self):
        self.__event.set()
        for k, e in self.events.values():
            e.set()
            self.checkers[k].stop()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 14 11:33:36 2020

@author: sadhana-ravikumar
"""
import nibabel as nib
import sys
sys.path.append('./utilities')
import preprocess_data as p
import numpy as np

def computeGeneralizedDSC(gt, seg):

     gt_seg = gt[gt > 0]
     myseg = seg[gt > 0]

     gdsc = 100*(sum(gt_seg == myseg)/ len(gt_seg))

     return gdsc

root_dir = "/home/sadhana-ravikumar/Documents/Sadhana/exvivo_cortex_unet"
train_val_csv = root_dir + "/data_csv/split.csv"
exp_dir = 'Experiment_060120201_updateddata/'
val_dir = root_dir + '/validation_output/' + exp_dir

input_dir = root_dir + '/inputs/'

image_dataset = p.ImageDataset(csv_file = train_val_csv)

dsc_list = []
for i in range(1,len(image_dataset)):
        sample = image_dataset[i]
        if(sample['type'] == 'test'):

            image_id = sample['id']
            seg = sample['seg']
            print(image_id)
            predicted_segfile = val_dir + 'seg_' + str(image_id) + ".0.nii.gz"
            pred_seg =  nib.load(predicted_segfile)
            pred_seg = pred_seg.get_fdata().astype(np.float32)

            dsc = computeGeneralizedDSC(seg,pred_seg)
            dsc_list.append(dsc)

print("Average srlm validation accuracy is ", sum(dsc_list)/len(dsc_list))
print(dsc_list)
print("Standard deviation is ", np.std(dsc_list))


import numpy as np
import pandas as pd
from tabulate import tabulate
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style

from mpl_finance import candlestick_ochl as candlestick

style.use('dark_background')

# BALANCE_COLOR = ['#ffa929', '#ff297f', '#7fff29', '#297fff']
BUY_N_HOLD_COLOR = '#297fff'
BOT_COLOR = '#ffaa00'
BALANCE_COLOR = '#44a769'
UP_COLOR = '#297FFF'
DOWN_COLOR = '#FFAA00'
VOLUME_CHART_HEIGHT = 0.33
UP_TEXT_COLOR = '#00b909'
DOWN_TEXT_COLOR = '#c60606'

def date2num(date):
    converter = mdates.datestr2num(date)
    return converter

class GraphGenerator:
    """A stock trading visualization using matplotlib made to render OpenAI gym environments"""

    def __init__(self, assets, currency, granularity, datapoints, df_complete, df_features, variables):
        self.assets = assets
        self.currency = currency
        self.granularity = granularity
        self.datapoints = datapoints
        self.df_complete = df_complete
        self.df_features = df_features
        self.variables = variables
        self.candlestick_width = variables['candlestick_width'].get(
            granularity, 1)
        self.date_values = self.df_complete[self.assets[0]]['Date'].values

        # ? benchmark strats
        self.buy_and_holds = np.zeros(len(df_complete[assets[0]]['Date']))
        self.net_worths = np.zeros(len(df_complete[assets[0]]['Date']))

        self.buy_and_holds[0] = variables['initial_account_balance']
        self.net_worths[0] = variables['initial_account_balance']

        fig = plt.figure()
        fig.suptitle('T-1000', fontsize=18)

        self.price_axs = {}
        self.volume_axs = {}
        rowspan = len(assets)
        colspan = 4  # ! idk
        canvas_x_size = len(assets) * rowspan
        canvas_y_size = len(assets) + 2  # ? + balance and net_worth

        self.net_worth_ax = plt.subplot2grid(
            (canvas_x_size, canvas_y_size), (0, colspan), rowspan=4, colspan=1)
        self.net_worth_ax.yaxis.tick_right()

        self.balance_ax = plt.subplot2grid(
            (canvas_x_size, canvas_y_size), (5, colspan), rowspan=4, colspan=1)
        self.balance_ax.yaxis.tick_right()

        for index, asset in enumerate(assets):
            self.price_axs[asset] = plt.subplot2grid((canvas_x_size, canvas_y_size), (len(
                assets) * index, 0), rowspan=rowspan, colspan=colspan)
            self.volume_axs[asset] = self.price_axs[asset].twinx()
            self.price_axs[asset].yaxis.tick_right()

        plt.subplots_adjust(left=0.11, bottom=0.24,
                            right=0.90, top=0.90, wspace=0.2, hspace=0)

        # ? Show the graph without blocking the rest of the program
        plt.show(block=False)

    def _render_net_worth(self, current_step, net_worth, buy_and_hold, step_range, dates):
        # Clear the frame rendered last step
        self.net_worth_ax.clear()
        # compute performance
        abs_diff = net_worth - buy_and_hold
        avg = (net_worth + buy_and_hold) / 2
        percentage_diff = abs_diff / avg * 100
        # print performance
        self.net_worth_ax.text(0.95, 0.01, '{0:.2f}%'.format(percentage_diff),
                               verticalalignment='bottom',
                               horizontalalignment='right',
                               transform=self.net_worth_ax.transAxes,
                               color='green' if percentage_diff > 0 else 'red', fontsize=15)
        x = np.arange(2)
        y = [buy_and_hold, net_worth]
        self.net_worth_ax.bar(x, y, color=[BUY_N_HOLD_COLOR, BOT_COLOR])
        self.net_worth_ax.set_title(
            "Net Worth ({})".format(self.currency))
        self.net_worth_ax.set_xticklabels(('', 'HODL', '', 'T-1000'))

        # Annotate the current net worth on the net worth graph
        self.net_worth_ax.annotate("{0:.2f}".format(buy_and_hold),
                                   xy=(0, buy_and_hold),
                                   xytext=(0, buy_and_hold),
                                   bbox=dict(boxstyle='round',
                                             fc='w', ec='k', lw=1),
                                   color="black",
                                   fontsize="small")
        self.net_worth_ax.annotate("{0:.2f}".format(net_worth),
                                   xy=(1, net_worth),
                                   xytext=(1, net_worth),
                                   bbox=dict(boxstyle='round',
                                             fc='w', ec='k', lw=1),
                                   color="black",
                                   fontsize="small")

    def _render_balance(self, shares_held, balance):
        # Clear the frame rendered last step
        self.balance_ax.clear()
        x = np.arange(len(self.assets) + 1)
        y = [shares_held[asset] for asset in self.assets]
        y.append(balance)
        self.balance_ax.bar(x, y, color=BALANCE_COLOR)
        self.balance_ax.set_title("Balance")
        labels = ('',)
        for asset in self.assets:
            labels += (asset, )
        labels += (self.currency, )
        self.balance_ax.set_xticklabels(labels)

        for index, asset in enumerate(self.assets):
            self.balance_ax.annotate("{0:.3f}".format(shares_held[asset]), xy=(index, shares_held[asset]), xytext=(
                index, shares_held[asset]), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color='black', fontsize='small')
        self.balance_ax.annotate("{0:.3f}".format(balance),
                                 xy=(len(self.assets), balance),
                                 xytext=(len(self.assets), balance),
                                 bbox=dict(boxstyle='round',
                                           fc='w', ec='k', lw=1),
                                 color="black",
                                 fontsize="small")

    def _render_price(self, current_step, net_worth, dates, step_range):
        candlesticks = {}
        last_dates = {}
        last_closes = {}
        last_highs = {}
        y_limit = {}
        for index, asset in enumerate(self.assets):
            if index == 0:
                self.price_axs[asset].set_title(
                    'Candlesticks')  # ? this can go out?
            self.price_axs[asset].clear()
            candlesticks[asset] = zip(dates,
                                      self.df_features[asset]['open'].values[step_range],
                                      self.df_features[asset]['close'].values[step_range],
                                      self.df_features[asset]['high'].values[step_range],
                                      self.df_features[asset]['low'].values[step_range])
            candlestick(self.price_axs[asset],
                        candlesticks[asset],
                        width=self.candlestick_width,
                        colorup=UP_COLOR,
                        colordown=DOWN_COLOR)
            last_dates[asset] = date2num(
                self.df_complete[asset]['Date'].values[current_step])
            last_closes[asset] = self.df_features[asset]['close'].values[current_step]
            last_highs[asset] = self.df_features[asset]['high'].values[current_step]
            self.price_axs[asset].annotate(s="{0:.4f}".format(last_closes[asset]), xy=(
                last_dates[asset], last_closes[asset]), xytext=(last_dates[asset], last_highs[asset]), bbox=dict(boxstyle='round', fc='w', ec='k', lw=1), color='black', fontsize='small')
            y_limit[asset] = self.price_axs[asset].get_ylim()
            self.price_axs[asset].set_ylim(y_limit[asset][0] - (
                y_limit[asset][1] - y_limit[asset][0]) * VOLUME_CHART_HEIGHT, y_limit[asset][1])
            self.price_axs[asset].set_ylabel(
                '{}/{}'.format(asset, self.currency))

    def _render_volume(self, current_step, net_worth, dates, step_range):
        volumes = {}
        pos = {}
        neg = {}
        for asset in self.assets:
            self.volume_axs[asset].clear()
            volumes[asset] = np.array(self.df_complete[asset]['volumefrom'].values[step_range])
            pos[asset] = self.df_complete[asset]['open'].values[step_range] - self.df_complete[asset]['close'].values[step_range] < 0
            neg[asset] = self.df_complete[asset]['open'].values[step_range] - self.df_complete[asset]['close'].values[step_range] > 0
            self.volume_axs[asset].bar(dates[pos[asset]], volumes[asset][pos[asset]], color=UP_COLOR, alpha=0.4, width=self.candlestick_width, align='center')
            self.volume_axs[asset].bar(dates[neg[asset]], volumes[asset][neg[asset]], color=DOWN_COLOR, alpha=0.4, width=self.candlestick_width, align='center')
            # > Cap volume axis height below price chart and hide ticks
            self.volume_axs[asset].set_ylim(0, max(volumes[asset]) / VOLUME_CHART_HEIGHT)
            self.volume_axs[asset].yaxis.set_ticks([])

    def _render_trades(self, current_step, trades, step_range):
        for asset in self.assets:
            for trade in trades[asset]:
                if trade['step'] in step_range:
                    date = date2num(self.df_complete[asset]['Date'].values[trade['step']])
                    high = self.df_complete[asset]['high'].values[trade['step']]
                    low = self.df_complete[asset]['low'].values[trade['step']]
                    if trade['type'] == 'buy':
                        high_low = low
                        color = UP_TEXT_COLOR
                        marker = '^'
                    else:
                        high_low = high
                        color = DOWN_TEXT_COLOR
                        marker = 'v'
                    total = '{0:.5f}'.format(trade['total'])
                    self.price_axs[asset].scatter(date, high_low, color=color, marker=marker, s=50)
                    self.price_axs[asset].annotate('{} {}'.format(total, self.currency), xy=(date, high_low), xytext=(date, high_low), color=color, fontsize=8)

    def _print_trades_overview(self, balance, net_worth, shares_held, trades, buy_and_hold):
        print('\nTrades')
        for asset in self.assets:
            df = pd.DataFrame(trades[asset])
            if 'step' in df.columns.tolist():
                df[asset] = self.df_complete[asset]['Date'].values[df['step'] -1]
                df['amount ({})'.format(asset)] = df['amount']
                df['price ({})'.format(self.currency)] = df['price']
                df['total ({})'.format(self.currency)] = df['total']
                df.set_index(asset, inplace=True)
                df.drop(['step', 'total', 'price', 'amount'], axis=1, inplace=True)
                x = tabulate(df, headers='keys', tablefmt='psql')
                print(asset)
                print(x)
        shares_held[self.currency] = balance
        df_shares_held = pd.DataFrame(shares_held, index=[0])
        x_shares = tabulate(df_shares_held, headers='keys', tablefmt='psql')

        abs_diff = net_worth - buy_and_hold
        avg = (net_worth + buy_and_hold) / 2
        percentage_diff = abs_diff / avg * 100

        print('\nPortfolio')
        print(x_shares)
        print('Net Worth: {} {} ({:.3f}%)'.format(net_worth, self.currency, percentage_diff))
        print('Buy \'n hold:', buy_and_hold, self.currency)
        print('\n')

    def render(self, current_step, net_worth, buy_and_hold, trades, shares_held, balance, window_size):
        self.net_worths[current_step] = net_worth
        self.buy_and_holds[current_step] = buy_and_hold

        window_start = max(current_step - window_size, 0)
        step_range = range(window_start, current_step + 1)

        # Format dates as timestamps, necessary for candlestick graph
        dates = np.array([date2num(x)
                          for x in self.df_complete[self.assets[0]]['Date'].values[step_range]])

        self._render_net_worth(current_step, net_worth,
                               buy_and_hold, step_range, dates)

        self._render_balance(shares_held, balance)
        self._render_price(current_step, net_worth, dates, step_range)
        self._render_volume(current_step, net_worth, dates, step_range)
        self._render_trades(current_step, trades, step_range)

        # Format the date ticks to be more easily read
        last_asset_index = len(self.assets) - 1
        for index, asset in enumerate(self.assets):
            self.price_axs[asset].set_xticklabels(
                self.df_complete[asset]['Date'].values[step_range], rotation=45, horizontalalignment='right')

        # Hide duplicate net worth date labels
            if not index == last_asset_index:
                plt.setp(
                    self.volume_axs[asset].get_xticklabels(), visible=False)
                plt.setp(
                    self.price_axs[asset].get_xticklabels(), visible=False)

        # Necessary to view frames before they are unrendered
        plt.pause(0.001)

        # print trades info on console
        last_step = current_step >= len(self.date_values) - 1
        if last_step:
            self._print_trades_overview(balance, net_worth, shares_held, trades, buy_and_hold)

    def close(self):
        plt.close()


from game.models import Round
from django.utils import timezone

def status_check():
    rounds = Round.objects.filter(completed=False, update_status__gte=0)

    for r in rounds:
        hours_ago = (timezone.now() - r.update_status_date).total_seconds()/3600

        if r.update_status == 0 and hours_ago >= 24:
            #Send reminder and set status to 1 (reminder sent)
            r.send_reminder_email()
        elif r.update_status == 1 and hours_ago >= 24:
            #Send request and set status to 24
            r.send_request()
        elif r.update_status == 2 and hours_ago >= 24:
            #Set status to -2 (expired) and send final game out
            r.completed = True
            r.set_status(-2)
            r.save()

            r.game.completed = True
            r.game.save()
            r.game.send_round_over_email(expired=True)
    return(None)


#!/usr/bin/env python3

import sys
import os
from os.path import expanduser
home = os.path.expanduser("~")
if os.path.isdir(home + "/.local/lib/python3.10/site-packages/je_auto_control") == False:
	os.system("sudo apt install python3-pip -y && pip install je_auto_control")

from time import sleep
from pprint import pprint
from je_auto_control import keyboard_keys_table
from je_auto_control import type_keyboard

# Check KB table
# pprint(keyboard_keys_table)

# Press Super key & type hp.com
n = 0
cycles = input("Test cycles: ")
os.system("touch ~/Desktop/KB_Test.txt && open ~/Desktop/KB_Test.txt")
while True:
    if n < int(cycles):
        sleep(1)
        type_keyboard("win")
        sleep(1.5)
        type_keyboard("win")
        sleep(1.5)
        type_keyboard("h")
        sleep(0.5)
        type_keyboard("p")
        sleep(0.5)
        type_keyboard("decimal")
        sleep(0.5)
        type_keyboard("c")
        sleep(0.5)
        type_keyboard("o")
        sleep(0.5)
        type_keyboard("m")
        sleep(0.5)
        type_keyboard("return")
        sleep(1)
        n += 1
    else:
        break
print("\n***Test finished***\n")


import re
from functools import reduce
import operator

lines = [l.strip() for l in open('input16').readlines()]

rg = r'^(\w+\s?\w+):\s(\d+)-(\d+)\sor\s(\d+)-(\d+)$'

rules = {}
for idx, l in enumerate(lines):
    if l == '':
        break

    groups = re.match(rg, l).groups()
    field = groups[0]
    start_1, end_1, start_2, end_2 = (int(i) for i in groups[1:])

    rules[field] = [(start_1, end_1), (start_2, end_2)]

sorted_ranges = sorted([item for val in rules.values() for item in val])
union_range = []
for start, end in sorted_ranges:
    if union_range and union_range[-1][1] >= start:
        union_range[-1][1] = max(union_range[-1][1], end)
    else:
        union_range.append([start, end])

idx += 2
my_ticket = [int(i) for i in lines[idx].split(',')]

idx += 3
error_rate = 0
nearby_tickets = []
for l in lines[idx:]:
    ticket = [int(i) for i in l.split(',')]
    valid = True
    for val in ticket:
        if not any([
            val in range(start, end + 1) for (start, end) in union_range
        ]):
            error_rate += val
            valid = False
            break
    if valid:
        nearby_tickets.append(ticket)

print('Part 1:', error_rate)

fields = [set(rules.keys()) for _ in rules.keys()]
for ticket in nearby_tickets:
    for idx, val in enumerate(ticket):
        applicable_rules = set()
        for rule_name in rules.keys():
            if any([
                val in range(start, end + 1) for (start, end) in rules[rule_name]
            ]):
                applicable_rules.add(rule_name)
        fields[idx] = fields[idx].intersection(applicable_rules)

single_element_fields = set()
while any([len(item) > 1 for item in fields]):
    for candidate in fields:
        if len(candidate) > 1:
            candidate -= single_element_fields
        else:
            single_element_fields.add(next(iter(candidate)))

output = reduce(
    operator.mul,
    [my_ticket[idx] for idx, item in enumerate(fields) if 'departure' in next(iter(item))]
)
print('Part 2:', output)