# from flask-redis
# https://github.com/underyx/flask-redis

try:
    import redis
except ImportError:
    # We can allow custom provider only usage without redis-py being installed
    redis = None

__all__ = ('FlaskRedis', )
__version__ = '0.5.0'

class FlaskRedis(object):

    def __init__(self, app=None, strict=True, config_prefix="REDIS", **kwargs):
        self.provider_class = redis.StrictRedis if strict else redis.Redis
        self.provider_kwargs = kwargs
        self.config_prefix = config_prefix

        self.config_uri = '{}_URI'.format(config_prefix)
        self.config_binds = '{}_BINDS'.format(config_prefix)
        # 保存 REDIS_URI 中设定的那个连接
        self._redis_client = None
        # 以 bind_key 保存 Client，其中 self._redis_client 将 None 作为 bind_key 保存
        self._redis_binds = None

        if app is not None:
            self.init_app(app)

    @classmethod
    def from_custom_provider(cls, provider, app=None, **kwargs):
        assert provider is not None, 'your custom provider is None, come on'

        # We never pass the app parameter here, so we can call init_app
        # ourselves later, after the provider class has been set
        instance = cls(**kwargs)

        instance.provider_class = provider
        if app is not None:
            instance.init_app(app)
        return instance

    def init_app(self, app, **kwargs):
        redis_url = app.config.get(
            self.config_uri, 'redis://localhost:6379/0'
        )

        self.provider_kwargs.update(kwargs)
        self._redis_client = self.provider_class.from_url(
            redis_url, **self.provider_kwargs
        )

        self._update_binds(app)

        if not hasattr(app, 'extensions'):
            app.extensions = {}
        app.extensions[self.config_prefix.lower()] = self

    def _update_binds(self, app):
        redis_binds = app.config.get(self.config_binds)
        self._redis_binds = {
            None: self._redis_client
        }
        if isinstance(redis_binds, dict):
            for bind_key, bind_uri in redis_binds.items():
                self._redis_binds[bind_key] = self.provider_class.from_url(
                    bind_uri, **self.provider_kwargs
                )

    def get_client(self, bind_key=None):
        return self._redis_binds.get(bind_key)

    def get_clients(self):
        return self._redis_binds

    def __getattr__(self, name):
        return getattr(self._redis_client, name)

    def __getitem__(self, name):
        return self._redis_client[name]

    def __setitem__(self, name, value):
        self._redis_client[name] = value

    def __delitem__(self, name):
        del self._redis_client[name]


# Copyright (c) 2013, molie and contributors
# For license information, please see license.txt

from __future__ import unicode_literals
import frappe
from frappe.utils import cint, flt
from frappe import _

def execute(filters=None):
	if not filters: filters = {}

	columns = get_columns()
	data = get_recheck_landed_cost_voucher_item(filters)

	return columns, data

def get_columns():
	return [
		_("Status")+":Data:80",
		_("No. LCV")+":Link/Landed Cost Voucher:80",
		_("No. Purchase Receipt")+":Link/Purchase Receipt:150",
		_("Supplier Name") + ":Link/Supplier:250",

		_("Item Code") + ":Link/Item:300",
		_("Based On") + "::80",
		_("Amount LCV / QTY (IDR)") + ":Currency:150",
		_("Created Date") + ":Datetime:150",
		_("Created By") + ":Data:200",
		_("Modified Date") + ":Datetime:150",
		_("Modified By") + ":Data:200"
	]

def get_recheck_landed_cost_voucher_item(filters):
	conditions = get_conditions(filters)
	return frappe.db.sql(
		"""select distinct
				if(lcv1.docstatus = 0,"Draft","Submit") as docstatuslcv,
				lcv1.name,
				lcv3.purchase_receipt,
				lcv2.supplier,
				lcv3.item_code,
				lcv1.distribute_charges_based_on,
				lcv3.applicable_charges,
				lcv3.creation,lcv3.owner,
				lcv3.modified,lcv3.modified_by
		   from
		   		`tabLanded Cost Voucher` lcv1
				inner join `tabLanded Cost Purchase Receipt` lcv2
				inner join `tabLanded Cost Item` lcv3

		   where
		   		lcv2.parent = lcv1.name
				and lcv3.parent = lcv2.parent
				and lcv1.docstatus < 2 %s
				order by lcv1.name desc, lcv3.purchase_receipt desc, lcv2.posting_date desc
		""" % conditions, as_list=1)
	#return frappe.db.sql("""select `tabPurchase Receipt`.status,`tabPurchase Receipt`.name,`tabPurchase Receipt`.supplier,`tabPurchase Receipt`.company,`tabPurchase Receipt`.posting_date,`tabPurchase Receipt`.posting_time,`tabPurchase Receipt`.transporter_name,`tabPurchase Receipt`.lr_date,`tabPurchase Receipt`.lr_no,`tabPurchase Receipt`.currency,`tabPurchase Receipt`.price_list_currency,`tabPurchase Receipt`.conversion_rate,`tabPurchase Receipt`.base_net_total,concat(`tabCurrency`.symbol," ",`tabPurchase Receipt`.base_grand_total),`tabPurchase Receipt`.net_total,`tabPurchase Receipt`.base_total,`tabPurchase Receipt`.base_rounded_total from `tabPurchase Receipt` inner join `tabCurrency` on `tabPurchase Receipt`.currency = `tabCurrency`.name where `tabPurchase Receipt`.docstatus < 2 %s""" % conditions, as_list=1)

def get_conditions(filters):
	conditions = ""

	if filters.get("from_date"):
		conditions += "and lcv2.posting_date >= '%s'" % filters["from_date"]

	if filters.get("to_date"):
		conditions += "and lcv2.posting_date <= '%s'" % filters["to_date"]

	if filters.get("landed_cost_voucher"):
		conditions += "and lcv1.name = '%s'" % filters["landed_cost_voucher"]

	if filters.get("purchase_receipt"):
		conditions += "and lcv3.purchase_receipt = '%s'" % filters["purchase_receipt"]

	if filters.get("supplier"):
		conditions += "and lcv2.supplier = '%s'" % filters["supplier"]

	return conditions

		#if filters.get("company"): conditions += " and company = '%s'" % \
		#	filters["company"].replace("'", "\\'")


def azureml_main(df, quantile):
    import pandas as pd

    ## Save the original names of the DataFrame.
    in_names = list(df)

    df = pd.merge(df, quantile,
                     left_on = ['monthCount', 'workHr'],
                     right_on = ['monthCount', 'workHr'],
                     how = 'inner')

    ## Filter rows where the count of bikes is less than the lower quantile.
    df = df.ix[df['cnt'] > df['quantile']]

    ## Remove the unneeded column and restore the original column names.
    df.drop('quantile', axis = 1, inplace = True)
    df.columns = in_names

    ## Sort the data frame based on the dayCount
    df.sort(['days', 'workHr'],  axis = 0, inplace = True)

    return df


import os
import logging
import datetime
class LogConfig:
    @staticmethod
    def init(path):
        global logger

        if not os.path.exists('./log'):
            os.mkdir('./log')

        nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        logging.basicConfig(level=logging.INFO,
                            format='%(asctime)s %(levelname)s %(message)s',
                            datefmt='%Y-%m-%d %H:%M:%S',
                            filename = './log/'+nowTime+'.log',
                            filemode='a')
        logger = logging.getLogger()

    @staticmethod
    def getLogger():
        return logger


from . import views as book_view
from member import views as member_view
from django.urls import path, re_path

app_name = 'books'

urlpatterns = [
    path('', book_view.retrive, name='retrive'),
    path('create', book_view.create),
    re_path(r'^(?P<slug>[\w-]+)/borrow/$', member_view.borrow, name='borrow'),
    re_path(r'^(?P<slug>[\w-]+)/return/$', member_view.returning, name='return'),
    re_path(r'^(?P<slug>[\w-]+)/$', book_view.detail, name='detail'),
    re_path(r'^(?P<slug>[\w-]+)/edit/$', book_view.edit, name='edit'),
    re_path(r'^(?P<slug>[\w-]+)/delete/$', book_view.delete, name='delete'),
]


from unittest import mock

import pytest

from purchases.forms import CreatePurchaseForm

@pytest.fixture
def product(product_factory):
    return product_factory.create()

@pytest.fixture
def purchaser(staff_factory):
    return staff_factory.create()

@pytest.fixture
def form_data(purchaser, product):
    return {"purchaser": purchaser.id, "product_id": product.id, "quantity": 2}

@pytest.fixture
def mock_purchase_model():
    with mock.patch("purchases.forms.models.Purchase") as mock_purchase_model:
        yield mock_purchase_model

@pytest.fixture
def purchase(purchase_factory):
    return purchase_factory.build()

@pytest.fixture
def saved_form(purchase):
    form = CreatePurchaseForm()
    form.instance = purchase
    return form

def test_has_purchaser_field():
    assert "purchaser" in CreatePurchaseForm().fields

def test_has_product_field():
    assert "product_id" in CreatePurchaseForm().fields

def test_has_quantity_field():
    assert "quantity" in CreatePurchaseForm().fields

@pytest.mark.django_db
def test_form_validation(form_data):
    form = CreatePurchaseForm(form_data)
    assert form.is_valid()

@pytest.mark.django_db
def test_purchaser_in_cleaned_data(purchaser, form_data):
    form = CreatePurchaseForm(form_data)
    form.is_valid()
    assert form.cleaned_data["purchaser"] == purchaser

@pytest.mark.django_db
def test_product_in_cleaned_data(product, form_data):
    form = CreatePurchaseForm(form_data)
    form.is_valid()
    assert form.cleaned_data["product_id"] == product.pk

@pytest.mark.django_db
def test_quantity_in_cleaned_data(form_data):
    form = CreatePurchaseForm(form_data)
    form.is_valid()
    assert form.cleaned_data["quantity"] == form_data["quantity"]

@pytest.mark.django_db
def test_save_calls_new_purchase(mock_purchase_model, form_data, purchaser, product):
    form = CreatePurchaseForm(form_data)
    form.is_valid()
    form.save()
    mock_purchase_model.objects.new_purchase.assert_called_once_with(
        purchased_by=purchaser, product=product, quantity=form_data["quantity"]
    )

@pytest.mark.django_db
def test_save_sets_purchase_to_instance_attribute(mock_purchase_model, form_data):
    form = CreatePurchaseForm(form_data)
    form.is_valid()
    form.save()
    assert form.instance == mock_purchase_model.objects.new_purchase.return_value

@mock.patch("purchases.forms.StockManager")
def test_update_stock_level_calls_get_stock_level(
    mock_stock_manager, purchase, saved_form
):
    mock_stock_manager.get_stock_level.return_value = 50
    saved_form.instance.quantity = 5
    saved_form.update_stock_level()
    mock_stock_manager.get_stock_level.assert_called_once_with(purchase.product)

@mock.patch("purchases.forms.StockManager")
def test_update_stock_level_calls_set_stock_level(
    mock_stock_manager, purchase, saved_form
):
    purchase.quantity = 5
    mock_stock_manager.get_stock_level.return_value = 50
    saved_form.update_stock_level()
    mock_stock_manager.set_stock_level.assert_called_once_with(
        product=purchase.product,
        user=purchase.purchased_by.stcadmin_user,
        new_stock_level=45,
        change_source="Staff purchase by {{ purchase.purchased_by }}",
    )

@mock.patch("purchases.forms.StockManager")
def test_update_stock_level_returns_updated_stock_level(mock_stock_manager, saved_form):
    saved_form.instance.quantity = 5
    mock_stock_manager.get_stock_level.return_value = 50
    returned_value = saved_form.update_stock_level()
    assert returned_value == mock_stock_manager.set_stock_level.return_value

@mock.patch("purchases.forms.StockManager")
@mock.patch("purchases.forms.logging")
def test_update_stock_level_logs_get_stock_level_error(
    mock_logging, mock_stock_manager, saved_form
):
    mock_stock_manager.get_stock_level.side_effect = Exception
    with pytest.raises(Exception):
        saved_form.update_stock_level()
    mock_logging.getLogger.assert_called_once_with("django")
    mock_logging.getLogger.return_value.exception.assert_called_once()

@mock.patch("purchases.forms.StockManager")
@mock.patch("purchases.forms.logging")
def test_update_stock_level_logs_set_stock_level_error(
    mock_logging, mock_stock_manager, saved_form
):
    mock_stock_manager.get_stock_level.return_value = 3
    mock_stock_manager.set_stock_level.side_effect = Exception
    with pytest.raises(Exception):
        saved_form.update_stock_level()
    mock_logging.getLogger.assert_called_once_with("django")
    mock_logging.getLogger.return_value.exception.assert_called_once()

@mock.patch("purchases.forms.StockManager")
@mock.patch("purchases.forms.logging")
def test_update_stock_level_errors_when_stock_level_would_be_set_negative(
    mock_logging, mock_stock_manager, saved_form
):
    saved_form.instance.quantity = 5
    mock_stock_manager.get_stock_level.return_value = 3
    with pytest.raises(Exception):
        saved_form.update_stock_level()


import re
import typing
from datetime import datetime

import aiohttp
import requests
from yarl import URL

class SteamNewsPost:
    def __init__(
        self,
        gid: str = None,
        title: str = None,
        url: str = None,
        is_external_url: bool = None,
        author: str = None,
        contents: str = None,
        feedlabel: str = None,
        date: int = None,
        feedname: str = None,
        feed_type: int = None,
        appid: int = None,
    ):
        """
        Helper object to represent a Steam news post

        URLs are stripped from the contents string on instantiation
        """
        self.gid = gid
        self.title = title
        self.url = URL(url)
        self.is_external_url = is_external_url
        self.author = author
        self.contents = self._stripURL(contents)
        self.feedlabel = feedlabel
        self.date = datetime.fromtimestamp(date)
        self.feedname = feedname
        self.feed_type = feed_type
        self.appid = appid

    def __repr__(self):
        return (
            f"<SteamNews> \"{self.title}\" Posted {datetime.strftime(self.date, '%Y-%m-%d')} "
            f"by {self.author}"
        )

    @staticmethod
    async def asyncgetnewsforapp(
        appID: int = 582_010,
        count: int = 10,
        maxlength: int = 300,
        format: str = "json",
        **kwargs,
    ) -> typing.List:
        """
        This function is a coroutine

        Retrieve Steam news posts for the input appID

        Additional keyword arguments are accepted but not used to generate the API query

        Results are returned as a list of SteamNewsPost objects
        """
        apiURL = URL("https://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/")

        paramdict = {
            "appID": appID,
            "count": count,
            "maxlength": maxlength,
            "format": format,
        }
        async with aiohttp.ClientSession() as session:
            async with session.get(apiURL.with_query(paramdict)) as resp:
                rawdict = await resp.json()

        if rawdict["appnews"] and rawdict["appnews"]["newsitems"]:
            return [SteamNewsPost(**item) for item in rawdict["appnews"]["newsitems"]]

    @staticmethod
    def getnewsforapp(
        appID: int = 582_010,
        count: int = 10,
        maxlength: int = 300,
        format: str = "json",
        **kwargs,
    ) -> typing.List:
        """
        Retrieve Steam news posts for the input appID

        Additional keyword arguments are accepted but not used to generate the API query

        Results are returned as a list of SteamNewsPost objects
        """
        apiURL = URL("https://api.steampowered.com/ISteamNews/GetNewsForApp/v0002/")

        paramdict = {
            "appID": appID,
            "count": count,
            "maxlength": maxlength,
            "format": format,
        }
        r = requests.get(apiURL.with_query(paramdict))
        rawdict = r.json()

        if rawdict["appnews"] and rawdict["appnews"]["newsitems"]:
            return [SteamNewsPost(**item) for item in rawdict["appnews"]["newsitems"]]

    @staticmethod
    def _stripURL(instr: str) -> str:
        """
        Strip URLs out of instr using a basic regex
        """
        exp = r"https?:\/\/[\w\-\.\/]+\s?"
        return re.sub(exp, "", instr)


import time

def fib(n):
    if n == 1: return 1
    if n == 2: return 1
    return fib(n-1) + fib(n-2)

def fib2():
    a = 1
    b = 0
    n = 1
    while len(str(a)) < 1000:
        a, b = a+b, a
        n = n + 1
    return a, n

t_0 = time.clock()

a_1,  n_1 = fib2()
print("The first fibonacci number with a thousand digits is\n the {0}th: ({1})".format(n_1, a_1))

dt = time.clock() - t_0
print("Time elapsed:", dt)


from unittest import TestCase, mock
import tfe2_pipeline_wrapper.lib.ConsulKeys as ai

TEST_CONSUL_CONFIGURATION = {
    "address": "consul.test",
    "port": "8500",
    "dc": "dc1",
    "token": "FakeToken"
}

TEST_DEPLOYMENT_INFORMATION = {
    "id": "001",
    "component_name": "Infrastructure",
    "environment": "dev"
}

class TestConsulCalls(TestCase):
    def setUp(self):
        self.cc = ai.ConsulCalls(TEST_CONSUL_CONFIGURATION, TEST_DEPLOYMENT_INFORMATION)


import torch.nn as nn

class Generator(nn.Module):
    def __init__(self, ngpu):
        super(Generator, self).__init__()
        self.ngpu = ngpu
        self.main = nn.Sequential(
            # input is Z, going into a convolution
            nn.ConvTranspose2d(100, 64 * 8, 4, 1, 0, bias=True),
            nn.BatchNorm2d(64 * 8),
            nn.ReLU(True),
            # state size. (64*8) x 4 x 4
            nn.ConvTranspose2d(64 * 8, 64 * 4, 4, 2, 1, bias=True),
            nn.BatchNorm2d(64 * 4),
            nn.ReLU(True),
            # state size. (64*4) x 8 x 8
            nn.ConvTranspose2d( 64 * 4, 64 * 2, 4, 2, 1, bias=True),
            nn.BatchNorm2d(64 * 2),
            nn.ReLU(True),
            # state size. (64*2) x 16 x 16
            nn.ConvTranspose2d( 64 * 2, 64, 4, 2, 1, bias=True),
            nn.BatchNorm2d(64),
            nn.ReLU(True),
            # state size. (64) x 32 x 32
            nn.ConvTranspose2d( 64, 3, 4, 2, 1, bias=True),
            nn.Tanh()
            # state size. (nc) x 64 x 64
        )

    def forward(self, input):
        return self.main(input)


import piexif

def get_field_value(field_tag, exif_blob):
    """
    Gets the raw value from the api response for the given tag
    Args:
        field_tag (str): EXIF tag name
        exif_blob (dict): decoded api response

    Returns:
        unicode or None: the raw value of the specified EXIF tag

    """
    relevant_field = filter(lambda blob: blob['tag'] == field_tag, exif_blob)
    if not relevant_field:
        return None
    return relevant_field[0]['raw']['_content']

def map_exif_data(exif_blob):
    """
    Maps common EXIF fields to their Flickr counterparts. Not all the EXIF data is used.

    Args:
        exif_blob (dict): decoded api response

    Returns:
        dict: EXIF data ready to be encoded

    """
    zeroth_ifd = {
        piexif.ImageIFD.Make: get_field_value('Make', exif_blob),
        piexif.ImageIFD.Model: get_field_value('Model', exif_blob),
        piexif.ImageIFD.XResolution: (int(get_field_value('XResolution', exif_blob)), 1),
        piexif.ImageIFD.YResolution: (int(get_field_value('YResolution', exif_blob)), 1),
        piexif.ImageIFD.Software: get_field_value('Software', exif_blob),
        piexif.ImageIFD.DateTime: get_field_value('ModifyDate', exif_blob),
    }
    exif_ifd = {
        piexif.ExifIFD.DateTimeOriginal: get_field_value('DateTimeOriginal', exif_blob),
        piexif.ExifIFD.DateTimeDigitized: get_field_value('CreateDate', exif_blob),
    }
    first_ifd = {
        piexif.ImageIFD.Make: get_field_value('Make', exif_blob),
        piexif.ImageIFD.Software: get_field_value('Software', exif_blob),
    }

    exif_dict = {
        '0th': zeroth_ifd,
        'Exif': exif_ifd,
        '1st': first_ifd,
    }
    return exif_dict


# -*- coding: utf-8 -*-
#1. Caricare tutti i dati del file in un dataframe e visualizzarli in un oggetto opportuno
#2. Dato il nome di un gioco, visualizzare tutte le informazioni relative a quel gioco
#3. Modificare il punto precedente in modo che sia possibile visualizzare le informazioni dei giochi
#successivi o precedenti con due bottoni “Next” e “Prev”
#4. Dato il nome di un gioco, visualizzare la percentuale di vendita nei quattro mercati
#5. Visualizzare i giochi appartenenti ad una certa piattaforma: permettere all’utente di inserire (o di
#scegliere) la piattaforma
#6. Visualizzare il numero totale di giochi venduti in ogni mercato
#7. Visualizzare il grafico del punto 4 con un grafico a torta
#8. Visualizzare il grafico del punto 5 con un grafico a barre orizzontali
#9. Data una stringa, visualizzare i giochi che hanno quella stringa nel nome

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import PySimpleGUI as sg
import os.path
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk

df = pd.read_csv("C:/Users/ismai/Downloads/gamesSales.txt", sep='|')
df["percent"] = (df['NA_Sales'] / df['NA_Sales'].sum()) * 100
df["percent2"] = (df['EU_Sales'] / df['EU_Sales'].sum()) * 100
df["percent3"] = (df['JP_Sales'] / df['JP_Sales'].sum()) * 100
df["percent4"] = (df['Other_Sales'] / df['Other_Sales'].sum()) * 100

pd.options.display.max_rows = 8
sg.theme('DarkBlue')

fig = plt.figure(figsize=(500, 100), dpi=400)
ax = fig.add_subplot(1, 1, 1)

labels = df['Name']
values = df['percent']

x = np.arange(len(values))
width = 0.2 # the width of the bars

fig, ax = plt.subplots()

ind = np.arange(len(labels))

ax.barh(ind, df["percent"],color='red', align='center')
ax.barh(ind, df["percent2"],color='green', align='center')
ax.barh(ind, df["percent3"],color='blue', align='center')
ax.barh(ind, df["percent4"],color='orange', align='center')
ax.set(yticks=ind + width, yticklabels=df["percent2"], ylim=[2*width - 1, len(df)])
ax.set_yticks(ind)
ax.set_yticklabels(labels)
ax.invert_yaxis()  # labels read top-to-bottom
ax.set_xlabel('Performance')

def draw_figure(canvas, figure, loc=(0, 0)):
    figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
    figure_canvas_agg.draw()
    figure_canvas_agg.get_tk_widget().pack(side='top', fill='both', expand=1)
    return figure_canvas_agg

fig = plt.gcf() # if using Pyplot then get the figure from the plot
fig.set_size_inches(9,12)
figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds

# ------------------------------- Beginning of GUI CODE -------------------------------

file_list_column = [
    [sg.Text(""),
     sg.Output(size=(80,20)),
     ],
]

# For now will only show the name of the file that was chosen
menu_column = [
    [sg.Text("MENU",size=(30, 1), font='Lucida',justification='left')],
    [sg.Button('visualizzare data frame')],
    [sg.InputText(key='key'),sg.Button('cerca gioco')],
    [sg.Button('prev'),sg.Button('next')],
    [sg.InputText(key='key1'),sg.Button('cerca percentuale vendita del gioco')],
    [sg.Combo(['Wii', "NES", "GB","X360","SNES","DS","3DS","PS4","PS2","2060","N64","XB","GBA","PC"], key='key2'),sg.Button('visualizza giochi')],
    [sg.Button('visualizzare totale vendite')],
    [sg.Button('visualizzare grafico a torta')],
    [sg.Button('visualizzare grafico a barre')],
    [sg.InputText(key='key3'),sg.Button('cerca nome')],
    [sg.Button('Exit')],
]

# ----- Full layout -----
layout = [
    [sg.Column(file_list_column),
     sg.Canvas(size=(figure_w, figure_h), key='-CANVAS-'),
     sg.VSeperator(),
     sg.Column(menu_column),]
]

window = sg.Window("giochi", layout)

while True:
    event, values = window.read()
    if event == "Exit" or event == sg.WIN_CLOSED:
        break
    elif  event == 'visualizzare data frame':
        print(df)
    elif  event == 'cerca gioco':
        print(df.loc[df['Name'] == values.get("key")],"\n")
    elif  event == 'prev':
        condition = df[df["Name"]== values.get("key")].index.values
        indice = condition[0]
        print(df.iloc[indice-1])
    elif  event == 'next':
        condition = df[df["Name"]== values.get("key")].index.values
        indice = condition[0]
        print(df.iloc[indice+1])
    elif  event == 'cerca percentuale vendita del gioco':
        c = df.loc[df['Name'] == values.get("key1")]
        perc = c[["NA_Sales","EU_Sales","JP_Sales","Other_Sales"]] / df[["NA_Sales","EU_Sales","JP_Sales","Other_Sales"]].sum() * 100
        print(perc)
    elif  event == 'visualizza giochi':
        b = df.loc[df['Platform'] == values.get("key2")]
        print(b["Name"])
    elif  event == 'visualizzare totale vendite':
        print(df[["NA_Sales","EU_Sales","JP_Sales","Other_Sales"]].sum())
    elif event == 'visualizzare grafico a barre':
        fig_photo = draw_figure(window['-CANVAS-'].TKCanvas, fig)
    elif event =="cerca nome":
        print(df.loc[df['Name'].str.contains(values.get("key3"), case=False)])
window.refresh()
window.close()

window.refresh()
window.close()


from exercises.Exercise import Exercise
from workouts.Workout import Workout
import random
import collections
import itertools
import inquirer

muscle_list = ["Traps", "a_shoulder", "l_shoulder", "p_shoulder", "chest", "biceps", "triceps", "abs",
               "row_back", "pulldown_back", "lower_back", "glutes", "quads", "hamstrings", "calves"]

def muscle_subgroups(muscles):
    combinations = []
    for i in range(len(muscles) + 1, 0, -1):
        # loop from highest and go down to prioritize finding exercises using all muscle groups
        combinations.append((list(itertools.combinations(muscles, i))))
        # get every combination of sub-pairing and isolation of muscles in muscle list
    combinations = [list(elem) for elem in [item for sublist in combinations for item in sublist]]
    return combinations

def compare(x,y):
    return collections.Counter(x) == collections.Counter(y)

def find_exercises(muscles, exercise_database):
    """
    Description: Generates workout based off of input muscles list
    :param muscles:
    :return:
    """
    combinations = muscle_subgroups(muscles)
    options = []
    for x in exercise_database:
        if x.use_muscles(combinations):
            options.append(x)
    return options

def workout(potential_exercises, user_exercises, user_time):
    """
    Description: Generates workout object & takes exercises which targets user muscle groups and applies constraints
    to determine workout
    :return:
    Originally had function which created workout object, and looped whilst workout was not valid to find exercises
    based on the muscle input. Having this function later may be useful and using that technique may be useful
    when adding lots of variables in determining whether an exercise is valid
    """
    final_workout = Workout(user_muscles, 20)
    final_workout.calculate_type_breakdown(user_exercises)
    # set the comp/iso breakdown of the workout
    while not final_workout.is_valid_workout():
    # while the final workout state doesnt meet the conditions of the workout prescribed
        try :
            temp = random.choice(user_exercises)
        except IndexError:
            return "Unable to make a workout"
        user_exercises.remove(temp)
        # pick a random exercise from the potential user exercises for muscles and remove it from list
        if final_workout.is_valid_to_add(temp):
        # here we check if adding that exercise will not invalidate our workout object
            final_workout.add_exercise(temp)
            # add the exercise to our workout
    return final_workout

def build_exercise_database():
    exercise_database = []
    with open("Exercise.txt") as file:
        line = file.read().strip().split()
        for x in line:
            x = x.split(',')
            exercise_database.append(Exercise(x[0], x[1].split('/'), x[2]))
    return exercise_database

if __name__ == "__main__":
    user_exercises = build_exercise_database()
    # generate users exercises
    muscles = [inquirer.List('muscles', message="Select a muscle group to train",choices=['Chest, Shoulders, Triceps', 'Back, Biceps', 'Legs'],),]
    answers = inquirer.prompt(muscles)
    print (answers["muscles"])

    user_muscles = input("Enter muscles ").split()
    user_time = input("How long do you want to spend in the gym? ")
    # find out what user wants to train and how long to spend in the gym
    user_exercises = find_exercises(user_muscles, user_exercises)
    # build exercises based on those muscles and the exercise database
    final = workout(user_exercises, user_exercises, user_time)
    # build workout object
    if final != "Unable to make a workout":
        final.sort()
    # place the exercises that recruit most muscles first in exercise list (compound -> isolation)
    print (str(final))


# O(n) time | O(1) space
def kadanesAlgorithm(array):
    if len(array) == 1:
        return array[0]
    maxSum = prev = array[0]
    for i in range(1, len(array)):
        current = max(array[i], array[i] + prev)
        if current > maxSum:
            maxSum = current
        prev = current

    return maxSum


from ffmpeg_tools import key_frame_extraction
from face_detection import recommend
import shutil
import glob
import argparse
import os
import dlib
from expression_detection.models import *
from mtcnn import MTCNN

"""
输入：视频路径
输出：推荐帧序列
"""
parse = argparse.ArgumentParser()
parse.add_argument('--video_path', type=str, default="G:/DrawMusic/videos/001.mp4",
                   help="待推荐视频的绝对路径")
parse.add_argument('--frames_path', type=str, default="G:/DrawMusic/frames",
                   help="待推荐视频的绝对路径")
parse.add_argument('--test_path', type=str, default="G:/DrawMusic/result", help="存储调试图片的路径")
args = parse.parse_args()

def main(video_path):
    print("开始载入预训练模块:")
    detector = dlib.get_frontal_face_detector()
    predictor = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat')
    print("1.闭眼检测模块载入完成======>>>>>>")

    net = VGG('VGG19')
    checkpoint = torch.load(os.path.join('G:/DrawMusic/expression_detection/FER2013_VGG19',
                                         'PrivateTest_model.t7'))
    net.load_state_dict(checkpoint['net'])
    net.cuda()
    net.eval()
    print("2.表情检测模块载入完成======>>>>>>")

    mtcnn = MTCNN()
    print("3.人脸检测模块载入完成======>>>>>>")

    # 判定frames文件夹是否有图片:

    video_list = glob.glob(video_path)

    for video_path in video_list:

        _, fullflname = os.path.split(video_path)
        fname, _ = os.path.splitext(fullflname)

        file_list = glob.glob(args.frames_path + "/*.png")
        if file_list:
            for filename in file_list:
                os.remove(filename)

        frame_dict = key_frame_extraction(video_path, args.frames_path)
        # frame_length = len(frame_dict)
        cover_index_list, best_index = recommend(args.frames_path,fname,detector,predictor,net,mtcnn)
        print("我们推荐的5帧(可能小于5)的关键帧序号为:", cover_index_list,
              "其中评分最好的关键帧序号是:", best_index)

        shutil.copyfile("G:/DrawMusic/frames/keyframe-000.png",
                        "G:/DrawMusic/result/{}-begin.png".format(fname))

        if best_index < 10:
            shutil.copyfile("G:/DrawMusic/frames/keyframe-00{}.png".format(best_index),
                            "G:/DrawMusic/result/{}-selection.png".format(fname))
        elif best_index < 100:
            shutil.copyfile("G:/DrawMusic/frames/keyframe-0{}.png".format(best_index),
                            "G:/DrawMusic/result/{}-selection.png".format(fname))
        else:
            shutil.copyfile("G:/DrawMusic/frames/keyframe-{}.png".format(best_index),
                            "G:/DrawMusic/result/{}-selection.png".format(fname))

if __name__ == "__main__":
    file_list = glob.glob(args.test_path+"/*.png")
    if file_list:
        for filename in file_list:
            os.remove(filename)

    video_path = "G:/Test_Videos"
    main(video_path)


import threading

import qtpy
from qtpy import QtWidgets

from qt_thread_updater.thread_updater import ThreadUpdater

__all__ = ['get_updater', 'set_updater', 'cleanup_app',
           'get_global_updater_mngr', 'set_global_updater_mngr', 'GlobalUpdaterManager']

def get_updater():
    """Return the main updater. Override `GlobalUpdater.get_updater` to change how this function works.

    Overriding GlobalUpdater.get_updater may be needed if multiprocess/pickling does not work because of the lock.
    """
    return get_global_updater_mngr().get_updater()

def set_updater(updater):
    """Set the main updater. Override `GlobalUpdater.set_updater` to change how this function works."""
    get_global_updater_mngr().set_updater(updater)

def cleanup_app(app=None):
    """Clean up and delete the QApplication singleton."""
    if app is None:
        app = QtWidgets.QApplication.instance()

    # Reset the global reference to the updater
    set_updater(None)

    if app:
        app.closeAllWindows()
        for widg in app.allWindows():
            widg.deleteLater()

    for mod in dir(qtpy):
        try:
            delattr(getattr(qtpy, mod), 'qApp')
        except:
            pass
        try:
            setattr(getattr(qtpy, mod), 'qApp', None)
        except:
            pass

GLOBAL_UPDATER_MANGER = None

def get_global_updater_mngr():
    """Return the manager that creates and returns the ThreadUpdater."""
    global GLOBAL_UPDATER_MANGER
    return GLOBAL_UPDATER_MANGER

def set_global_updater_mngr(mngr):
    """Return the manager that creates and returns the ThreadUpdater."""
    global GLOBAL_UPDATER_MANGER
    GLOBAL_UPDATER_MANGER = mngr

class GlobalUpdaterManager(object):

    def __init__(self):
        self.lock = threading.RLock()
        self.main_updater = ThreadUpdater()

    def get_updater(self):
        """Return the main updater."""
        with self.lock:
            if self.main_updater is None:
                # Create a default updater (may cause issues if this is not created in the main thread)
                self.main_updater = ThreadUpdater(init_later=True)

                # Init later was temporarily used when the lock was not used. Two thread could create the main_updater
                # at the same time causing problems.
                # Initially I did not want to use a lock, because it could break multiprocessing for the module.
                self.main_updater.init()

            return self.main_updater

    def set_updater(self, updater):
        """Set the main updater."""
        with self.lock:
            self.main_updater = updater

    def __getstate__(self):
        """Return the variables to serialize. This should fix multiprocessing with locks pickling problems."""
        # Note do NOT give any lock objects!
        return {}

    def __setstate__(self, state):
        """Initialize this object in a separate process."""
        self.lock = threading.RLock()
        self.main_updater = ThreadUpdater()

        if isinstance(state, dict):
            for k, v in state.items():
                setattr(self, k, v)

# Set the default global updater manager
set_global_updater_mngr(GlobalUpdaterManager())


"""
Summary
-------
The purpose of this module is to review and correct data unit issues in a
CalSim DSS file.

"""
# %% Import libraries.
# Import standard libraries.
import os
import argparse
# Import third party libraries.
import pandas as pd
# Import custom modules.
try:
    import custom_modules
    from tools.io import read_dss, write_dss
    from tools.transform import split_pathname, join_pathname
except(ModuleNotFoundError):
    from ..tools.io import read_dss, write_dss
    from ..tools.transform import split_pathname, join_pathname

# %% Define functions.
def unit_correction(df, auto_correct_file=False, verbose=True,
                    fp_out=''):
    """
    Summary
    -------
    Core function for identifying and correcting units in a CalSim DataFrame.

    Parameters
    ----------
    df : pandas DataFrame
        Original CalSim DataFrame in tidy format for manipulation.
    auto_correct_file : bool, default False, optional
        Option to bypass user prompt to correct CalSim unit labeling and
        automatically apply corrections.
    verbose : bool, default True, optional
        Option to report proposed data unit changes.
    fp_out : path, default '', optional
        Absolute or relative file path destination to write corrected data.

    Returns
    -------
    part_Bs : list
        List of Part B variables flag for data unit correction. An empty list
        indicates that all variables units are correct according to this
        procedure.
    df_c : pandas DataFrame
        Copy of `df` with applied corrections if `auto_correct_file` = True.

    """
    df_c = df.copy()
    df_c = split_pathname(df_c)
    # Flag where 'Units' column has additional whitespace.
    filter_ws = df_c['Units'] != df_c['Units'].str.strip()
    # Flag where 'STORAGE' variables are not unit date-types 'TAF INST-VAL'.
    filter_sc = df_c['Part C'] == 'STORAGE'
    filter_su = df_c['Units'] != 'TAF'
    filter_sd = df_c['Data Type'] != 'INST-VAL'
    filter_stor = (filter_sc & (filter_su | filter_sd))
    # Flag where non-STORAGE variables with unit 'TAF' are not 'PER-CUM'.
    filter_nc = df_c['Part C'] != 'STORAGE'
    filter_nu = df_c['Units'] == 'TAF'
    filter_nd = df_c['Data Type'] != 'PER-CUM'
    filter_nonstor = ((filter_nc & filter_nu) & filter_nd)
    # Flag variables with unit 'CFS' without date-type 'PER-AVER'.
    filter_cu = df_c['Units'] == 'CFS'
    filter_cd = df_c['Data Type'] != 'PER-AVER'
    filter_cfs = (filter_cu & filter_cd)
    # Combine filters into a single filter.
    filter_combo = (filter_ws | filter_stor | filter_nonstor | filter_cfs)
    # Correct or report data unit issues.
    if filter_combo.any():
        part_Bs = df_c.loc[filter_combo, 'Part B'].unique().tolist()
        df_c = join_pathname(df_c)
        if verbose:
            print('Found values requiring unit correction.')
            first_pth = ~df_c.duplicated('Pathname')
            col = ['Pathname', 'Units', 'Data Type']
            for v in df_c.loc[filter_ws & first_pth, col].values.tolist():
                p, u, _ = v
                print('{}: "{}" -> "{}"'.format(p, u, u.strip()))
            for v in df_c.loc[filter_stor & first_pth, col].values.tolist():
                p, u, d = v
                print(f'{p}: "{u} {d}" -> "TAF INST-VAL"')
            for v in df_c.loc[filter_nonstor & first_pth, col].values.tolist():
                p, u, d = v
                print(f'{p}: "{u} {d}" -> "{u} PER-CUM"')
            for v in df_c.loc[filter_cfs & first_pth, col].values.tolist():
                p, u, d = v
                print(f'{p}: "{u} {d}" -> "{u} PER-AVER"')
        if auto_correct_file:
            df_c['Units'] = df_c['Units'].str.strip()
            df_c.loc[filter_stor, ['Units', 'Data Type']] = ['TAF', 'INST-VAL']
            df_c.loc[filter_nonstor, 'Data Type'] = 'PER-CUM'
            df_c.loc[filter_cfs, 'Data Type'] = 'PER-AVER'
            if fp_out:
                _ = write_dss(fp_out, df_c.loc[filter_combo, :])
    else:
        if verbose: print('Found no variables requiring unit correction.')
        part_Bs = list()
    # Return `part_Bs` and `df_c`.
    return part_Bs, df_c

def main(fp, auto_correct_file=False, fp_init=False, verbose=True):
    """
    Summary
    -------
    This main function detects incorrect units in a CalSim DSS file and applies
    a correction. Note, this procedure is current optimized for CalSim3 DSS
    files.

    Parameters
    ----------
    fp : path
        Absolute or relative file path a CalSim DSS file.
    auto_correct_file : bool, default False, optional
        Option to bypass user prompt to correct CalSim unit labeling and
        automatically apply corrections.
    fp_init : bool, default False, optional
        Option to flag if `fp` is an initialization file (INIT).
    verbose : bool, default False, optional
        Option to report proposed data unit changes.

    Returns
    -------
    part_Bs : list
        List of Part B variables flag for data unit correction. An empty list
        indicates that all variables units are correct according to this
        procedure.

    Notes
    -----
    1. According the HEC-DSS, the available data types are 'PER-AVER',
       'PER-CUM', and 'INST-VAL'.
    2. Correcting units in Init and SV *.dss files does not have an effect or
       creates errors when running a CalSim study. Storage units of 'TAF
       INST-VAL' do not seem to propagate through to the DV file, remaining in
       units of 'TAF PER-AVER'. As a result, it is best to use this tool as a
       pre-processor prior to visualization with the `calsim_toolkit`.

    """
    # Ensure passed file path is a DSS file.
    _, extn = os.path.splitext(fp)
    if extn.lower() != '.dss':
        msg = 'This procedure can currently only handle a *.dss file.'
        raise RuntimeError(msg)
    # Query in data.
    if fp_init:
        df = read_dss(fp, start_date='1918-05-31', end_date='1921-11-30')
    else:
        df = read_dss(fp, end_date='2015-09-30')
    # Apply unit correction.
    part_Bs, df = unit_correction(df, auto_correct_file=auto_correct_file,
                                  verbose=verbose,
                                  fp_out=fp)
    # Return list of Part B required for correction.
    return part_Bs

# %% Execute script.
if __name__ == '__main__':
    # Initialize argument parser.
    intro = '''
            Detects incorrect units in a CalSim DSS file and applies
            a correction.
            '''
    parser = argparse.ArgumentParser(description=intro)
    # Add positional arguments to parser.
    parser.add_argument('fp', metavar='DSS file path', type=str, nargs='?',
                        help='Absolute or relative path to DSS file.')
    # Add optional arguments.
    parser.add_argument('-c', '--correct', action='store_true', default=False,
                        help='''
                             Option to automatically correct detected unit
                             issues in DSS file.
                             ''')
    parser.add_argument('-i', '--init', action='store_true', default=False,
                        help='''
                             Option to flag if `fp` is an initialization file
                             (INIT).
                             ''')
    # Parse arguments.
    args = parser.parse_args()
    fp = args.fp.strip('"')
    auto_correct_file = args.correct
    fp_init = args.init
    verbose = not auto_correct_file
    # Pass arguments to function.
    _ = main(fp, auto_correct_file=auto_correct_file, fp_init=fp_init,
             verbose=verbose)


# -*- coding: utf-8 -*-
from flask import Flask, render_template,request,url_for,redirect,session
import fonksiyonlar

app = Flask(__name__)
@app.route('/')
def home():
    return render_template('arama.html')
@app.route('/sonuc', methods=["GET","POST"])
def sonuc():
    if request.method == "POST":
        gelen = request.form["numara"]
        if fonksiyonlar.numarami(gelen)== True:
            sonuc = fonksiyonlar.numara_denetim(gelen)
            return render_template('sonuc.html', dogruluk=sonuc[0], isim=sonuc[1], id=sonuc[2])
        else:
            return redirect(url_for('home'))
    else:
        return redirect(url_for('home'))

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


import unittest

from algo_tasks import task_num_243_b, task_num_243_a, task_num_107
from unittest.mock import patch

class TestAlgoTasks(unittest.TestCase):

    def test_task107(self):
        expected_answer = 3
        expected_input = 232
        with patch('builtins.input', return_value=expected_input) as _raw_input:
            self.assertEqual(task_num_107(), expected_answer)

    def test_task_243_a(self):
        expected_answer = (1, 5)
        expected_input = 26
        with patch('builtins.input', return_value=expected_input) as _raw_input:
            self.assertEqual(task_num_243_a(), expected_answer)

    def test_task_243_b(self):
        expected_answer = [(0, 5), (3, 4)]
        expected_input = 25
        with patch('builtins.input', return_value=expected_input) as _raw_input:
            self.assertEqual(task_num_243_b(), expected_answer)

if __name__ == '__main__':
    unittest.main()


from dg import *
from keras.utils import multi_gpu_model   #multi GPU function
from keras.layers import Input, Dense, Dropout, LSTM, multiply, BatchNormalization, Concatenate, TimeDistributed
from keras.layers.advanced_activations import LeakyReLU
from keras.models import Sequential, Model
from keras import backend
from sklearn.metrics import mean_squared_error
from keras.optimizers import adam
import tensorflow as tf
import json, os, datetime as dt
import numpy as np
import random
import sys
from tqdm import tqdm
from statistics import mean

class myLSTM():
    """A class for an building and inferencing an GAN model with a generator and a discriminator"""

    def __init__(self, configs):
        self.timesteps = configs['model']['input_timesteps']
        self.numFeatures = configs['model']['num_features']
        self.seq_len = configs['model']['GAN3_seq_len']
        self.noiseLatentDim = configs['model']['noise_latent_dim']
        self.num_GPU = 1

        opt = adam(learning_rate=configs['model']['learning_rate'], beta_1=configs['model']['momentum'])

        if self.num_GPU == 1:

            # Build the generator
            self.generator = self.build_generator()
            self.generator.summary()
            self.generator.compile(loss=['mse'], optimizer=opt)
            print("[LSTM] Generator Built")

    #generate traj base on previous trajs(full signal)
    def build_generator(self):

        #features (including vehicles information for others)
        condition_features = Input(shape=(None, self.numFeatures), name='G_feature_input')
        encoded_condition_features = (LSTM(256, return_sequences=True)(condition_features))

        model = Sequential()
        model.add(Dropout(0.2))
        model.add(LSTM(512,  return_sequences=True))
        model.add(BatchNormalization())
        model.add(Dropout(0.4))
        model.add(LSTM(64,  return_sequences=True))
        model.add(BatchNormalization())
        model.add(Dropout(0.4))
        model.add(TimeDistributed(Dense(1, activation="sigmoid")))

        out = model(encoded_condition_features)
        return Model(condition_features, out)

    def train(self, configs, data_train, data_val):
        epochs = configs['training']['epochs']

        print('[LSTM Model] LSTM Training Started')
        print('[LSTM Model] %s epochs' % (epochs))

        X = np.array([i[0] for i in data_train])
        Y = np.array([i[1] for i in data_train])

        X_val = np.array([i[0] for i in data_val])
        Y_val = np.array([i[1] for i in data_val])

        size = len(X)
        Y = np.reshape(Y, (size, self.seq_len, 1))
        X = np.reshape(X, (size, self.seq_len, self.numFeatures))
        size = len(Y_val)
        Y_val = np.reshape(Y_val, (size, self.seq_len, 1))
        X_val = np.reshape(X_val, (size, self.seq_len, self.numFeatures))
        hist = self.generator.fit(X, Y, validation_data=(X_val, Y_val))

if __name__ == '__main__':
    configs = json.load(open('config_gan.json', 'r'))
    if not os.path.exists(configs['model']['save_dir']):
        os.makedirs(configs['model']['save_dir'])

    #prepare data
    data_train, data_val, data_test = PlatoonDataGenerator(configs).prepareDataBySeq()

    #create and build GAN model
    lstm = myLSTM(configs)
    lstm.train(configs, data_train, data_val)


from bb.clipboard import *
from ctypes import (c_int, byref, POINTER, pointer,
    create_string_buffer, string_at, sizeof, get_errno, cast)
import tart
import errno

PATH_MAX = 255
CLIPBOARD_BUFFER_SIZE = 16384

class ClipboardError(Exception):
    '''represents a failure in Clipboard call.'''

class Clipboard:
    def __init__(self, path=None):
        if path:
           print('Clipboard set_clipboard_path {!r}'.format(path))
           rc = set_clipboard_path(c_char_p(path.encode('utf-8')), len(path))
           print('set clipboard path, rc', rc)

        buf = create_string_buffer(PATH_MAX)
        rc = get_clipboard_path(buf, len(buf))
        if rc == -1:
            raise ClipboardError('get_clipboard_path')
        self.path = buf.value.decode('utf-8')

    def contains(self, mimeType):
        '''
        Returns True if the data exists in the clipboard for the specified type and accessible for the caller. False otherwise.
        '''

        print('Clipboard contains type {!r}'.format(mimeType))
        rc = is_clipboard_format_present(c_char_p(mimeType.encode('utf-8')))
        exists = True if rc == 0 else False
        restricted = False
        if not exists:
            restricted = True if get_errno() == errno.EACCES else False
        print('contains exists = {!r}, restricted = {!r}'.format(exists, restricted))
        if restricted:
            raise ClipboardError('Access restricted.')

        return exists

    def value(self, mimeType):
        '''
        Returns data (byte string) from the clipboard for the specified type.

        Will return the data requested if it's able to be accessed. If not, it will be None.
        '''

        print('Clipboard get_clipboarddataa type {!r}'.format(mimeType))
        buf = (c_char * CLIPBOARD_BUFFER_SIZE)()
        t = cast(buf, POINTER(c_char))
        rc = get_clipboard_data(c_char_p(mimeType.encode('utf-8')), byref(t))
        if rc == 4294967295: # -1 in as unsigned int
            restricted = True if get_errno() == errno.EACCES else False
            size = 0
            data = None
        else:
            restricted = False
            size = rc
            data = b""
            for i in range(size):
                data += t[i]
        print('value restricted {!r}, size {!r}, data {!r}'.format(restricted, size, data))

        if restricted:
            raise ClipboardError('Access restricted.')

        return data

    def insert(self, mimeType, data):
        '''
        Adds new data to the clipboard for the specified type.

        If the data already exists for the type, it's replaced. Data for other types is unaffected.
        '''

        print('Clipboard set_clipboard_data type {!r}'.format(mimeType))
        if isinstance(data, str):
            buf = create_string_buffer(data.encode('utf-8'))
        elif isintance(data, bytes):
            buf = (c_char * len(data))()
            for i in range(len(data)):
                buf[i] = data[i]
        else:
            raise ClipboardError('Unsupported data type.')

        t = cast(buf, POINTER(c_char))
        rc = set_clipboard_data(mimeType.encode('utf-8'), len(data), t)
        size = 0 if rc == -1 else rc
        restricted = False
        if size == -1:
            restricted = True if get_errno() == errno.EACCES else False
        print('insert restricted {!r}, bytes written {!r}'.format(restricted, size))
        if restricted:
            raise ClipboardError('Access restricted.')
        return size

    def remove(self, mimeType):
        '''
        Deletes data from the clipboard for the specified type

        Returns True if the data was deleted successfully. False otherwise.
        '''

        print('Clipboard empty_clipboard_by type {!r}'.format(mimeType))
        rc = empty_clipboard_by(mimeType.encode('utf-8'))
        success = True if rc == -1 else False
        restricted = False
        if not success:
            restricted = True if get_errno() == errno.EACCES else False
        print('remove restricted {!r}, success {!r}'.format(restricted, success))
        if restricted:
            raise ClipboardError('Access restricted.')
        return success

    def clear(self):
        '''
        Deletes all data from the clipboard.

        Returns True if all data was deleted successfully. False otherwise.
        '''

        print('Clipboard empty_clipboard')
        rc = empty_clipboard()
        success = True if rc == -1 else False
        restricted = False
        if not success:
            restricted = True if get_errno() == errno.EACCES else False
        print('clear restricted {!r}, success {!r}'.format(restricted, success))
        if restricted:
            raise ClipboardError('Access restricted.')
        return success


import tensorflow as tf

def create_placeholders(input_dim, output_dim):
    # None은 training 갯수
    X = tf.placeholder(tf.float32, [input_dim, None], 'x')
    Y = tf.placeholder(tf.float32, [output_dim, None], 'y')

    return X, Y

def initialize_parameters(dims_of_layers):
    params = {}
    for i in range(1, len(dims_of_layers)):
        params['w' + str(i)] = tf.get_variable('w' + str(i), [dims_of_layers[i], dims_of_layers[i - 1]],
                                               initializer=tf.keras.initializers.he_uniform())
        params['b' + str(i)] = tf.get_variable('b' + str(i), [dims_of_layers[i], 1], initializer=tf.zeros_initializer())

    return params

def linear_forward(w, b, x):
    z = tf.matmul(w, x) + b

    return z

def forward_propagation(params, x, dims_of_layers):
    a = x
    for i in range(1, len(dims_of_layers)):
        w = params['w' + str(i)],
        b = params['b' + str(i)]
        z = linear_forward(w, b, a)
        if i == len(dims_of_layers) - 1:
            a = tf.nn.softmax(z, axis=0)
        else:
            a = tf.nn.relu(z)
    return a

def compute_cost(a, y):
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=a, labels=y))

    return cost

def predict(params, x, y, dims_of_layers):
    a = forward_propagation(params, x, dims_of_layers)

    p = tf.equal(tf.argmax(a), tf.argmax(y))

    return p


"""
从起始节点开始，作为切分的一部分，
剩下的节点作为切分的另一部分。找到横切边中权值最小的那一个（使用最小堆实现），
如果横切边另外一边没有被加入最小生成树，那么就选取这条横切边并将该节点变为最小生成树
以此类推
"""
from MinHeap import MinHeap

class LazyPrimMST:

    def __init__(self, graph):
        self.graph = graph  # 图的引用
        self.pq = MinHeap()  # 用最小堆来作为优先队列
        self.marked = [False for _ in range(graph.num_of_vertex)]  # 用于标记该节点是否已经加入了最小生成树
        self.mst = []  # 用于存储产生的最小生成树
        self.mst_weight = 0  # 用于存储最小生成树对应的权值

        self.lazy_prim()

    @property
    def mst_(self):
        return self.mst

    @property
    def mst_weight_(self):
        return self.mst_weight

    def lazy_prim(self):
        """
        从初始节点开始（这里选取0）访问临边寻找横切边， 从当前优先队列中取出最小的边（要进行一次横切边判断），
        将此边加入到最小生成树， 然后访问该横切边未加入到最小生成树的节点。最后累加最小生成树的权值
        """
        self.visit(0)
        while not self.pq.is_empty():
            tmp = self.pq.extract_min()
            # 虽然加入的时候判断了一次横切边，但在取出之前可能节点状态发生了改变， 还需要再一次判断
            if self.marked[tmp.vertex_a] == self.marked[tmp.vertex_b]:
                continue

            self.mst.append(tmp)
            if not self.marked[tmp.vertex_a]:
                self.visit(tmp.vertex_a)
            else:
                self.visit(tmp.vertex_b)

        for edge in self.mst:
            self.mst_weight += edge.weight_

    def visit(self, vertex):
        """
        用于访问一个节点的相邻节点， 如果该相邻节点还没有加入最小生成树，那么这条边就是一个
        横切边（即潜在的最小生成树的边）， 将其加入到优先队列中, 并且该节点加入最小生成树
        """
        assert not self.marked[vertex]
        self.marked[vertex] = True

        connected_vertex_list = self.graph.get_edge_iterator(vertex).get_connected_vertex_list()
        for edge in connected_vertex_list:
            if not self.marked[edge.other(vertex)]:
                self.pq.insert(edge)


class cutplane(object):

    def __init__(self,date,jobname,var,path='D:/Ansys/Data/ITER/',reread=False):
        self.lut = 13  # number of colorbar divisions
        self.reread = reread
        path = check_path(path)
        self.path = path+date+'_'+jobname
        self.im = {}
        self.var = var
        self.read_cutplanes()
        self.load_mesh(1)
        files = glob.glob(path+date+'_'+jobname+'/loadstep/*'+'tempCP'+'*.vi')
        self.nCPfiles = max([int(file.split('_')[-1].split('.')[0])
                           for file in files])

    def load_mesh(self,cplane):
        self.cplane = cplane
        self.mesh = {}
        self.mesh['n'] = self.read_surface('temp',self.cplane)
        self.mesh['e'] = self.read_surface('volt',self.cplane)
        self.grid_mesh(self.mesh['n'])
        self.grid_mesh(self.mesh['e'])
        self.triangulate()
        self.data = {'V':[[] for i in range(self.ncp)],
                     'J':[[] for i in range(self.ncp)],
                     'BFE':[[] for i in range(self.ncp)]}
        self.data['T'] = [[] for i in range(self.ncp)]

    def read_data(self,LS):
        file = self.path+'/loadstep/tempCP_'+str(LS)+'.vi'
        with open(file,'r') as f:
            self.time = int(float(f.readline().split()[-1]))
            self.ncp = int(float(f.readline().split()[-1]))
            for i in range(self.ncp):
                ndata = int(float(f.readline().split()[-1]))
                self.data['T'][i] = np.zeros(ndata)
                f.readline()
                for j in range(ndata):
                    self.data['T'][i][j] = float(f.readline().split()[0])

        file = self.path+'/loadstep/voltCP_'+str(LS)+'.vi'
        with open(file,'r') as f:
            self.time = int(float(f.readline().split()[-1]))
            self.ncp = int(float(f.readline().split()[-1]))
            for i in range(self.ncp):
                ndata = int(float(f.readline().split()[-1]))
                self.data['V'][i] = np.zeros(ndata)
                self.data['J'][i] = np.zeros(ndata)
                self.data['BFE'][i] = np.zeros(ndata)
                f.readline()
                for j in range(ndata):
                    data = f.readline().split()
                    self.data['J'][i][j] = float(data[0])
                    #self.data['J'][i][j] = float(data[1])
                    #self.data['BFE'][i][j] = float(data[2])

    def load_data(self,LS,cplane=1,verbose=True):
        if cplane != self.cplane: self.load_mesh(cplane)
        datafile = self.path+'/CP{:1.0f}_{:1.0f}.pkl'.format(self.cplane,LS)
        if not os.path.isfile(datafile) or self.reread:
            if verbose: print('reading LS {:1.0f}'.format(LS))
            self.read_data(LS)  # update
            self.store_data('write',datafile)
        else:
            if verbose: print('loading LS {:1.0f}'.format(LS))
            self.store_data('read',datafile)

    def store_data(self,readwrite,datafile):
        if readwrite is 'write':
            with open(datafile, 'wb') as output:
                pickle.dump(self.data,output,-1)
                pickle.dump(self.nCPfiles,output,-1)
        else:
            with open(datafile, 'rb') as input:
                self.data = pickle.load(input)
                self.nCPdata = pickle.load(input)

    def get_clim(self,LS):
        limit_array = np.zeros((len(LS),),dtype=[('T','2float'),('V','2float'),
                                            ('J','2float'),('BFE','2float')])
        for i,ls in enumerate(LS):
            self.read_data(ls)
            for var in self.var:
                minmax = np.zeros((self.ncp,2))
                for j in range(len(self.data[var])):
                    minmax[j,0] = self.data[var][j].min()
                    minmax[j,1] = self.data[var][j].max()
                limit_array[i][var][0] = np.min(minmax[:,0])
                limit_array[i][var][1] = np.max(minmax[:,1])

        self.clim = {}
        for var in self.var:
            self.clim[var] = np.zeros(2)
            self.clim[var][0] = np.min(limit_array[var])
            self.clim[var][1] = np.max(limit_array[var])

    def store_mesh(self,N,r,th,z,dy,y):
        mesh = {}
        mesh['N'],mesh['r'],mesh['th'] = N,r,th
        mesh['z'],mesh['dy'],mesh['y'] = z,dy,y
        return mesh

    def read_cutplanes(self):
        file = self.path+'/data/cutplanes.vi'
        self.ncp = sum(1 for line in open(file))-1  # cutplane number
        self.theta_cp = np.zeros(self.ncp)
        with open(file,'r') as f:
            f.readline()
            for i,line in enumerate(f):
                self.theta_cp[i] = float(line.split()[-1])

    def read_surface(self,varaible,index):
        file = self.path+'/data/'+varaible+'_surface_{:1.0f}.vi'.format(index)
        print(file)
        N = sum(1 for line in open(file))-6  # node number
        x_mesh,y_mesh = np.empty(N),np.empty(N)
        z_mesh,da_mesh = np.empty(N),np.empty(N)
        with open(file,'r') as f:
            xo = float(f.readline().split()[-1])
            yo = float(f.readline().split()[-1])
            zo = float(f.readline().split()[-1])
            theta = float(f.readline().split()[-1])
            f.readline()
            f.readline()
            for i,line in enumerate(f):
                x_mesh[i] = float(line.split()[0])
                y_mesh[i] = float(line.split()[1])
                z_mesh[i] = float(line.split()[2])
                da_mesh[i] = float(line.split()[3])

        pl.figure()
        for y,z in zip(y_mesh,z_mesh):
            pl.plot(y,z,'.',markersize=2)
        pl.axis('equal')
        pl.figure()

        th_mesh = np.arctan2(x_mesh-xo,y_mesh-yo)
        #r_mesh = np.sqrt((x_mesh-xo)**2+(y_mesh-yo)**2)
        r_mesh = (y_mesh-yo)/np.cos(theta)
        dy_mesh = -r_mesh#-(r_mesh-np.mean(r_mesh))
        y_mesh = dy_mesh
        mesh = self.store_mesh(N,r_mesh,th_mesh,z_mesh,dy_mesh,y_mesh)
        return mesh

    def read_surface_old(self,varaible,index):
        file = self.path+'/data/'+varaible+'_surface_{:1.0f}.vi'.format(index)
        print(file)
        N = sum(1 for line in open(file))-6  # node number
        x_mesh,y_mesh = np.empty(N),np.empty(N)
        z_mesh,da_mesh = np.empty(N),np.empty(N)
        with open(file,'r') as f:
            xo = float(f.readline().split()[-1])
            yo = float(f.readline().split()[-1])
            zo = float(f.readline().split()[-1])
            theta = float(f.readline().split()[-1])
            f.readline()
            f.readline()
            for i,line in enumerate(f):
                x_mesh[i] = float(line.split()[0])
                y_mesh[i] = float(line.split()[1])
                z_mesh[i] = float(line.split()[2])
                da_mesh[i] = float(line.split()[3])

        pl.figure()
        for y,z in zip(y_mesh,z_mesh):
            pl.plot(y,z,'.',markersize=2)
        pl.axis('equal')
        pl.figure()

        th_mesh = np.arctan2(x_mesh-xo,y_mesh-yo)
        #r_mesh = np.sqrt((x_mesh-xo)**2+(y_mesh-yo)**2)
        r_mesh = (y_mesh-yo)/np.cos(theta)
        dy_mesh = -r_mesh#-(r_mesh-np.mean(r_mesh))
        y_mesh = dy_mesh
        mesh = self.store_mesh(N,r_mesh,th_mesh,z_mesh,dy_mesh,y_mesh)
        return mesh

    def grid_mesh(self,mesh):
        Ngg = 30*mesh['N']#50*N  # super-sample
        zmm = [np.min(mesh['z']),np.max(mesh['z'])]  # min,max
        ymm = [np.min(mesh['y']),np.max(mesh['y'])]  # min,max
        dz = np.diff(zmm)
        dy = np.diff(ymm)
        AR = dz/dy
        ny = np.round(np.sqrt(Ngg/AR))
        nz = np.round(Ngg/ny)
        z_space = np.linspace(zmm[0],zmm[1],nz)
        y_space = np.linspace(ymm[0],ymm[1],ny)
        z_map,y_map = np.meshgrid(z_space,y_space,indexing='ij')
        mesh['z_map'],mesh['y_map'] = z_map,y_map
        mesh['axes'] = [ymm[0],ymm[1],zmm[0],zmm[1]]

    def set_axis(self,xlim=[0,1],ylim=[0,1]):
        axis = self.mesh['n']['axes']
        xo,yo = axis[0],axis[2]
        dx,dy = np.diff(axis[:2]),np.diff(axis[2:])
        for i in range(2):
            self.mesh['n']['axes'][i] = xo+xlim[i]*dx
            self.mesh['n']['axes'][i+2] = yo+ylim[i]*dy

    def triangulate(self):
        self.points = np.array([self.mesh['n']['y'],
                                self.mesh['n']['z']]).T
        self.tri = Delaunay(self.points)
        cent = np.empty((self.tri.nsimplex,2))
        for i,v in enumerate(self.tri.vertices):
            for j in range(2):
                cent[i,j] = sum(self.points[v,j])/3
        self.el = np.empty(self.tri.nsimplex,dtype='int')
        for i,c in enumerate(cent):
            self.el[i] = np.argmin((self.mesh['e']['y']-c[0])**2+
                                   (self.mesh['e']['z']-c[1])**2)
        self.verts = np.empty((self.tri.nsimplex,3,2))
        for i,v in enumerate(self.tri.vertices):
            self.verts[i,:,:] = self.points[v]
        self.verts[:,:,1] *= -1  # flip z coordinate

    def plot_mesh(self,ax):
        ax.triplot(self.points[:,0], self.points[:,1],
                   self.tri.simplices.copy(),linewidth=0.75)

    def plot(self,var,ax,clim=[]):
        if var in ['T','V','J','BFE']:
            self.plot_node(var,ax,clim=clim)
        else:
            self.plot_elem(var,ax,clim=clim)
        self.plot_mesh(ax)

    def set_clim(self,var,scale,clim=[]):
        if clim:
            self.clim[var][0],self.clim[var][1] = clim[0],clim[1]
        vmin,vmax = self.clim[var][0],self.clim[var][1]
        if scale is 'log':
            if vmin == 0:
                vmin = 0.05*self.clim[var][1]
                self.clim[var][0] = vmin
            if vmin < 0:
                vmin = 5
            norm = LogNorm(vmin=vmin,vmax=vmax)
        else:
            print(vmin,vmax)
            norm = Normalize(vmin=vmin,vmax=vmax)
        return norm

    def plot_node(self,var,ax,clim=[],plot_mesh=True):
        if var in ['T']:
            mesh = self.mesh['n']
        else:
            mesh = self.mesh['e']
        var_map = griddata((mesh['y'],mesh['z']),
                           self.data[var][self.cplane-1][:],
                           (mesh['y_map'],mesh['z_map']),method='linear')
        norm = self.set_clim(var,'lin',clim=clim)
        #norm = Normalize(vmin=-2,vmax=2)
        cm = pl.get_cmap('afmhot',lut=self.lut)
        self.im[var] = ax.pcolor(mesh['y_map'],-mesh['z_map'],
                                 var_map,cmap=cm,
                                 norm=norm)  # RdYlBu_r
        corners = [mesh['y_map'].min(),mesh['y_map'].max(),
                   mesh['z_map'].min(),mesh['z_map'].max()]
        ax.plot([corners[0],corners[0]],[corners[2],corners[3]],'k',linewidth=0.5,alpha=0.5)
        ax.plot([corners[1],corners[1]],[corners[2],corners[3]],'k',linewidth=0.5,alpha=0.5)
        ax.plot([corners[0],corners[1]],[corners[2],corners[2]],'k',linewidth=0.5,alpha=0.5)
        ax.plot([corners[0],corners[1]],[corners[3],corners[3]],'k',linewidth=0.5,alpha=0.5)
        #ax.set_xlim(mesh['axes'][:2])
        #ax.set_ylim(mesh['axes'][2:])

    def plot_elem(self,var,ax,clim=[]):
        norm = self.set_clim(var,'lin',clim=clim)
        norm = Normalize(vmin=-0.16,vmax=0)
        data = self.data[var][self.cplane-1][:][self.el]
        if var in ['J']:
            cm = pl.get_cmap('Reds_r',self.lut)
        else:
            cm = pl.get_cmap('gist_gray',self.lut)
        coll = PolyCollection(self.verts,array=data,
                              cmap=cm,norm=norm,edgecolors='none')
        self.im[var] = ax.add_collection(coll)
        ax.set_xlim(self.mesh['n']['axes'][:2])
        ax.set_ylim(self.mesh['n']['axes'][2:])
        #self.plot_mesh(ax)


"""
    manly
    ~~~~~
    This script is used (through its' cli) to extract information from
    manual pages. More specifically, it tells the user, how the given
    flags modify a programs behaviour.
"""
from __future__ import print_function

__author__ = 'Carl Bordum Hansen'
__version__ = '0.3.1'

import sys
import subprocess
import re

_ANSI_BOLD = '\033[1m{}\033[0m'

HELP = """Usage: manly COMMAND FLAGS...
explain commands

Example:
    $ manly rm --preserve-root -rf

    rm - remove files or directories
    ================================

        -f, --force
                ignore nonexistent files and arguments, never prompt

        --preserve-root
                do not remove '/' (default)

        -r, -R, --recursive
                remove directories and their contents recursively

Arguments:
  -h, --help            display this help and exit.
  -v, --version         display version information and exit.

Project resides at <https://github.com/Zaab1t/manly>"""

VERSION = ('manly %s\nCopyright (c) 2017 %s.\nMIT License: see LICENSE.\n\n'
           'Written by %s and Mark Jameson.') % (
                   __version__, __author__, __author__)

def parse_flags(raw_flags, single_dash=False):
    '''Split concatenated flags (eg. ls' -la) into individual flags
    (eg. '-la' -> '-l', '-a').

    Args:
        raw_flags (list): The flags as they would be given normally.
        single_dash (bool): Indicate whether a manpage use long names
            prefixed with only one dash e.g. -nostdinc

    Returns:
        flags (list): The disassembled concatenations of flags, and regular
            verbose flags as given.
    '''
    flags = []
    for flag in raw_flags:
        if flag.startswith('--') or single_dash:
            flags.append(flag)
        elif flag.startswith('-'):
            for char in flag[1:]:
                flags.append('-' + char)
    return flags

def parse_manpage(page, args):
    '''Scan the manpage for blocks of text, and check if the found blocks
    have sections that match the general manpage-flag descriptor style.

    Args:
        page (str): The utf-8 encoded manpage.
        args (iter): An iterable of flags passed to check against.

    Returns:
        output (list): The blocks of the manpage that match the given flags.
    '''
    current_section = []
    output = []

    for line in page.splitlines():
        line = line + '\n'
        if line != '\n':
            current_section.append(line)
            continue

        section = ''.join(current_section)
        section_top = section.strip().split('\n')[:2]
        first_line = section_top[0].split(',')

        for arg in args:
            try:
                if any(seg.strip().startswith(arg) for seg in first_line) \
                  or section_top[1].strip().startswith(arg):
                    section = re.sub(r'(^|\s){}'.format(arg),
                                     _ANSI_BOLD.format(arg),
                                     section)
                    output.append(section.rstrip())
                    break
            except IndexError:
                pass
        current_section = []
    return output

def main():
    # HANDLE ALL INPUT
    try:
        command = sys.argv[1]
    except IndexError:
        print("manly: missing COMMAND\n"
              "Try 'manly --help' for more information.")
        sys.exit(0)
    if len(sys.argv) == 2:
        if sys.argv[1] in ('-h', '--help'):
            print(HELP)
            sys.exit(0)
        if sys.argv[1] in ('-v', '--version'):
            print(VERSION)
            sys.exit(0)
        print("manly: missing flags\n"
              "Try 'manly --help' for more information.")
        sys.exit(2)
    if sys.argv[1] == 'manly':
        print('There are no turtles.')
        sys.exit(0)
    try:
        manpage = subprocess.check_output(
            ['(export MANWIDTH=80; man %s)' % command],
            shell=True,
        ).decode('utf-8')
    except subprocess.CalledProcessError:
        sys.exit(16)  # because that's the exit status that `man` uses.

    # LOGIC
    uses_single_dash_names = any((re.match(r'\s+-\w{2,}', line) for line in
                                  manpage.splitlines()))
    flags = parse_flags(sys.argv[2:], uses_single_dash_names)
    output = parse_manpage(manpage, flags)
    title = _ANSI_BOLD.format(
            re.search(
                r'(?<=^NAME\n\s{5}).+',
                manpage,
                re.MULTILINE
            ).group(0).strip())

    # OUTPUT
    if output:
        print('\n%s' % title)
        print('=' * (len(title) - 8), end='\n\n')
        for flag in output:
            print(flag, end='\n\n')
    else:
        print('No flags found.')

if __name__ == '__main__':
    main()


# StreamLit setup
import streamlit as st
from PIL import Image

# Import libraries and dependencies
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from itertools import combinations_with_replacement

# Timeseries packages
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import adfuller
from statsmodels.tsa.arima_model import ARIMA

# MACD packages
import yfinance as yf
import vectorbt as vbt

# GIF
#st.image("Trading.gif", width=None)
st.image("https://www.wealthandfinance-news.com/wp-content/webp-express/webp-images/uploads/2020/10/stocks.jpg.webp")

st.title("Determine trade signals based upon MACD traces")

st.write('''
		 This app takes your stock ticker and provides you with a summary of the MACD signal.
		 ''')

st.header("Enter your stock ticker symbol")

ticker_symbol = st.text_input('(Example: AAPL)')

st.header("Enter amount you want to invest in this stock")
cash_inv = st.text_input('(Example: 1000)')

stock_name = ticker_symbol

if ticker_symbol:

    tickers = yf.download(tickers = stock_name,
                          start = "2020-01-01",
                          period="max",
                          interval = "1d")

    st.header("Here is the tail of the main dataframe")
    st.table(tickers.tail())

    # Drop duplicates
    tickers.drop_duplicates(inplace=False)

    # Drop NA and infinite values
    tickers = tickers.replace(-np.inf, np.nan).dropna()

    # Plot ACF
    st.header('ACF plot is a plot that represents the correlation between a time series and lags of itself')
    plt.rcParams["figure.figsize"] = [10,5]
    st.pyplot(plot_acf(tickers.Close, lags=20))

    # Plot PACF
    st.header('PACF plot is a plot that represents the partial correlation between a time series and lags of itself')
    plt.rcParams["figure.figsize"] = [10,5]
    st.pyplot(plot_pacf(tickers.Close, zero=False, lags=20))

    # Get all combinations of [1, 2, 1]
    comb1 = combinations_with_replacement([1, 1, 1], 3)

    variables_list1 = []

    # Print the obtained combinations
    for i in list(comb1):
        if i[1] == 1:
            variables_list1.append(i)

    # Get all combinations of [1, 1, 2]
    comb2 = combinations_with_replacement([1, 1, 2], 3)

    variables_list2 = []

    # Print the obtained combinations
    for i in list(comb2):
        if i[1] == 1:
            variables_list2.append(i)

    # Get all combinations of [1, 1, 3]
#     comb3 = combinations_with_replacement([1, 1, 3], 3)

#     variables_list3 = []

#     # Print the obtained combinations
#     for i in list(comb3):
#         if i[1] == 1:
#             variables_list3.append(i)

    # Get all combinations of [2, 1, 3]
#     comb4 = combinations_with_replacement([2, 1, 3], 3)

#     variables_list4 = []

#     # Print the obtained combinations
#     for i in list(comb4):
#         if i[1] == 1:
#             variables_list4.append(i)

    variables_list = variables_list1 #+ variables_list2 #+ variables_list3 + variables_list4

    results_aic = []
    results_bic = []

    for combination in variables_list:
        model = ARIMA(tickers['Close'],
                      order=combination)

        results = model.fit()

        results_aic.append(results.aic)
        results_bic.append(results.bic)

    df = pd.DataFrame({'aic':results_aic,
                       'bic':results_bic},
                      index=variables_list).sort_values(by='aic')

    aic_df_sorted = df.sort_values(by=['aic'], ascending=False)

    # Rerun ARIMA using optimised AIC (https://stats.stackexchange.com/questions/577/is-there-any-reason-to-prefer-the-aic-or-bic-over-the-other)
    model_refined = ARIMA(tickers['Close'],
                          order=aic_df_sorted.index[0])

    results_refined = model_refined.fit()

    st.text(results_refined.summary())

    # Forecast
    fc, se, conf = results_refined.forecast(5, alpha=0.05)  # 95% conf

    # Make as pandas series
    fc_series = pd.Series(fc, index=pd.date_range(tickers['Close'].index[-1] + datetime.timedelta(days=1), periods=5).tolist())
    lower_series = pd.Series(conf[:, 0], index=pd.date_range(tickers['Close'].index[-1] + datetime.timedelta(days=1), periods=5).tolist())
    upper_series = pd.Series(conf[:, 1], index=pd.date_range(tickers['Close'].index[-1] + datetime.timedelta(days=1), periods=5).tolist())

    plt.figure(figsize=(12,5), dpi=100)
    plt.plot(tickers['Close'], label='Actual')
    plt.plot(fc_series, label='Forecast')
    plt.fill_between(lower_series.index, lower_series, upper_series,
                     color='k', alpha=.15)
    plt.title('Forecast vs Actuals')
    plt.legend(loc='upper left', fontsize=8)
    st.pyplot(plt)

    # Forecast close prices
    predicted_df = pd.DataFrame(results_refined.forecast(steps=5)[0],
                                index=pd.date_range(tickers['Close'].index[-1] + datetime.timedelta(days=1), periods=5).tolist())

    #plt.rcParams["figure.figsize"] = [10, 5]

    pred_plot = predicted_df.plot(title="5 Days Forecast")

    actual_close = tickers['Close']

    # Concat data
    prev_predit_df = pd.concat([actual_close, predicted_df],
                               axis=0)

    # Rename col header
    prev_predit_df.rename(columns={0: "Close"}, inplace=True)

    # Rename index
    prev_predit_df.index.names=["Date"]

    tickers_df = prev_predit_df.copy()

    # Calculate MACD data and add to dictionary
    macd_list = {}

    # MACD data
    ewm_fast = tickers_df["Close"].ewm(span = 12, adjust = False).mean()
    ewm_slow = tickers_df["Close"].ewm(span = 26, adjust = False).mean()
    macd = pd.DataFrame(ewm_fast - ewm_slow)
    macd = macd.rename(columns = {"Close":"macd"})

    # Signal data
    signal = pd.DataFrame(macd["macd"].ewm(span = 9, adjust = False).mean()).rename(columns = {"macd":"signal"})

    # Histogram data
    histogram = pd.DataFrame(macd["macd"] - signal["signal"]).rename(columns = {0:("hist")})
    ticker_macd = pd.concat([macd, signal, histogram],
                            axis = 1)

    macd_list[ticker_symbol] = ticker_macd

    # Plot MACD data per individual stock

    plt.rcParams["figure.figsize"] = [18,12]

    ax1 = plt.subplot2grid((15,1), (0,0), rowspan = 5, colspan = 5)
    ax2 = plt.subplot2grid((15,1), (7,0), rowspan = 3, colspan = 5)
    ax1.plot(tickers_df["Close"], color = 'gray', linewidth = 2, label = ticker_symbol)
    ax1.set_title(f'{ticker_symbol} MACD SIGNALS')

    ax2.plot(macd_list[ticker_symbol]['macd'],
             color = 'skyblue',
             linewidth = 1.5,
             label = 'MACD')

    ax2.plot(macd_list[ticker_symbol]['signal'],
             color = 'orange',
             linewidth = 1.5,
             label = 'SIGNAL')

    for i in range(len(macd_list[ticker_symbol])):

        if str(macd_list[ticker_symbol]['hist'][i])[0] == '-':

            ax2.bar(macd_list[ticker_symbol].index[i],
                    macd_list[ticker_symbol]['hist'][i],
                    color = 'red')
        else:

            ax2.bar(macd_list[ticker_symbol].index[i],
                    macd_list[ticker_symbol]['hist'][i],
                    color = 'green')

    plt.legend(loc = 'lower right')
    st.pyplot(plt)

    def implement_macd_strategy(prices, data):
        buy_price = []
        sell_price = []
        macd_signal = []
        signal = 0

        # For loop for range of dates
        for i in range(len(data)):

            # Conditional produce signal to buy stock
            if data['macd'][i] > data['signal'][i]:
                if signal != 1:
                    buy_price.append(prices[i])
                    sell_price.append(np.nan)
                    signal = 1
                    macd_signal.append(signal)
                else:
                    buy_price.append(np.nan)
                    sell_price.append(np.nan)
                    macd_signal.append(0)

            # Conditional produce signal to sell stock
            elif data['macd'][i] < data['signal'][i]:
                if signal != -1:
                    buy_price.append(np.nan)
                    sell_price.append(prices[i])
                    signal = -1
                    macd_signal.append(signal)
                else:
                    buy_price.append(np.nan)
                    sell_price.append(np.nan)
                    macd_signal.append(0)
            else:
                buy_price.append(np.nan)
                sell_price.append(np.nan)
                macd_signal.append(0)

        return buy_price, sell_price, macd_signal

     # Run trade strategy and plot buy and sell signals

    buy_price, sell_price, macd_signal = implement_macd_strategy(tickers_df["Close"], macd_list[ticker_symbol])

    plt.rcParams["figure.figsize"] = [18,12]

    ax1 = plt.subplot2grid((15,1), (0,0), rowspan = 5, colspan = 1)

    ax2 = plt.subplot2grid((15,1), (7,0), rowspan = 3, colspan = 1)

    ax1.plot(tickers_df["Close"],
             color = 'gray',
             linewidth = 2,
             label = ticker_symbol)

    ax1.plot(tickers_df["Close"].index,
             buy_price,
             marker = '^',
             color = 'green',
             markersize = 6,
             label = 'BUY SIGNAL',
             linewidth = 0)

    ax1.plot(tickers_df["Close"].index,
             sell_price,
             marker = 'v',
             color = 'r',
             markersize = 6,
             label = 'SELL SIGNAL',
             linewidth = 0)

    ax1.legend()

    ax1.set_title(f'{ticker_symbol} MACD BUY-SELL SIGNAL')

    ax2.plot(macd_list[ticker_symbol]['macd'],
             color = 'skyblue',
             linewidth = 1.5,
             label = 'MACD')

    ax2.plot(macd_list[ticker_symbol]['signal'],
             color = 'orange',
             linewidth = 1.5,
             label = 'SIGNAL')

    for i in range(len(macd_list[ticker_symbol])):

        if str(macd_list[ticker_symbol]['hist'][i])[0] == '-':

            ax2.bar(macd_list[ticker_symbol].index[i],
                    macd_list[ticker_symbol]['hist'][i],
                    color = 'r')
        else:

            ax2.bar(macd_list[ticker_symbol].index[i],
                    macd_list[ticker_symbol]['hist'][i],
                    color = 'g')

    plt.legend(loc = 'lower right')
    st.pyplot(plt)

    # Run strategy to create position
    stock_strategy = {}

    buy_price, sell_price, macd_signal = implement_macd_strategy(tickers_df["Close"], macd_list[stock_name])

    position = []

    for i in range(len(macd_signal)):
        if macd_signal[i] > 1:
            position.append(0)
        else:
            position.append(1)

    for i in range(len(tickers_df['Close'])):

        if macd_signal[i] == 1:
            position[i] = 1
        elif macd_signal[i] == -1:
            position[i] = 0
        else:
            position[i] = position[i-1]

        macd = macd_list[stock_name]['macd']

        signal = macd_list[stock_name]['signal']

        close_price = tickers_df["Close"]

        macd_signal_df = pd.DataFrame(macd_signal).rename(columns = {0:'macd_signal'}).set_index(tickers_df["Close"].index)

        position = pd.DataFrame(position).rename(columns = {0:'macd_position'}).set_index(tickers_df["Close"].index)

        frames = [close_price, macd, signal, macd_signal_df, position]

        stock_strategy = pd.concat(frames,
                                   join = 'inner',
                                   axis = 1)

    # Create dictionary and populate according to macd_signal
    stock_signals = {}

    for ticker in tickers:
        entries = []
        exits = []

        for sig in stock_strategy["macd_signal"]:

            if sig == -1:
                entries.append("False")
                exits.append("True")
            elif sig == 1:
                entries.append("True")
                exits.append("False")
            else:
                entries.append("False")
                exits.append("False")

        entries = pd.Series(entries,
                            index = tickers_df["Close"].index)

        exits = pd.Series(exits, index = tickers_df["Close"].index)

        # Change type to bool
        entries = entries == "True"
        exits = exits == "True"

        # Create dataframe
        entries = pd.DataFrame(entries).rename(columns = {0:'entries'}).set_index(tickers_df["Close"].index)

        exits = pd.DataFrame(exits).rename(columns = {0:'exits'}).set_index(tickers_df["Close"].index)

        close_price = tickers_df["Close"]

        frames = [close_price,
                  entries,
                  exits]

        signals = pd.concat(frames, join = 'inner', axis = 1)

        stock_signals[ticker] = signals

    # Initial investment
    init_cash = int(cash_inv)

    # Total profit earned from holding stock. Timeframe 3 months
    for ticker in stock_name:

        price = vbt.YFData.download(ticker, start='2021-01-01').get('Close')

        portfolio = vbt.Portfolio.from_holding(price,
                                               init_cash = init_cash)

    portfolio.total_profit()

    st.header(f"With an inital investment of ${init_cash} in this stock, your total profit of just holding the stock from 2021-01-01 will be ${portfolio.total_profit():.2f}")

    total_profit = []

    for ticker in tickers:
        # Build portfolio using macd signals
        portfolio = vbt.Portfolio.from_signals(stock_signals[ticker]["Close"],
                                               stock_signals[ticker]["entries"],
                                               stock_signals[ticker]["exits"],
                                               init_cash = init_cash)

        # Total profit
        total_profit.append(portfolio.total_profit())

    st.header(f"With an inital investment of ${init_cash} in this stock, the total profit of trading based upon MACD signals will be ${sum(total_profit):.2f}")


"""Module for connection to Twitter API."""
import tweepy
import json
import logging
from os import environ

logger = logging.getLogger()

def create_api():
    """Create the Twitter API object."""
    CONSUMER_KEY = environ['KEY']
    CONSUMER_SECRET = environ['SECRET_KEY']
    ACCESS_KEY = environ['ACCESS']
    ACCESS_SECRET = environ['ACCESS_SECRET']

    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)

    auth.set_access_token(ACCESS_KEY, ACCESS_SECRET)

    api = tweepy.API(auth, wait_on_rate_limit=True,
                     wait_on_rate_limit_notify=True)

    try:
        api.verify_credentials()
    except Exception as e:
        logger.error("Error creating API", exc_info=True)
        raise e
    logger.info("API created")
    return api


n=int(input())
arr1=[int(i) for i in input().split()]
arr1.sort()
m=int(input())
arr2=[int(i) for i in input().split()]

for i in arr2:
    start=0
    end=n-1
    while start<=end:
        mid=(start+end)//2
        if arr1[mid]==i:
            break
        if arr1[mid]>i:
            end=mid-1
        else:
            start=mid+1
    if arr1[mid]==i:
        print(arr1.count(i),end=" ")
    else:
        print(0,end=" ")


# coding=utf-8
# Copyright (c) DIRECT Contributors
import logging
import random
import numpy as np
import torch
import os
import sys
import pathlib
import h5py

import direct.launch

from direct.common.subsample import CalgaryCampinasMaskFunc
from direct.data.mri_transforms import build_mri_transforms, Compose
from direct.data.datasets import build_dataset
from direct.environment import setup_environment, Args

logger = logging.getLogger(__name__)

class CreateSamplingMask:
    """
    Create sampling mask from a dictionary.
    """

    def __init__(self, masks_dict):
        self.masks_dict = masks_dict

    def __call__(self, sample):
        sample["sampling_mask"] = self.masks_dict[sample["filename"]][
            np.newaxis, ..., np.newaxis
        ]
        sample["acs_mask"] = torch.from_numpy(
            CalgaryCampinasMaskFunc(accelerations=[]).circular_centered_mask(
                sample["kspace"].shape[1:], 18
            )
        )

        return sample

def volume_post_processing(volume):
    # Only relevant for the Calgary Campinas challenge.
    crop = (50, -50)
    if crop:
        volume = volume[slice(*crop)]

    # Only needed to fix a bug in Calgary Campinas training
    volume = volume / np.sqrt(np.prod(volume.shape[1:]))
    return volume

def setup_inference(
    run_name,
    data_root,
    base_directory,
    output_directory,
    volume_processing_func,
    cfg_filename,
    checkpoint,
    masks,
    device,
    num_workers,
    machine_rank,
):

    # TODO(jt): This is a duplicate line, check how this can be merged with train_rim.py
    # TODO(jt): Log elsewhere than for training.
    # TODO(jt): Logging is different when having multiple processes.
    # TODO(jt): This can be merged with run_rim.py
    env = setup_environment(
        run_name, base_directory, cfg_filename, device, machine_rank
    )

    # Process all masks
    all_maps = masks.glob("*.npy")
    logger.info("Loading masks...")
    masks_dict = {
        filename.name.replace(".npy", ".h5"): np.load(filename) for filename in all_maps
    }
    logger.info(f"Loaded {len(masks_dict)} masks.")

    # Don't add the mask func, add it separately
    mri_transforms = build_mri_transforms(
        forward_operator=env.forward_operator,
        backward_operator=env.backward_operator,
        mask_func=None,
        crop=None,  # No cropping needed for testing
        image_center_crop=True,
        estimate_sensitivity_maps=env.cfg.training.dataset.transforms.estimate_sensitivity_maps,
    )

    mri_transforms = Compose([CreateSamplingMask(masks_dict), mri_transforms])

    # Trigger cudnn benchmark when the number of different input shapes is small.
    torch.backends.cudnn.benchmark = True

    # TODO(jt): batches should have constant shapes! This works for Calgary Campinas because they are all with 256
    # slices.
    if len(env.cfg.validation.datasets) > 1:
        logger.warning("Multiple datasets given. Will only predict the first.")

    data = build_dataset(
        env.cfg.validation.dataset[0].name,
        data_root,
        sensitivity_maps=None,
        transforms=mri_transforms,
    )
    logger.info(f"Inference data size: {len(data)}.")

    # Just to make sure.
    torch.cuda.empty_cache()

    # Run prediction
    output = env.engine.predict(
        data, env.experiment_dir, checkpoint_number=checkpoint, num_workers=num_workers,
    )

    # Create output directory
    output_directory.mkdir(exist_ok=True, parents=True)

    # TODO(jt): Perhaps aggregation to the main process would be most optimal here before writing.
    for idx, filename in enumerate(output):
        # The output has shape (depth, 1, height, width)
        logger.info(
            f"({idx + 1}/{len(output)}): Writing {output_directory / filename}..."
        )
        reconstruction = (
            torch.stack([_[1].rename(None) for _ in output[filename]])
            .numpy()[:, 0, ...]
            .astype(np.float)
        )
        reconstruction = volume_processing_func(reconstruction)

        with h5py.File(output_directory / filename, "w") as f:
            f.create_dataset("reconstruction", data=reconstruction)

if __name__ == "__main__":
    epilog = f"""
        Examples:
        Run on single machine:
            $ {sys.argv[0]} test_root output_directory --num-gpus 8 --cfg cfg.yaml
        Run on multiple machines:
            (machine0)$ {sys.argv[0]} test_root output_directory --machine-rank 0 --num-machines 2 --dist-url <URL> [--other-flags]
            (machine1)$ {sys.argv[0]} test_root output_directory --machine-rank 1 --num-machines 2 --dist-url <URL> [--other-flags]
        """

    parser = Args(epilog=epilog)
    parser.add_argument(
        "test_root", type=pathlib.Path, help="Path to the validation data."
    )
    parser.add_argument(
        "experiment_dir", type=pathlib.Path, help="Path to the experiment directory.",
    )
    parser.add_argument(
        "output_directory", type=pathlib.Path, help="Path to the output directory."
    )
    parser.add_argument("--masks", type=pathlib.Path, help="Path to the masks.")
    parser.add_argument("--checkpoint", type=int, required=True, help="Checkpoint number.")

    args = parser.parse_args()

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)

    run_name = (
        args.name if args.name is not None else os.path.basename(args.cfg_file)[:-5]
    )

    direct.launch.launch(
        setup_inference,
        args.num_machines,
        args.num_gpus,
        args.machine_rank,
        args.dist_url,
        run_name,
        args.test_root,
        args.experiment_dir,
        args.output_directory,
        volume_post_processing,
        args.cfg_file,
        args.checkpoint,
        args.masks,
        args.device,
        args.num_workers,
        args.machine_rank,
    )


import sh
app_name='xinput'
mouse_id=10

file = open('bla.txt','a')
for line in sh.xinput("test", mouse_id, _iter=True):
    file.write(line)
    #print(line.rstrip("\n"))
file.close()

# Subprocess Beispiel
#g = subprocess.Popen(["xinput","test",str(mouse_id)], stdout=subprocess.PIPE)
creator='procs'
version='0.0.1'


__author__ = 'Géraud'

def parse_input(file):
    replacements = {}
    molecule = None

    for line in file:
        splitted = line[:-1].split(" => ")
        if len(splitted) == 2:
            key = splitted[0]
            replace = splitted[1]
            if key in replacements:
                replacements[key].append(replace)
            else:
                replacements[key] = [replace]
        elif splitted[0] != "":
            molecule = splitted[0]
    return replacements, molecule

if __name__ == '__main__':
    with open('input.txt') as file:
        replacements, medicine_molecule = parse_input(file)

    combinations = []
    skip = 0
    for index, molecule in enumerate(medicine_molecule):
        if skip > 0:
            skip -= 1
            continue
        if medicine_molecule[index:index + 2] in replacements:
            skip = 1
            replaces = replacements[medicine_molecule[index:index + 2]]
            slice_left = slice(0, index)
            slice_right = slice(index + 2, None)
        elif medicine_molecule[index] in replacements:
            replaces = replacements[medicine_molecule[index]]
            slice_left = slice(0, index)
            slice_right = slice(index + 1, None)
        else:
            replaces = []
        for replace in replaces:
            combinations.append(medicine_molecule[slice_left] + replace + medicine_molecule[slice_right])
    print("Part 1: {}".format(len(set(combinations))))


# -*- encoding: utf-8 -*-
'''
@File    :   test_trade_query.py
@Time    :   2020/11/26 09:09:12
@Author  :   Jadenyu
@Version :   Python 3.7.6
@State   :   农行-单笔订单查询接口用例
'''

# here put the import lib

import os,sys
sys.path.append(os.getcwd().split("scripts1",1)[0])
from scripts1.apis.pay import pay_api
from scripts1.datas.pay.data_abc_002_trade_query import *
from scripts1.model.pay.pay_req import pay_req

api = pay_api.Trade_query.api

def data_list(test_host):
    """获取测试集"""
    data = Trade_query_abc_data()
    return data

import pytest
cases = []
for i in data_list().cases:
    cases.append ((i["title"],i["case"],i["expection"]))
    #break
@pytest.mark.parametrize("title,case,expection",cases)
def test_ccb_trade_query(test_host,title,case,expection):
    """农行-单笔订单查询"""
    title = title
    resp = pay_req(test_host,api,case,"99999998")
    assert resp.status_code == 200
    assert expection == resp.json()["rspCode"]

if __name__ == "__main__":

    import json
    import requests
    cases_list = data_list()

    for i in range(len(cases_list.cases)):
        print("测试序号：",i)
        if i == 700:
            print("跳过：",i)
        elif i >=0 :
            title = cases_list.cases[i]["title"]
            case = cases_list.cases[i]["case"]

            resp = pay_req("100",api,case,"99999998")
            print(resp.status_code)
            print(resp.json())

            with open("testresult.txt","a+",encoding="utf-8")as f:
                f.write("单笔订单查询接口"+title + ":" + "\n")
                f.write(json.dumps(resp.json(),ensure_ascii=False) + "\n")
                f.write("\n")