import unittest
from unittest import mock

import numpy as np

from dacbench.benchmarks import LubyBenchmark
from dacbench.wrappers import PerformanceTrackingWrapper

class TestPerformanceWrapper(unittest.TestCase):
    def test_init(self):
        bench = LubyBenchmark()
        env = bench.get_environment()
        wrapped = PerformanceTrackingWrapper(env)
        self.assertTrue(len(wrapped.overall_performance) == 0)
        self.assertTrue(wrapped.performance_interval is None)
        wrapped.instance = [0]
        self.assertTrue(wrapped.instance[0] == 0)

        wrapped2 = PerformanceTrackingWrapper(env, 10)
        self.assertTrue(len(wrapped2.overall_performance) == 0)
        self.assertTrue(wrapped2.performance_interval == 10)
        self.assertTrue(len(wrapped2.performance_intervals) == 0)
        self.assertTrue(len(wrapped2.current_performance) == 0)

    def test_step(self):
        bench = LubyBenchmark()
        bench.config.instance_set = {0: [0, 0], 1: [1, 1], 2: [3, 4], 3: [5, 6]}
        env = bench.get_environment()
        wrapped = PerformanceTrackingWrapper(env, 2)

        state, info = wrapped.reset()
        self.assertTrue(len(state) > 1)
        self.assertTrue(issubclass(type(info), dict))

        state, reward, terminated, truncated, _ = wrapped.step(1)
        self.assertTrue(len(state) > 1)
        self.assertTrue(reward <= 0)
        self.assertFalse(terminated)
        self.assertFalse(truncated)

        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)

        self.assertTrue(len(wrapped.overall_performance) == 1)
        self.assertTrue(len(wrapped.performance_intervals) == 0)
        self.assertTrue(len(wrapped.current_performance) == 1)
        self.assertTrue(len(wrapped.instance_performances.keys()) == 1)

        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)

        self.assertTrue(len(wrapped.performance_intervals) == 1)
        self.assertTrue(len(wrapped.current_performance) == 1)

        wrapped.reset()
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)
        wrapped.reset()
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)
        self.assertTrue(len(wrapped.instance_performances.keys()) == 3)

        wrapped.reset()
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)
        wrapped.reset()
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)
        self.assertTrue(len(wrapped.instance_performances.keys()) == 4)

    def test_get_performance(self):
        bench = LubyBenchmark()
        env = bench.get_environment()
        wrapped = PerformanceTrackingWrapper(env)
        wrapped.reset()
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped.step(1)
        wrapped2 = PerformanceTrackingWrapper(env, 2)
        wrapped2.reset()
        terminated, truncated = False, False
        while not (terminated or truncated):
            _, _, terminated, truncated, _ = wrapped2.step(1)
        wrapped3 = PerformanceTrackingWrapper(env, 2, track_instance_performance=False)
        wrapped3.reset()
        for i in range(5):
            wrapped3.step(i)
        wrapped4 = PerformanceTrackingWrapper(env, track_instance_performance=False)
        wrapped4.reset()
        for i in range(5):
            wrapped4.step(i)

        overall, instance_performance = wrapped.get_performance()
        overall_perf, interval_perf, instance_perf = wrapped2.get_performance()
        overall_performance_only = wrapped4.get_performance()
        overall_performance, intervals = wrapped3.get_performance()
        self.assertTrue(
            np.array_equal(
                np.round(overall_performance, decimals=2),
                np.round(overall_performance_only, decimals=2),
            )
        )

        self.assertTrue(
            np.array_equal(
                np.round(overall_perf, decimals=2), np.round(overall, decimals=2)
            )
        )

        self.assertTrue(len(instance_performance.keys()) == 1)
        self.assertTrue(len(list(instance_performance.values())[0]) == 1)
        self.assertTrue(len(instance_perf.keys()) == 1)
        self.assertTrue(len(list(instance_perf.values())[0]) == 1)

        self.assertTrue(len(intervals) == 1)
        self.assertTrue(len(intervals[0]) == 0)
        self.assertTrue(len(interval_perf) == 1)
        self.assertTrue(len(interval_perf[0]) == 1)

    @mock.patch("dacbench.wrappers.performance_tracking_wrapper.plt")
    def test_render(self, mock_plt):
        bench = LubyBenchmark()
        env = bench.get_environment()
        env = PerformanceTrackingWrapper(env)
        for _ in range(10):
            terminated, truncated = False, False
            env.reset()
            while not (terminated or truncated):
                _, _, terminated, truncated, _ = env.step(1)
        env.render_performance()
        self.assertTrue(mock_plt.show.called)
        env.render_instance_performance()
        self.assertTrue(mock_plt.show.called)


import numpy as np

def eval(pred, label):
    mat = np.zeros([3, 3])
    ind = ["bull", "bear", "neutual"]
    for i in range(len(pred)):
        mat[ind.index(pred[i]), ind.index(label[i])] += 1
    print("Confusion Matrix: [bull, bear, neutual], (pred, label)")
    print(mat)
    print("\nAccuracy")
    print((np.array(mat) * np.eye(3)).sum() / np.array(mat).sum())

def eval2(pred, label, length):
    import seaborn as sns
    import pandas as pd

    df = pd.DataFrame({"pred": pred, "label": label, "length": length})
    df["equal"] = df["pred"] == df["label"]

    L = []
    for size, sub in df.groupby(df["length"]):
        L.append([size, sub["equal"].sum() / len(sub), len(sub)])
    L = np.array(sorted(L, key=lambda x: x[0]))
    L = L[L[:, 2] > 50]
    sns.plt.plot(L[:, 0], L[:, 1])
    sns.plt.ylim([0, 1])
    sns.plt.show()


from torchvision.models import resnet50, ResNet50_Weights
import torch.nn as nn

# GradCamModel class with a ResNet pretrained model
class GradCamModel(nn.Module):
    def __init__(self):
        super(GradCamModel, self).__init__()

        # define the resnet50
        # self.resnet = resnet50(pretrained=True)
        self.resnet = resnet50(weights=ResNet50_Weights.DEFAULT)

        # isolate the feature blocks
        self.features = nn.Sequential(self.resnet.conv1,
                                      self.resnet.bn1,
                                      self.resnet.relu,
                                      self.resnet.maxpool,
                                      self.resnet.layer1,
                                      self.resnet.layer2,
                                      self.resnet.layer3,
                                      self.resnet.layer4)

        # average pooling layer
        self.avgpool = self.resnet.avgpool

        # classifier
        self.classifier = self.resnet.fc

        # gradient placeholder
        self.gradient = None

    # hook for the gradients
    def activations_hook(self, grad):
        self.gradient = grad

    def get_gradient(self):
        return self.gradient

    def get_activations(self, x):
        return self.features(x)

    def forward(self, x):

        # extract the features
        x = self.features(x)

        # register the hook
        h = x.register_hook(self.activations_hook)

        # complete the forward pass
        x = self.avgpool(x)
        x = x.view((1, -1))
        x = self.classifier(x)

        return x


import requests
from bs4 import BeautifulSoup
from datetime import datetime
import time
import ctypes

url = input("Enter your product URL: ")
amount_of_time = input("For how long do you want to check the price (in minutes): ")
aimed_price = input("The price I'm looking for: ")

headers = {'User Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'}
url_source = requests.get(url.strip(), headers=headers)
soup = BeautifulSoup(url_source.content, "lxml")

# NAME OF THE PRODUCT
name = soup.find(class_ ='page-title').text

# PRICE OF THE PRODUCT
price = soup.find(class_= 'product-new-price').text.strip()

# .99 or .00 from the price
for sup_price in soup.find_all('div', class_ = 'product-highlight product-page-pricing'):
    sup_extract =  sup_price.find('p', class_ = 'product-new-price')
    sup_extract1 = sup_extract.find('sup')
    sup = sup_extract1.text

full_price = (float(price[:-6].replace('.', '')) + (float(sup) / 100))

# TIME SPAN
time_to_end = time.time() + 60 * float(amount_of_time)

while time.time() < time_to_end:
    print("Name:  ", name.strip())
    print('Price: ', full_price)
    print('Time:  ',datetime.now().replace(microsecond=0))
    print('-'*40)
    time.sleep(1)  # Updates once per second
    if full_price <= float(aimed_price):
        MessageBox = ctypes.windll.user32.MessageBoxW
        MessageBox(None, 'Hello', 'Window title', 0)
        break


from pathlib import Path
import shutil

import bluepymm
from bluepymm import prepare_combos, run_combos, select_combos
import pandas as pd
import pytest

test_dir = "tests"

@pytest.fixture(autouse=True)
def setup_tests():
    """Deletes the tmp directory used in prepare step."""
    tmp_path = Path(test_dir) / "tmp"
    if tmp_path.exists() and tmp_path.is_dir():
        shutil.rmtree(tmp_path)

def test_select_output():
    """Runs all 3 steps and checks the output of select step."""
    prepare_config = "prepare.json"
    with bluepymm.tools.cd(test_dir):
        prepare_combos.prepare_combos(conf_filename=prepare_config, continu=False)

    run_config = "run.json"
    with bluepymm.tools.cd(test_dir):
        run_combos.run_combos(conf_filename=run_config)

    select_config = "select.json"
    with bluepymm.tools.cd(test_dir):
        select_combos.select_combos(conf_filename=select_config, n_processes=None)

    gt_df = pd.read_csv("tests/ground_truth/mecombo_emodel.tsv", sep="\t")
    res_df = pd.read_csv("tests/output_select/mecombo_emodel.tsv", sep="\t")

    pd.testing.assert_frame_equal(res_df, gt_df)


import datetime
import subprocess
import typing

import polib

from ..core import FileTransformer

def dictToPo(dic: typing.Mapping[str, str]) -> polib.POFile:
	poF = polib.POFile(encoding="utf-8")

	dt = str(datetime.datetime.now(tz=datetime.timezone.utc))
	poF.metadata.update(
		{
			"Project-Id-Version": "emojifilt",
			"POT-Creation-Date": dt,
			"PO-Revision-Date": dt,
			"Language": "emoji",
			"Content-Type": "text/plain; charset=UTF-8",
		}
	)

	for k, v in dic.items():
		poF.append(polib.POEntry(msgid=k, msgstr=v))

	poF.sort()
	return poF

def dumpPo(dic: typing.Mapping[str, str]):
	return str(dictToPo(dic))

def compileMoToPo(poSource: str) -> bytes:
	"""`polib` built-in compilation doesn't create a hashtable"""
	return bytes(subprocess.run(["msgfmt", "-o", "-", "-"], input=poSource.encode("utf-8"), capture_output=True).stdout)

def dumpMoWithHashtable(dic: typing.Mapping[str, str]) -> bytes:
	return compileMoToPo(dumpPo(dic))

poSerializer = FileTransformer("libintl_po", dumpPo, None, str, typing.Mapping[str, str], "po")
moSerializerWithHashtable = FileTransformer("libintl_mo_with_hashtable", dumpMoWithHashtable, None, bytes, typing.Mapping[str, str], "mo")


from datetime import datetime, timezone
from copy import deepcopy
from collections import defaultdict, OrderedDict
from typing import DefaultDict
from strategies.format_strategies.strategy import FormatStrategy
from strategies.format_strategies import MultiWayPlayerBetStrategy, DefaultStrategy, V1Strategy

local_timezone = datetime.now().astimezone().tzinfo

class Parser:
    def __init__(self, config) -> None:
        self.config = config
        self.strategy: FormatStrategy = None
        self.strategies = {
            'default': DefaultStrategy('default'),
            'multiwayPlayerBet': MultiWayPlayerBetStrategy('multiwayPlayerBet'),
            'v1': V1Strategy('v1')
        }
        self.player_name: str = ''

    def parse(self, event):
        self.response = {
            'default': None,
            'multiwayPlayerBet': {},
            'v1': None
        }
        event_info = self._get_event_info(event)
        if event_info:
            self.event_info = event_info
            self.response['default'] = deepcopy(event_info)
            self.response['v1'] = deepcopy(event_info)
            for market in event['Offers']:
                parsed_market = self._parse_market(market)
                if parsed_market:
                    self.strategy.append_market(self, parsed_market)

            return {
                "default": self.response['default'],
                "v1": self.response['v1'],
                "multiwayPlayerBet": [
                    {
                        **p,
                        'markets': [
                            {
                                "marketName": market_name,
                                "bets": market_value
                            } for market_name, market_value in p['markets'].items()]

                    } for p in self.response['multiwayPlayerBet'].values()]
            }

    def _get_event_info(self, event):
        self.home_name = event['TeamHome']
        self.away_name = event['TeamAway']
        sport = event['SportName']
        if sport in self.config:
            self.sport = self.config[sport]
            date = datetime.fromisoformat(event['MatchStartTime'][:-1])
            date = date.replace(tzinfo=timezone.utc).astimezone(tz=local_timezone)
            return {
                "homeName": self.home_name,
                "awayName": self.away_name,
                "date": date.strftime("%Y-%m-%d"),
                "hour": date.strftime("%H:%M"),
                "competition": event['LeagueName'],
                "country": event['CategoryName'],
                "sport": self.sport['translatedName'],
                "markets": defaultdict(list)
            }

    def _parse_market(self, market):
        market_name = market['OriginDescription']
        if market_name in self.sport['markets']:
            self.market_name = self.sport['markets'][market_name]['translatedName']
            # Set strategy
            strategy = self.sport['markets'][market_name]['strategy']
            self.strategy = self.strategies[strategy]

            self.line = market.get('Sbv')
            self.player_name = market.get('SbvText').replace(",","") if market.get('SbvText') else None
            outcomes = []
            for outcome in market['Odds']:
                parsed_outcome = self._parse_outcome(outcome)
                if parsed_outcome:
                    outcomes.append(parsed_outcome)

            return outcomes

    def _parse_outcome(self, outcome):
        if outcome['Active']:
            outcome_name = self._parse_outcome_name(outcome['Name'])
            outcome_odd = outcome['Odd']
            if outcome_odd > 0:
                if self.line:
                    outcome_name = f"{outcome_name} ({self.line})"
                return {
                    "outcomeName": outcome_name,
                    "outcomeOdd": outcome_odd
                }

    def _parse_outcome_name(self, outcome_name):
        transformed_outcome_name = outcome_name.replace("Więcej", "Over").replace("Mniej", "Under")
        if isinstance(self.strategy, MultiWayPlayerBetStrategy):
            if outcome_name.isnumeric():
                line = float(outcome_name) - 0.5
                transformed_outcome_name = f"Over ({line})"
        return transformed_outcome_name


from typing import Optional

import requests
from bs4 import BeautifulSoup

DEFAULT_HEADERS = {
    "User-Agent": (
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
        "AppleWebKit/537.36 (KHTML, like Gecko) "
        "Chrome/74.0.3729.169 Safari/537.36"
    )
}

def make_request(
    url: str,
    headers: Optional[dict] = None,
    proxies: Optional[dict] = None,
    soup: bool = False,
) -> Optional[requests.Response]:
    """ Make HTTP Get Request, return response or bs4 if status code is 200,
    None if 404 else raise error.
    """
    if headers is None:
        headers = DEFAULT_HEADERS
    try:
        response = requests.get(url, headers=headers, proxies=proxies)
    except requests.exceptions.MissingSchema:
        raise ValueError("Incorrect URL provided.")
    if response.status_code == 404:
        return None
    response.raise_for_status()
    return BeautifulSoup(response.content, "html.parser") if soup else response


import json, os, string, random, time, pickle, gc
from PIL import Image
import numpy as np
import torch
import torch.nn as nn
import torch.utils.data as data
import torchvision.transforms as transforms

from pycocotools.coco import COCO

class CocoObject(data.Dataset):
    def __init__(self, ann_dir, image_dir, split = 'train', transform = None):
        self.ann_dir = ann_dir
        self.image_dir = image_dir
        self.split = split
        self.transform = transform

        if self.split == 'train':
            ann_path = os.path.join(self.ann_dir, "instances_train2014.json")
            gender_file = "train_0.data"
        else:
            gender_file = "val_0.data"
            ann_path = os.path.join(self.ann_dir, "instances_val2014.json")
        self.cocoAPI = COCO(ann_path)
        self.data = json.load(open(ann_path))
        self.image_ids = [elem['id'] for elem in self.data['images']]
        print(type(self.image_ids[0]))
        if self.split == 'val':
            self.image_ids = self.image_ids[:10000]
        elif self.split == 'test':
            self.image_ids = self.image_ids[10000:]

        self.image_path_map = {elem['id']: elem['file_name'] for elem in self.data['images']}

        genders = pickle.load(open(gender_file))
        imageid2gender = {}
        for gender_image in genders:
            if gender_image['gender'][0] == 1:
                gender_label = 'man'
            else:
                gender_label = 'woman'
            imageid2gender[gender_image["image_id"]] = gender_label
        #80 objects
        id2object = dict()
        object2id = dict()
        self.person_id = -1
        for idx, elem in enumerate(self.data['categories']):
            if elem['name'] == 'person':
                self.person_id = idx
                print("person index: " + str(idx))
                id2object[idx] = "man"
                object2id["man"] = idx
                continue
            id2object[idx] = elem['name']
            object2id[elem['name']] = idx
        id2object[80] = "woman"
        object2id['woman'] = 80
        assert self.person_id != -1
        #generate one-hot encoding objects annotation for every image
        #self.object_ann = np.zeros((len(self.image_ids), 81))
        self.id2object = id2object
        self.object2id = object2id
        self.id2labels = {}
        self.new_image_ids = []
        for idx, image_id in enumerate(self.image_ids):
            ann_ids = self.cocoAPI.getAnnIds(imgIds = image_id)
            anns = self.cocoAPI.loadAnns(ids = ann_ids)
            category_ids = [elem['category_id'] for elem in anns]
            category_names = [elem['name'] for elem in self.cocoAPI.loadCats(ids=category_ids)]
            if 'person' in category_names and image_id not in imageid2gender:
                continue
            else:
                self.new_image_ids.append(image_id)
            #encoding_ids = [object2id[name] for name in category_names]
            #for encoding_id in encoding_ids:
                #self.object_ann[idx, encoding_id] = 1
        print("image ids len: " + str(len(self.image_ids)))
        print("new image ids len: " + str(len(self.new_image_ids)))
        gender_count = {}
        gender_count["man"] = 0
        gender_count["woman"] = 0
        self.object_ann = np.zeros((len(self.new_image_ids), 81))
        for idx, image_id in enumerate(self.new_image_ids):
            ann_ids = self.cocoAPI.getAnnIds(imgIds = image_id)
            anns = self.cocoAPI.loadAnns(ids = ann_ids)
            category_ids = [elem['category_id'] for elem in anns]
            category_names = [elem['name'] for elem in self.cocoAPI.loadCats(ids=category_ids)]
            encoding_ids = []
            self.id2labels[image_id] = []
            for name in category_names:
                if 'person' == name:
                    gender_count[imageid2gender[image_id]] = gender_count[imageid2gender[image_id]] + 1
                    encoding_ids.append(object2id[imageid2gender[image_id]])
                    self.id2labels[image_id].append(imageid2gender[image_id])
                else:
                    encoding_ids.append(object2id[name])
                    self.id2labels[image_id].append(name)
            for encoding_id in encoding_ids:
                self.object_ann[idx, encoding_id] = 1
        print(gender_count)

    def __getitem__(self, index):
        image_id = self.new_image_ids[index]
        image_file_name = self.image_path_map[image_id]
        if self.split == 'train':
            image_path = os.path.join(self.image_dir,"train2014", image_file_name)
        else:
            image_path = os.path.join(self.image_dir,"val2014", image_file_name)

        img = Image.open(image_path).convert('RGB')

        if self.transform is not None:
            img = self.transform(img)

        return img, torch.Tensor(self.object_ann[index]), image_id

    def getObjectWeights(self):
        return (self.object_ann == 0).sum(axis = 0) / (1e-8 + self.object_ann.sum(axis = 0))

    def __len__(self):
        return len(self.new_image_ids)


n = int(input())
x = []
y = []

for i in range(n):
    xi, yi = [int(e) for e in input().split()]
    x.append(xi)
    y.append(yi)
c = input()
mi = 2e9
ma = -2e9
if c[1]=='i':
    for i in range(n):
        if(i%2==0):
            mi=min(x[i],mi)
            ma=max(y[i],ma)
        else:
            mi=min(y[i],mi)
            ma=max(x[i],ma)
else:
    for i in range(n):
        if(i%2!=0):
            mi=min(x[i],mi)
            ma=max(y[i],ma)
        else:
            mi=min(y[i],mi)
            ma=max(x[i],ma)
print(mi,ma)


'''
Problem Description

A hotel manager has to process N advance bookings of rooms for the next season. His hotel has C rooms. Bookings contain an arrival date and a departure date. He wants to find out whether there are enough rooms in the hotel to satisfy the demand. Write a program that solves this problem in time O(N log N) .

Input Format
First argument is an integer array A containing arrival time of booking.
Second argument is an integer array B containing departure time of booking.
Third argument is an integer C denoting the count of rooms.

Output Format
Return True if there are enough rooms for N bookings else return False.
Return 0/1 for C programs.

Example Input
Input 1:

 A = [1, 3, 5]
 B = [2, 6, 8]
 C = 1

Example Output
Output 1:

 0

Example Explanation
Explanation 1:

 At day = 5, there are 2 guests in the hotel. But I have only one room.
'''
class Solution:
    # @param arrive : list of integers
    # @param depart : list of integers
    # @param K : integer
    # @return a boolean
    def hotel(self, arrive, depart, K):
        possible_events = [(t, 1) for t in arrive] + [(t, 0) for t in depart]

        possible_events = sorted(possible_events)

        guests = 0

        for event in possible_events:
            if event[1] == 1:
                guests += 1
            else:
                guests -= 1

            if guests > K:
                return 0

        return 1


import pandas as pd
import urllib
import urllib.request
import json

def main():
    url = "https://ephtracking.cdc.gov:443/apigateway/api/v1/" + \
            "getCoreHolder/441/2/ALL/ALL/2011,2012,2013,2013,2014,2015/0/0"
    # Reading the json as a dict
    with urllib.request.urlopen(url) as json_data:
        data = json.load(json_data)
    dataset = pd.DataFrame.from_dict(data['pmTableResultWithCWS'])
    # Datatype of dataValue is object, change it into numeric
    dataset['dataValue'] = pd.to_numeric(data['dataValue'], errors='coerce')

    # 1. get the means of all values for each county using "groupby" method
    result = data.groupby(['title','year','geoId'])['dataValue'].mean()
    result = result.to_frame().reset_index()
    result.columns = ['Location','Year','GeoId','Value']
    # 2. split the location column into two column("county","state")
    result[['County','State']] = result['Location'].str.split(',', n=1,
                                                              expand=True)
    del result['Location']
    result['Quality'].dropna(inplace=True)
    result.to_csv("water_clean.csv",index=False)


import wx
import order

class MyFrame(wx.Frame):
    def __init__(self,superior):
        wx.Frame.__init__(self,parent=superior,title='一个简单的订餐系统 by WSG',size=(480,600))

        #创建面板
        panel=wx.Panel(self)

        sizer=wx.GridBagSizer(5,5)

        self.customer=order.Customer('None')
        self.employee=order.Employee('0000')

        #标题
        maintitle=wx.StaticText(panel,label='一个简单的订餐系统')
        sizer.Add(maintitle,pos=(0,0),span=(0,3),flag=wx.TOP|wx.LEFT|wx.BOTTOM,border=15)
        font=wx.Font(18,wx.DEFAULT,wx.NORMAL,wx.BOLD)
        maintitle.SetFont(font)
        maintitle.SetForegroundColour('blue')

        #图片
        img=wx.Image("icon.png",wx.BITMAP_TYPE_ANY)
        w=img.GetWidth()*0.25
        h=img.GetHeight()*0.25
        img.Rescale(w,h)
        imgicon=img.ConvertToBitmap()
        icon=wx.StaticBitmap(panel,bitmap=imgicon)
        sizer.Add(icon,pos=(0,4),flag=wx.EXPAND)

        #食物图标
        foodimg=[]
        for i in range(6):
            imgg=wx.Image("{n}.png".format(n=i+1),wx.BITMAP_TYPE_ANY)
            imgg.Rescale(30,30)
            imggg=imgg.ConvertToBitmap()
            foodimg.append(imggg)

        #加图标
        imgadd=wx.Image("add.png",wx.BITMAP_TYPE_ANY)
        imgadd.Rescale(20,20)
        imgaddicon=imgadd.ConvertToBitmap()

        #减图标
        imgsub=wx.Image("sub.png",wx.BITMAP_TYPE_ANY)
        imgsub.Rescale(20,20)
        imgsubicon=imgsub.ConvertToBitmap()

        #线
        line=wx.StaticLine(panel)
        sizer.Add(line,pos=(1,0),span=(1,5),flag=wx.EXPAND|wx.BOTTOM,border=10)

        #顾客姓名
        font1=wx.Font(12,wx.DEFAULT,wx.NORMAL,wx.NORMAL)
        text1=wx.StaticText(parent=panel,label='输入您的姓名：')
        text1.SetFont(font1)
        sizer.Add(text1,pos=(2,0),flag=wx.LEFT,border=10)
        self.input1=wx.TextCtrl(parent=panel)
        sizer.Add(self.input1,pos=(2,1),span=(1,4),flag=wx.EXPAND|wx.RIGHT,border=10)

        #选择服务员
        text2=wx.StaticText(parent=panel,label='请选择服务员：')
        text2.SetFont(font1)
        sizer.Add(text2,pos=(3,0),flag=wx.LEFT|wx.TOP, border=10)
        self.empnum=['1000','1001','1002','1003']
        self.combo=wx.ComboBox(panel,value='请选择',choices=self.empnum)
        sizer.Add(self.combo,pos=(3,1),span=(1,4),flag=wx.TOP|wx.EXPAND|wx.RIGHT, border=10)

        #菜单复选框
        font2=wx.Font(15,wx.DEFAULT,wx.ITALIC,wx.NORMAL)
        title=wx.StaticBox(panel,label='今日菜单')
        title.SetFont(font2)
        title.SetForegroundColour('red')
        foodname=['可乐','汉堡','牛排','面条','包子','牛奶']
        foodprice=[12,14,34,23,23,11]
        self.menulen=len(foodname)
        self.foodlist=[]
        for i in range(self.menulen):
            food=order.Food(foodname[i],foodprice[i])
            self.foodlist.append(food)

        boxsizer=wx.StaticBoxSizer(title,wx.VERTICAL)
        self.menuCheckBox=[]
        self.CheckedFood=[]
        self.foodnumText=[]
        self.foodnumlist=[]
        self.addbuttonlist=[]
        self.subbuttonlist=[]

        for i in range(self.menulen):
            foodbox=wx.BoxSizer(wx.HORIZONTAL)
            img1=wx.StaticBitmap(panel,bitmap=foodimg[i]) #食物图片
            foodbox.Add(img1,flag=wx.ALL|wx.CENTER,border=5)

            checkbox=wx.CheckBox(panel,id=i,label=self.foodlist[i].showfd())
            checkbox.SetFont(font1)
            self.menuCheckBox.append(checkbox)
            self.CheckedFood.append(False)
            #self.Bind(wx.EVT_CHECKBOX,self.OnCheckBox,self.menuCheckBox[i])
            foodbox.Add(self.menuCheckBox[i],flag=wx.ALL|wx.CENTER,border=5) #食物名称

            subbutton=wx.BitmapButton(panel,id=i+100,bitmap=imgsubicon,style=10)
            self.subbuttonlist.append(subbutton)
            self.Bind(wx.EVT_BUTTON,self.OnSubButton,self.subbuttonlist[i])
            foodbox.Add(subbutton,flag=wx.LEFT|wx.CENTER,border=20) #减

            foodnum=wx.StaticText(panel,id=i,label="0")
            foodnum.SetFont(font2)
            self.foodnumText.append(foodnum)
            self.foodnumlist.append(0)
            foodbox.Add(foodnum,flag=wx.LEFT|wx.CENTER,border=10) #数量

            addbutton=wx.BitmapButton(panel,id=i+10,bitmap=imgaddicon)
            self.addbuttonlist.append(addbutton)
            self.Bind(wx.EVT_BUTTON,self.OnAddButton,self.addbuttonlist[i])
            foodbox.Add(addbutton,flag=wx.ALL|wx.CENTER,border=10) #加

            boxsizer.Add(foodbox,flag=wx.CENTER)

        sizer.Add(boxsizer,pos=(4,0),span=(1,5),flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT,border=10)

        font3=wx.Font(15,wx.DEFAULT,wx.NORMAL,wx.BOLD)
        button1 = wx.Button(panel, size=(100,40),label='重置')
        button1.SetFont(font3)
        button1.SetForegroundColour('white')
        button1.SetBackgroundColour('slate blue')
        sizer.Add(button1, pos=(6, 0),flag=wx.LEFT, border=10)

        button2 = wx.Button(panel, size=(100,40),label="下单")
        button2.SetFont(font3)
        button2.SetForegroundColour('white')
        button2.SetBackgroundColour('slate blue')
        sizer.Add(button2, pos=(6, 3))

        button3 = wx.Button(panel,size=(100,40), label="退出",style=0)
        button3.SetFont(font3)
        button3.SetForegroundColour('black')
        button3.SetBackgroundColour('white')
        sizer.Add(button3, pos=(6, 4), span=(1, 1), flag=wx.BOTTOM|wx.RIGHT, border=10)

        sizer.AddGrowableCol(2)
        panel.SetSizer(sizer)

        #绑定事件
        self.Bind(wx.EVT_BUTTON,self.OnButtonReset,button1)
        self.Bind(wx.EVT_BUTTON,self.OnButtonCheck,button2)
        self.Bind(wx.EVT_BUTTON,self.OnButtonQuit,button3)

    def resizeBitmap(image,width=50,height=50):
        bmp=image.Scale(width,height).ConvertToBitmap()
        return bmp

    def OnButtonReset(self,event):#重置
        self.input1.Clear()
        self.combo.SetValue('请选择')
        for i in range(self.menulen):
            self.menuCheckBox[i].SetValue(False)
            self.foodnumText[i].SetLabel('0')
            self.foodnumlist[i]=0

    def OnButtonCheck(self,event):#确定
        try:
            cusname=self.input1.GetValue()
            empnum=self.combo.GetValue()
            flag=False
            for i in range(self.menulen):
                if not self.foodnumlist[i]==0:
                    flag=True
            if not cusname or empnum=='请选择' or flag==False:
                raise EOFError
            else:
                dlg=wx.MessageDialog(self,'确定下单？','注意',wx.CANCEL|wx.OK|wx.ICON_QUESTION)
                if dlg.ShowModal()==wx.ID_CANCEL:
                    return
        except EOFError:
            wx.MessageBox("信息填写不完整！",'注意',wx.OK|wx.ICON_EXCLAMATION)
            return
        self.customer.SetName(cusname)
        self.customer.delfoodordered()
        self.employee.SetNum(empnum)
        self.lunch=order.Lunch(self.customer,self.employee)
        for i in range(self.menulen):
            if not self.foodnumlist[i]==0:
                self.lunch.order(self.foodlist[i],self.foodnumlist[i])
        result=self.lunch.result()

        wx.MessageBox(result,'订餐结果',wx.OK|wx.ICON_EXCLAMATION)

    def OnCheckBox(self,event):
        cb=event.GetEventObject()
        self.CheckedFood[cb.GetId()]=cb.GetValue()

    def OnButtonQuit(self,event):#退出
        dlg=wx.MessageDialog(self,'确定退出订餐系统？','注意',wx.CANCEL|wx.OK|wx.ICON_QUESTION)
        if dlg.ShowModal()==wx.ID_OK:
            self.Destroy()

    def OnAddButton(self,event):#加
        ad=event.GetEventObject()
        fn=self.foodnumText[ad.GetId()-10]
        fn.SetLabel(str(int(fn.GetLabel())+1))
        self.foodnumlist[ad.GetId()-10]+=1

    def OnSubButton(self,event):#减
        sb=event.GetEventObject()
        fn=self.foodnumText[sb.GetId()-100]
        num=int(fn.GetLabel())
        if num==0:
            return
        fn.SetLabel(str(int(num-1)))
        self.foodnumlist[sb.GetId()-100]-=1

if __name__=='__main__':
    app=wx.App()
    frame=MyFrame(None)
    frame.Show()
    app.MainLoop()


import os.path
import csv

#make variables
votes_list = []
candidates_list = []
stockham = 0
degette = 0
doane = 0

output_csv = os.path.join("Resources", "election_data.csv")

#opening up the csv file to read and gather information from it
with open(output_csv, 'r') as csvfile:
    csvreader = list(csv.reader(csvfile, delimiter=','))
    for row in csvreader[1:]:
        votes_list.append(row[0])
        candidates_list.append(row[2])

for candidate in candidates_list:
    if candidate == 'Charles Casper Stockham':
        stockham += 1
    elif candidate == 'Diana DeGette':
        degette += 1
    elif candidate == 'Raymon Anthony Doane':
        doane += 1

stockham_percent = round((stockham/len(votes_list)) *100 ,3)
degette_percent = round((degette/len(votes_list)) *100 ,3)
doane_percent = round((doane/len(votes_list)) *100 ,3)

#lots of printing for the terminal analysis
print("Election Results")
print("-"*40)
print("Total Votes: " + str(len(votes_list)))
print("-"*40)
print("Charles Casper Stockham: " + str(stockham_percent) + "% " + str(stockham))
print("Diana DeGette: " + str(degette_percent) + "% " + str(degette))
print("Raymon Anthony Doane: " + str(doane_percent) + "% " + str(doane))
print("-"*40)
if stockham > degette and stockham > doane:
    print("Winner: Charles Casper Stockham")
elif degette > stockham and degette > doane:
    print("Winner: Diana DeGette")
elif doane > stockham and doane > degette:
    print("Winner: Raymon Anthony Doane")

txt_output = os.path.join("Analysis", "output.txt")
#writing to a text file
with open(r'C:\Users\Ryan Kracaw\Desktop\PyPoll\Analysis\output.txt', 'w') as target:
    target.write("Election Results")
    target.write("\n")
    target.write("-"*40)
    target.write("\n")
    target.write("Total Votes: ")
    target.write(str(len(votes_list)))
    target.write("\n")
    target.write("-"*40)
    target.write("\n")
    target.write("Charles Casper Stockham: ")
    target.write(str(stockham_percent))
    target.write("% ")
    target.write(str(stockham))
    target.write("\n")
    target.write("Diana DeGette: ")
    target.write(str(degette_percent))
    target.write("% ")
    target.write(str(degette))
    target.write("\n")
    target.write("Raymon Anthony Doane: ")
    target.write(str(doane_percent))
    target.write("% ")
    target.write(str(doane))
    target.write("\n")
    target.write("-"*40)
    target.write("\n")
    if stockham > degette and stockham > doane:
        target.write("Winner: Charles Casper Stockham")
    elif degette > stockham and degette > doane:
        target.write("Winner: Diana DeGette")
    elif doane > stockham and doane > degette:
        target.write("Winner: Raymon Anthony Doane")


import razorpay
from datetime import datetime
from .settings import KEY_ID,  KEY_SECRET

client = razorpay.Client(auth=(KEY_ID, KEY_SECRET))

def order(username, email, fname, lname, amount_rs, currency='INR'):
    amount = int(amount_rs) * 100
    id = username + "@" + str(datetime.now()).split(".")[0].replace(":", "").replace("-", "").replace(" ", "")
    notes = {"email" : email, "name" : f"{fname} {lname}"}

    data = { "amount": amount, "currency": currency, "receipt": id, "notes" : notes }
    order = client.order.create(data=data)

    return order

def verify_payment_request(data):
    client.utility.verify_payment_signature(data)


import math
import pyaudio

import numpy as np
import scipy.integrate as integrate
import matplotlib.pyplot as plt
import seaborn as sns

from math import e as e
from math import pi as pi

p = pyaudio.PyAudio()

plt.ion()
fig, (ax1, ax2) = plt.subplots(2)
fig.suptitle('Vertically stacked subplots')

# freqs = [523, 440, 349]
freqs = [1, 4, 15]

def func_aperiodic(x):
    falloff = e ** (-2 * pi * (x ** 2))
    out = sum([math.cos(2 * pi * f * x) for f in freqs])

    return out

def func_periodic(x):
    out = sum([math.cos(f * x) for f in freqs])

    return out

def fourier_transform(freq):
    """ integral(x(t) * e^(-i2(pi)ft)) dx/dt """

    fourier = lambda t: func_aperiodic(t) * (e ** (-2j * pi * freq * t))
    fourier_full = lambda t: fourier(t).real + fourier(t).imag

    out = integrate.quad(fourier_full, -np.inf, np.inf)[0]

    return out

def fourier_series(x, num_iter=1):
    a_0 = (1 / pi) * integrate.quad(func_periodic, -pi, pi)[0]
    coef_a = lambda x: func_periodic(x) * math.cos(n * x)
    coef_b = lambda x: func_periodic(x) * math.sin(n * x)
    a_n = lambda n: (1 / pi) * integrate.quad(coef_a, -pi, pi)[0]
    b_n = lambda n: (1 / pi) * integrate.quad(coef_b, -pi, pi)[0]

    out = a_0 / 2
    for n in range(num_iter):
        out += (a_n(n) * math.cos(n * x)) + (b_n(n) * math.sin(n * x))

    return out

def plot_func(function, span, ax, n=None):
    volume = 0.5     # range [0.0, 1.0]
    fs = 44100       # sampling rate, Hz, must be integer
    duration = 1.0   # in seconds, may be float
    f = 440.0        # sine frequency, Hz, may be float

    x = np.linspace(-(duration / 2), -(duration / 2), fs)
    y = np.vectorize(function)(x, n) if n else np.vectorize(function)(x)

    samples = (y).astype(np.float32)

    print(samples)
    print(len(samples))

    # for paFloat32 sample values must be in range [-1.0, 1.0]
    stream = p.open(format=pyaudio.paFloat32,
                                    channels=1,
                                    rate=fs,
                                    output=True)

    # play. May repeat with different volume values (if done interactively)
    stream.write(volume*samples)

    stream.stop_stream()
    stream.close()

    return x, y

def play_sound():
    volume = 0.5     # range [0.0, 1.0]
    fs = 44100       # sampling rate, Hz, must be integer
    duration = 1.0   # in seconds, may be float
    f = 440.0        # sine frequency, Hz, may be float

    # generate samples, note conversion to float32 array
    samples = (np.sin(2*np.pi*np.arange(fs*duration)*f/fs)).astype(np.float32)

    print(samples)
    print(len(samples))

    # for paFloat32 sample values must be in range [-1.0, 1.0]
    stream = p.open(format=pyaudio.paFloat32,
                                    channels=1,
                                    rate=fs,
                                    output=True)

    # play. May repeat with different volume values (if done interactively)
    stream.write(volume*samples)

    stream.stop_stream()
    stream.close()

if __name__=="__main__":
    play_sound()

    x, y = plot_func(func_periodic, 50, ax1)
    sns.lineplot(x=x, y=y, ax=ax1)

    print("asdf")
    plt.show()
    plt.pause(10)

    x, y = plot_func(fourier_series, 50, ax2, 20)
    sns.lineplot(x=x, y=y, ax=ax2)

    # num_iter = 0
    # while num_iter < 20:
        # x, y = plot_func(fourier_series, 50, ax2, num_iter)
        # print(y)

        # for line in ax2.lines:
            # line.set_ydata(y)
            # fig.canvas.draw()
            # fig.canvas.flush_events()

        # plt.pause(1)


# coding=utf-8

# NameError: 调用不存在的变量
# print(myName)

# SyntaxError: 语法错误
# print())

# IndexError: 下标有问题
myList = [1,2,3,4,5]
# print(myList[20])

# KeyError: key值有问题
myDict = {"stuName":"lucy","age":20}
# print(myDict['stuSex'])

# ValueError
# int(myDict.get('stuName'))

# AttributeError: 属性错误 调用了不存在的属性
age = 10
# age.append(20)

# IndentationError: 缩进错误


import numpy as np

def inverse_wire_dynamics(forces_desired, wire_directions, moment_arms, max_iter=2000, wire_forces_min=0, wire_forces_max=5000, initial_wire_force=0):
    # Internal Parameters
    F_tolerance = 1       # Accepted deviation from desired force
    M_tolerance = 1  # Accepted deviation from desired moment

    # Initialize motor_forces for first iteration
    motor_forces = np.array([[[initial_wire_force]] * 5] * forces_desired.shape[0])

    # Initialize convergence counter in case it does not converge
    converge_iter = max_iter + 1

    # Calculate the gradients with respect to each motor_forces value
    dF_df = wire_directions
    dM_df = np.cross(moment_arms, wire_directions, axis=2)

    # Arrays for plotting the errors over iterations
    err_array = np.zeros((forces_desired.shape[0], max_iter, 3))

    for i in range(max_iter):
        # Calculate the total force and moment using the current f values
        F, M = forward_wire_dynamics(motor_forces, wire_directions, moment_arms)

        # Calculate error
        F_err = np.subtract(F[:, :2], forces_desired[:, :2])
        M_err = np.subtract(M, forces_desired[:, 2])[:, np.newaxis]
        err_array[:, i, :2] = F_err
        err_array[:, i, 2] = M_err[:, 0]

        # Check for convergence
        if np.all(abs(F_err[:, :2]) < F_tolerance) and np.all(abs(M_err) < M_tolerance):
            converge_iter = i
            break

        motor_forces = update_forces(dF_df, dM_df, F_err, M_err, motor_forces, wire_forces_min, wire_forces_max)

    return motor_forces, F, M, converge_iter, np.concatenate([F_err, M_err], axis=1), err_array

def forward_wire_dynamics(motor_forces, wire_directions, moment_arms):
    """
    Function computes the combined forces and moments from motor forces
    :param motor_forces: `numpy` array of shape (N, 5)
    :param wire_directions: `numpy` array of shape (N, 5, 3)
    :param moment_arms: `numpy` array of shape (N, 5, 3)
    :return:
    """
    wire_forces = np.multiply(motor_forces, wire_directions)
    wire_moments = np.cross(moment_arms, wire_forces)
    wire_forces_sum = np.sum(wire_forces, axis=1)
    wire_moments_sum = np.sum(wire_moments, axis=1)[:, 2]
    return wire_forces_sum, wire_moments_sum

def update_forces(dF_df, dM_df, F_err, M_err, motor_forces, wire_forces_min, wire_forces_max):
    step_size_Fx = 0.1  # Step size (learning rate) for Fx
    step_size_Fy = 0.1  # Step size (learning rate) for Fy
    step_size_Mz = 0.8  # Step size (learning rate) for Mz

    # Compute the gradients
    f_grad_xy = np.multiply(F_err[:, np.newaxis, :2], dF_df[:, :, :2])
    f_grad_z = np.multiply(M_err, dM_df[:, :, 2])

    # Compute the step sizes
    f_step_x = np.multiply(step_size_Fx, f_grad_xy[:, :, 0])
    f_step_y = np.multiply(step_size_Fy, f_grad_xy[:, :, 1])
    f_step_z = np.multiply(step_size_Mz, f_grad_z)

    # Update f values using gradient descent
    motor_forces = np.subtract(motor_forces, np.sum([f_step_x, f_step_y, f_step_z], axis=0)[:, :, np.newaxis])

    # Apply constraints to f values
    motor_forces = np.maximum(wire_forces_min, np.minimum(wire_forces_max, motor_forces))

    return motor_forces


''' Standup.py
File that contains all functions related to standup.

'''

import datetime
import data
import message

from error import InputError, AccessError

def standup_start(token, channel_id, length):

	# Check token is valid.
    try:
        data.token_to_user_id(token)
    except:
        raise AccessError(description='Invalid token')

    # Check channel ID is valid.
    try:
        channel_index = data.resolve_channel_id_index(channel_id)
    except LookupError:
        raise InputError(description='Invalid Channel ID')

	# Check that there is not already an active standup in this channel.
    if standup_active(token, channel_id)['is_active'] is True:
        raise InputError(description='Standup Already Active')

    current_time = datetime.datetime.now()
    finish_time = (current_time + datetime.timedelta(seconds=length)).timestamp()

	# Edit data structure to store standup details.
    standup = data.data['channels'][channel_index]['standup']
    standup['time_finish'] = finish_time
    standup['creator'] = token

    return  {'time_finish': finish_time}

# Close a standup and clear standup data.
def close_standup(channel_index, channel_id):
    # Collate all messages sent.
    standup = data.data['channels'][channel_index]['standup']

    standup_str = ''

    for message_info in standup['messages']: # pragma: no cover
	    user_index = data.resolve_user_id_index(message_info['u_id'])
	    # Use handle rather than first name as handle is unique.
	    handle = data.data['users'][user_index]['handle']
	    # Add a message in format 'hayden: I ate a catfish'.
	    standup_str += handle + ': '+ message_info['message'] + '\n'

    # Send out collated messages (unless no messages were sent during standup).
    if standup_str != '': # pragma: no cover
        try:
            send_time = standup['time_finish']
            message.message_sendlater(standup['creator'], channel_id, standup_str, send_time)
        except InputError:
            message.message_send(standup['creator'], channel_id, standup_str)

    # Clear data
    standup['time_finish'] = None
    standup['messages'] = []
    standup['creator'] = None

def standup_active(token, channel_id):

	# Check token is valid.
    try:
        data.token_to_user_id(token)
    except:
        raise AccessError(description="Invalid token")

    # Check channel ID is valid.
    try:
        channel_index = data.resolve_channel_id_index(channel_id)
    except LookupError:
        raise InputError(description='Invalid Channel ID')

    current_time = datetime.datetime.now().timestamp()

    active = False

    standup = data.data['channels'][channel_index]['standup']
    # Check if any data for a standup has been stored
    if standup['time_finish'] is not None:
	    if standup['time_finish'] < current_time:
		    # Close the standup:
		    # ie. send out final message and erase all data.
		    close_standup(channel_index, channel_id)
	    else:
		    active = True

    return {
	    'is_active': active,
        'time_finish':  standup['time_finish']
    }

def standup_send(token, channel_id, message):

    # Check token is valid.
    try:
        u_id = data.token_to_user_id(token)
    except:
        raise AccessError(description="Invalid token")

    # Check channel ID is valid.
    try:
        channel_index = data.resolve_channel_id_index(channel_id)
    except LookupError:
        raise InputError(description='Invalid Channel ID')

    # Check that message is valid.
    if len(message) > 1000:
	    raise InputError(description='Message Too Long')

    # Check that standup is active in this channel.
    if standup_active(token, channel_id)['is_active'] is False:
	    raise InputError(description='Standup Not Active')

    # Check that user is authorised to send a message in channel.
    permissions = [1, 2]
    if data.resolve_permissions(channel_id, u_id) not in permissions:
	    raise AccessError(description='User Not Authorised')

    # Store the message in standup buffer.
    standup = data.data['channels'][channel_index]['standup']
    standup['messages'].append({
	    'u_id': u_id,
	    'message': message
    })

    return {}


import cv2 as cv
import copy as copy
import sys
sys.path.append('FacialDetection')
from helperFunctions import *
from ImageManager import ImageManager

image = cv.imread('human\people2.jpg')
image2 = cv.imread('human\people2.jpg')
# image = resizeMinTo(image,800)
# print("DEBUG ", image[2])

imgMngr = ImageManager(image)

# eyes_rect = imgMngr.findPairsOfEyes(1.1, 10)

# print(f'Number of eyes found = {len(eyes_rect)}')

# for pair in eyes_rect:
#     pair[0].draw(image, (0,255,0), thickness= 2)
#     pair[1].draw(image, (0,255,0), thickness= 2)

# faces_rect = imgMngr.findFacesUsingPairOfEyes(eyes_rect, 1.1, 10)
faces_rect = imgMngr.findFaces(1.1, 10)

for face in faces_rect:
    face.draw(image, (0,0,255), thickness= 2)

image2Gray = cv.cvtColor(image2, cv.COLOR_BGR2GRAY)
faces_rect_default = imgMngr.haarcascade_face.detectMultiScale(image2Gray, 1.1, 10)

for (x,y,w,h) in faces_rect_default:
    cv.rectangle(image2, (x,y), (x + w, y + h), (0,255,0), 2)

# og = cv.resize(og, dimensions, interpolation=cv.INTER_AREA)
cv.imshow('My method', image)
cv.imshow('Default method', image2)

cv.waitKey(0)


################################################
# FILE: cluster_analysis.py
# WRITERS: Bar Melinarskiy
# DESCRIPTION: Utils functions for evaluating the received latent space clusters
################################################

# Imports
import numpy as np
import pandas as pd
from sklearn.cluster import DBSCAN
from sklearn import metrics
import seaborn as sns
import colorcet as cc
# import mplscience
# mplscience.set_style()
from math import ceil
import matplotlib
from os.path import exists
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_samples, silhouette_score
from sklearn.metrics import rand_score
from yellowbrick.cluster import SilhouetteVisualizer  # to continue here
from collections import Counter
from formatters import *
import settings as settings
from collections import Counter
from random import choice

matplotlib.use('Agg')
rng = np.random.RandomState(0)

"""
* V-measure, the harmonic mean of completeness and homogeneity;

* Rand index, which measures how frequently pairs of data points are grouped consistently according to the result
of the clustering algorithm and the ground truth class assignment;

* Adjusted Rand index (ARI), a chance-adjusted Rand index such that a random cluster assignment has an
ARI of 0.0 in expectation;

* Mutual Information (MI) is an information theoretic measure that quantifies how dependent are the two
labelings. Note that the maximum value of MI for perfect labelings depends on the number of clusters and samples;

* Normalized Mutual Information (NMI), a Mutual Information defined between 0 (no mutual information) in the
limit of large number of data points and 1 (perfectly matching label assignments, up to a permutation of the labels).
It is not adjusted for chance: then the number of clustered data points is not large enough, the expected values of MI
or NMI for random labelings can be significantly non-zero;

* Adjusted Mutual Information (AMI), a chance-adjusted Mutual Information. Similarly to ARI, random cluster
assignment has an AMI of 0.0 in expectation.
"""
score_funcs = [
    ("Homogeneity", metrics.homogeneity_score),
    ("Completeness", metrics.completeness_score),
    ("V-measure", metrics.v_measure_score),
    ("Rand index", metrics.rand_score),
    ("Adjusted Rand Index", metrics.adjusted_rand_score),
    ("MI", metrics.mutual_info_score),
    ("NMI", metrics.normalized_mutual_info_score),
    ("Adjusted Mutual Information", metrics.adjusted_mutual_info_score)
]

ATTRIBUTES = ['celltype', 'organ']

# Functions
def matrices_figures(X: np.ndarray, true_labels: np.ndarray, df: pd.DataFrame, attributes_map, attribute,
                     title: str, save_path: str) -> np.ndarray:
    """
    Evaluate the latent space clustering, comparing known labels to kmeans clustering using the Rand index score
    :param X: The latent space data
    :param true_labels: array of known labels for each sample
    :param df: dataframe for UMAP
    :param title: title for plot
    :param save_path: path to save the figures
    :return: rand index score for all attributes together and separately
    """
    # Number of clusters in labels, ignoring noise if present.
    n_clusters_ = len(set(true_labels)) - (1 if -1 in true_labels else 0)
    n_noise_ = list(true_labels).count(-1)
    k_values = np.arange(2, 16)
    df_metrics = {
        "k": k_values,
        "Homogeneity": [],
        "Completeness": [],
        "V-measure": [],
        "Adjusted Rand Index": [],
        "Adjusted Mutual Information": [],
        "Silhouette Coefficient": []
    }

    fixed_classes_uniform_labelings_scores_plot(X, true_labels, title, save_path)
    uniform_labelings_scores_plot(X, true_labels, title, save_path)
    best_kmeans = kmeans_scores_plot(X, true_labels, title, save_path)
    umap_with_kmeans_labels(df, best_kmeans, title, save_path, attributes_map, attribute)
    return df_metrics

def random_labels(n_samples, n_classes):
    return rng.randint(low=0, high=n_classes, size=n_samples)

def fixed_classes_uniform_labelings_scores(
        score_func, n_samples, n_clusters_range, n_classes, n_runs=5
):
    scores = np.zeros((len(n_clusters_range), n_runs))
    labels_a = random_labels(n_samples=n_samples, n_classes=n_classes)

    for i, n_clusters in enumerate(n_clusters_range):
        for j in range(n_runs):
            labels_b = random_labels(n_samples=n_samples, n_classes=n_clusters)
            scores[i, j] = score_func(labels_a, labels_b)
    return scores

def fixed_classes_uniform_labelings_scores_plot(X, true_labels, title, save_path):
    n_samples = len(true_labels)
    n_classes = len(set(true_labels)) - (1 if -1 in true_labels else 0)
    n_clusters_range = np.arange(2, 16).astype(int)
    plots = []
    names = []

    sns.color_palette("colorblind")
    plt.figure(1)

    for marker, (score_name, score_func) in zip("d^vx.+*,", score_funcs):
        scores = fixed_classes_uniform_labelings_scores(
            score_func, n_samples, n_clusters_range, n_classes=n_classes
        )
        plots.append(
            plt.errorbar(
                n_clusters_range,
                scores.mean(axis=1),
                scores.std(axis=1),
                alpha=0.8,
                linewidth=1,
                marker=marker,
            )[0]
        )
        names.append(score_name)
    plt.title(title +
              ", Clustering measures for random uniform labeling\n"
              f"against reference assignment with {n_classes} classes"
              )
    plt.xlabel(f"Number of clusters (Number of samples is fixed to {n_samples})")
    plt.ylabel("Score value")
    plt.ylim(bottom=-0.05, top=1.05)
    plt.legend(plots, names, bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.savefig(save_path + "fixed_classes_uniform_labelings_scores.png", format="png", dpi=300)
    plt.show()

def uniform_labelings_scores(score_func, n_samples, n_clusters_range, n_runs=5):
    scores = np.zeros((len(n_clusters_range), n_runs))

    for i, n_clusters in enumerate(n_clusters_range):
        for j in range(n_runs):
            labels_a = random_labels(n_samples=n_samples, n_classes=n_clusters)
            labels_b = random_labels(n_samples=n_samples, n_classes=n_clusters)
            scores[i, j] = score_func(labels_a, labels_b)
    return scores

def uniform_labelings_scores_plot(X, true_labels, title, save_path):
    n_samples = len(true_labels)
    n_clusters_range = np.arange(2, 16).astype(int)
    plt.figure(2)
    plots = []
    names = []

    for marker, (score_name, score_func) in zip("d^vx.+*", score_funcs):
        scores = uniform_labelings_scores(score_func, n_samples, n_clusters_range)
        plots.append(
            plt.errorbar(
                n_clusters_range,
                np.median(scores, axis=1),
                scores.std(axis=1),
                alpha=0.8,
                linewidth=2,
                marker=marker,
            )[0]
        )
        names.append(score_name)

    plt.title(title +
              ", Clustering measures for 2 random uniform labelings\nwith equal number of clusters"
              )
    plt.xlabel(f"Number of clusters (Number of samples is fixed to {n_samples})")
    plt.ylabel("Score value")
    plt.legend(plots, names, bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.ylim(bottom=-0.05, top=1.05)
    plt.savefig(save_path + "uniform_labelings_scores.png", format="png", dpi=300)
    plt.show()

def get_random_max_index(labels_list):
    max_value = np.nanmax(labels_list)
    # Get a list of indices where the maximum value occurs
    max_indices = [i for i, x in enumerate(labels_list) if x == max_value]
    # Get a random index from the list of indices
    random_index = choice(max_indices)
    return random_index

def get_counters(ground_truth_labels, labels, num_unique_true_labels):
    label_counts = {label: Counter([ground_truth_labels[i] for i in range(len(labels)) if labels[i] == label]) for label
                    in set(labels)}
    label_counts_df = pd.DataFrame(label_counts).sort_index()
    label_counts_df /= num_unique_true_labels
    new_labels = [label_counts[label].most_common(1)[0][0] for label in labels]
    return label_counts_df, new_labels

def robustness(id_, kmeans_labels, true_labels_celltype, true_labels_organ):
    values = ['B1', 'CYCLING_B', 'IMMATURE_B', 'LARGE_PRE_B', 'LATE_PRO_B', 'MATURE_B', 'PLASMA_B', 'PRE_PRO_B',
              'PRO_B',
              'SMALL_PRE_B', 'BM', 'GU', 'KI', 'LI', 'MLN', 'SK', 'SP', 'TH', 'YS']
    labels_dic = {i: value for i, value in enumerate(values)}
    number_of_clusters = len(set(kmeans_labels))

    new_labels_list = []
    df_robustness = {
        'n_clusters': [],
        'k': [],
        'new_id': [],
        'value': []
    }

    number_of_celltypes = len(set(true_labels_celltype))
    number_of_organs = len(set(true_labels_organ))

    label_counts_celltype, new_labels_celltype = get_counters(true_labels_celltype, kmeans_labels, number_of_organs)
    label_counts_organ, new_labels_organ = get_counters(true_labels_organ, kmeans_labels, number_of_celltypes)
    new_labels = []
    for k in list(set(kmeans_labels)):
        if label_counts_celltype[k].max() > label_counts_organ[k].max():
            new_val = get_random_max_index(label_counts_celltype[k])
            max_val = label_counts_celltype[k].max()
            new_labels.append(new_val)
        else:
            new_val = number_of_celltypes + get_random_max_index(label_counts_organ[k])
            max_val = label_counts_organ[k].max()
            new_labels.append(new_val)

        df_robustness['new_id'].append(new_val)
        df_robustness['value'].append(max_val)
        df_robustness['n_clusters'].append(number_of_clusters)
        df_robustness['k'].append(k)
    new_labels_list.append(new_labels)

    most_common_new_labels = [Counter(col).most_common(1)[0][0] for col in zip(*new_labels_list)]
    meaningful_new_labels = [labels_dic.get(item, item) for item in most_common_new_labels]
    df_robustness = pd.DataFrame(df_robustness)
    df_robustness['new_id'] = df_robustness['new_id'].replace(labels_dic)

    print(f'for n_clusters = {number_of_clusters}\nmost_common_new_labels = {meaningful_new_labels}')
    print(df_robustness)
    csv_name = settings.SAVE_DIR + f"relabeling_{id_}.csv"

    if not exists(csv_name):
        df_robustness.to_csv(csv_name)
    else:
        df_robustness.to_csv(csv_name, mode='a', header=False)

    return df_robustness['value'].mean(), df_robustness['value'].std()

def get_kmeans_score(X, df_true_labels, n_clusters_range=np.arange(9, 13).astype(int), id_=None, save_path=""):
    return kmeans_scores(X, df_true_labels, n_clusters_range, id_=id_, save_path=save_path)
    # for score_name, score_func in score_funcs:
    #     scores = kmeans_scores(X, df_true_labels, score_name, score_func, n_clusters_range, id_=id_,
    #                                         save_path=save_path)
    #     scores['score_name'] = score_name
    #     scores_kmeans.append(scores)
    # return scores_kmeans

# def kmeans_scores(X, df_true_labels, score_name, score_func, n_clusters_range, n_runs=1, id_=None, save_path=""):
#     scores = np.zeros((len(n_clusters_range), n_runs))
#     all_kmeans = {
#         "id_biolord": [],
#         "id": [],
#         "n_clusters": [],
#         "score_name": [],
#         "score": [],
#         "labels": [],
#         "true_labels": []
#     }
#     best_kmeans = {
#         "labels": [],
#         "n_clusters": 0,
#         "km": None
#     }
#     max_score = -np.inf
#     for i, n_clusters in enumerate(n_clusters_range):
#         for j in range(n_runs):
#             km = KMeans(n_clusters=n_clusters, n_init='auto', random_state=42)
#             labels_kmeans = km.fit_predict(X)
#             score = score_func(true_labels, labels_kmeans)
#             index = (i * n_runs) + j
#             all_kmeans['id'].append(index)
#             all_kmeans['id_biolord'].append(id_)
#             all_kmeans['n_clusters'].append(n_clusters)
#             all_kmeans['score_name'].append(score_name)
#             all_kmeans['score'].append(score)
#             all_kmeans['labels'].append(labels_kmeans)
#             all_kmeans['true_labels'].append(true_labels)
#             if score > max_score:
#                 max_score = score
#                 best_kmeans['labels'] = labels_kmeans
#                 best_kmeans['n_clusters'] = n_clusters
#                 best_kmeans['km'] = km
#             scores[i, j] = score
#     best_kmeans['score'] = max_score
#     all_kmeans = pd.DataFrame(all_kmeans)
#     # create only if this is the 1st model and 1st score func, otherwise append
#     if not exists(save_path):
#         all_kmeans.to_csv(save_path)
#     else:
#         all_kmeans.to_csv(save_path, mode='a', header=False)
#     return scores, best_kmeans

def kmeans_scores(X, df_true_labels, n_clusters_range, id_=None, save_path=""):
    all_kmeans = {
        "id_biolord": [],
        "n_clusters": [],
        "labels": [],
        "score_robustness_mean": [],
        "score_robustness_std": []
    }

    for n_clusters in n_clusters_range:
        all_kmeans['id_biolord'].append(id_)
        all_kmeans['n_clusters'].append(n_clusters)
        # fit the k means model over the latent space
        km = KMeans(n_clusters=n_clusters, n_init='auto', random_state=42)
        labels_kmeans = km.fit_predict(X)
        all_kmeans['labels'].append(labels_kmeans)

        for score_name, score_func in score_funcs:
            for attribute, true_labels in zip(df_true_labels['attributes'], df_true_labels['true_labels']):
                if attribute == "celltype":
                    true_labels_celltype = true_labels
                else:
                    true_labels_organ = true_labels
                score = score_func(true_labels, labels_kmeans)
                attribute_score_name = f"score_{score_name}_{attribute}"
                if attribute_score_name not in all_kmeans:
                    all_kmeans[attribute_score_name] = []
                all_kmeans[attribute_score_name].append(score)

        robustness_mean, robustness_std = robustness(id_=id_, kmeans_labels=labels_kmeans,
                                                     true_labels_celltype=true_labels_celltype,
                                                     true_labels_organ=true_labels_organ)
        all_kmeans['score_robustness_mean'].append(robustness_mean)
        all_kmeans['score_robustness_std'].append(robustness_std)
    all_kmeans = pd.DataFrame(all_kmeans)
    # if not exists(save_path):
    #     all_kmeans.to_csv(save_path)
    # else:
    #     all_kmeans.to_csv(save_path, mode='a', header=False)
    return all_kmeans

def kmeans_scores_plot(X, true_labels, title, save_path):
    n_samples = len(true_labels)
    n_clusters_range = np.arange(2, 16).astype(int)
    plt.figure(3)
    plots = []
    names = []
    for marker, (score_name, score_func) in zip("d^vx.+*", score_funcs):
        scores = kmeans_scores(X, true_labels, score_func, n_clusters_range, save_path)
        plots.append(
            plt.errorbar(
                n_clusters_range,
                np.median(scores, axis=1),
                scores.std(axis=1),
                alpha=0.8,
                linewidth=2,
                marker=marker,
            )[0]
        )
        names.append(score_name)

    plt.title(title +
              ", Clustering measures for Kmeans Vs ground trouth labels"
              )
    plt.xlabel(f"Number of clusters (Number of samples is fixed to {n_samples})")
    plt.ylabel("Score value")
    plt.legend(plots, names, bbox_to_anchor=(1.05, 1), loc='upper left')
    plt.ylim(bottom=-0.05, top=1.05)
    plt.tight_layout()
    plt.savefig(save_path + "kmeans_scores_plot.png", format="png", dpi=300)
    plt.show()
    return scores

def umap_with_kmeans_labels(df, best_kmeans, title, save_path, attributes_map, attribute_):
    fig, axs = plt.subplots(2, 2, figsize=(14, 7), gridspec_kw={"width_ratios": [1, 1]})
    # plt.subplots_adjust(wspace=0.2)
    # df['kmeans'] = best_kmeans['labels']
    title += '\nBest kmeans got Adjusted Rand Index score of: ' + str(round(best_kmeans['score'], 3)) + \
             ' with n_clusters = ' + str(best_kmeans['n_clusters'])

    attributes_color_map = {}
    labels_all_attributes = []
    for attribute in ATTRIBUTES:
        # Determine the most common label for each label in best_kmeans['labels']
        attribute_key = attribute + '_key'
        ground_truth_labels = df[attribute_key]
        label_counts = {label: Counter(
            [ground_truth_labels[i] for i in range(len(best_kmeans['labels'])) if best_kmeans['labels'][i] == label])
            for label in
            set(best_kmeans['labels'])}
        new_labels = [label_counts[label].most_common(1)[0][0] for label in best_kmeans['labels']]
        property_ = 'kmeans_' + attribute
        df[property_] = new_labels
        df[property_] = df[property_].replace(attributes_map[attribute])
        if attribute == "celltype":
            df[property_] = switch_to_celltype_fullname(df[property_])
        elif attribute == "organ":
            df[property_] = switch_to_organ_fullname(df[property_])

        # Generate a color palette
        labels_all_attributes = np.append(labels_all_attributes, np.unique(df[attribute]))
        # n_labels = len(np.unique(df[attribute]))
        # palette = sns.color_palette('hls', n_labels)
        # # Create the color dictionary
        # color_dict = dict(zip(np.unique(df[attribute]), palette))
        # attributes_color_map[attribute] = color_dict

        labels_truth = df['celltype_key']
        unique_labels_kmeans = list(set(best_kmeans['labels']))
        for l in unique_labels_kmeans:
            indexes = [i for i in range(len(best_kmeans['labels'])) if best_kmeans['labels'][i] == l]
            values = [labels_truth[i] for i in indexes]
            counts = Counter(values)
            total_count = len(values)
            print(f'For the label {l}:')
            for value, count in counts.items():
                percentage = count / total_count * 100
                print(f'{value}: {percentage}%')
            most_common_label = max(counts, key=counts.get)
            print(f'For the label {l} the new label will be: {most_common_label}')

    n_labels = len(np.unique(labels_all_attributes))
    palette = sns.color_palette(cc.glasbey, n_labels)
    # palette = sns.color_palette("husl", n_labels)
    # Create the color dictionary
    attributes_color_map = dict(zip(np.unique(labels_all_attributes), palette))
    #
    # print("kmeans values after are:", new_labels, '\n')
    # print("indexes of ground truth:")
    # map_indexes_truth = print_indexes(list(df['celltype_key']))
    # print("----------------------------------------")
    # print("indexes of kmeans before:")
    # print("----------------------------------------")
    # map_indexes_kmeans = pd.DataFrame(print_indexes(list(best_kmeans['labels'])), index=[0])
    # print("map before:")
    # print(map_indexes_kmeans)
    # map_indexes_kmeans.replace(map_indexes_truth, inplace=True)
    # print("map after:")
    # print(map_indexes_kmeans)
    #
    # print("indexes of kmeans after:")
    # print_indexes(new_labels)
    # print("----------------------------------------")

    # 2nd attempted
    # Determine the majority label in labels1
    # majority_label = Counter(labels1).most_common(1)[0][0]
    # # Create a dictionary mapping each label in labels1 to its corresponding ID
    # id_dict = {label: i for i, label in enumerate(set(labels1))}
    # # Transfer the IDs from labels1 to labels2 based on majority rule
    # ids2 = [id_dict[label] if label == majority_label else -1 for label in labels2]

    col = row = 0
    for hue_attribute in ['celltype', 'kmeans_celltype', 'organ', 'kmeans_organ']:
        attribute = hue_attribute
        if "kmeans_" in attribute:
            attribute = attribute.replace("kmeans_", "")
        # color_pal = attributes_color_map[attribute]
        sns.scatterplot(
            data=df,
            x="umap1",
            y="umap2",
            hue=hue_attribute,
            ax=axs[row][col],
            alpha=.8,
            s=60,
            palette=attributes_color_map
        )
        unique_labels = len(list(set(df[hue_attribute])))
        subplot_title = "Color is set to: " + hue_attribute + ", Number of unique labels: " + str(unique_labels)
        axs[row][col].set_title(subplot_title)
        axs[row][col].set(xticklabels=[], yticklabels=[])
        axs[row][col].set_xlabel("UMAP1")
        axs[row][col].set_ylabel("UMAP2")
        axs[row][col].grid(False)
        axs[row][col].legend(loc='center left', bbox_to_anchor=(1, 0.5))

        if col == 1:
            row += 1
            col = 0
        else:
            col += 1
    # plt.tight_layout()
    fig.tight_layout(pad=5.0)
    fig.suptitle(title, fontsize=14)
    plt.savefig(save_path + "umap_with_kmeans_labels.png", format="png", dpi=300)
    plt.show()

def print_indexes(list_):
    map_indexes = {}
    for value in set(list_):
        indexes = [i for i, x in enumerate(list_) if x == value]
        print(f"Indexes of {value}: {indexes}")
        for i in indexes:
            map_indexes[str(i)] = value
    return map_indexes

    # generate a boxplot to see the data distribution by treatments. Using boxplot, we can
    # easily detect the differences between different treatments

# def silhouette(km, X):
#     visualizer = SilhouetteVisualizer(km, colors='yellowbrick')
#     visualizer.fit(X)  # Fit the data to the visualizer
#     visualizer.show()  # Finalize and render the figure

if __name__ == '__main__':
    # anova()
    print("The End")


import logging
import scrapy
import os
from scrapy import Spider
from vandenborre.items import Manual

logger = logging.getLogger(__name__)

class VandenBorreSpider(Spider):
    name = "vandenborre.be"
    start_urls = [
        "https://www.vandenborre.be/sitemap/nl/default/",
        "https://www.vandenborre.be/sitemap/fr/default/",
        ]

    def parse(self, response):
        for section in response.css('.border-btm-grey-sm.margin-btm-10-sm'):
            if not section:
                continue
            for goto in section.css('.listicon.clearfix.margin-btm-60-md.margin-btm-20-sm.margin-top-20-sm.js-content.hide-sm .nolist.flex.flex-wrap .col-xs-12.col-md-3 a::attr(href)').extract():
                goto = response.urljoin(goto)
                yield scrapy.Request(url=goto, callback=self.get_each_brand_li)

    def get_each_brand_li(self, response):
        for link in response.css('.border-btm-grey-sm.margin-btm-10-sm'):
            if not link:
                continue
            for goto in link.css('.listicon.clearfix.margin-btm-60-md.js-content.margin-btm-20-sm.margin-top-20-sm.hide-sm .nolist.flex.flex-wrap .col-xs-12.col-md-3 a::attr(href)').extract():
                goto = response.urljoin(goto)
                yield scrapy.Request(url=goto, callback=self.get_product_data)

    def get_product_data(self, response):
        pdf_files = response.css('.js-specs-doc.clearfix .doc-link.flex div>a::attr(href)').extract()
        if len(pdf_files) == 0:
            return
        for pdf in pdf_files:
            pdf = pdf.replace(' ', '%20') # removing spaces from the pdf link
            manual = Manual()
            bread_crums = response.css('.breadcrumbs.js-breadcrumbs.hidden-print.w-100 .row .col-xs-12 ul>li')
            manual["product"] = bread_crums[-2].css('.js-ellipsis *::text').extract_first()
            brand = response.css('.product-detail-title.no-margin-btm a *::text').extract_first()
            manual["brand"] = brand.strip()
            thumb = response.css('.image-gallery-main-image.js-image-gallery-main-image.js-image-zoom-image.image-gallery-main-image-0::attr(data-large-image)').extract_first()
            manual["thumb"] = response.urljoin(thumb)
            # nested_fonts = response.css('.product-detail-title.no-margin-btm::text').extract_first()
            # model = nested_fonts.css('font ::text').extract_first()
            model = response.css('.product-detail-title.no-margin-btm::text').extract_first()
            manual["model"] = model
            # manual["model"] = model.strip()
            manual["source"] = self.name
            manual["file_urls"] = [response.urljoin(pdf)]
            manual["url"] = response.urljoin('')
            manual["type"] = response.css('.js-specs-doc.clearfix .doc-link.flex div>a *::text').extract_first()
            print(manual)
            yield manual


from django.core.urlresolvers import reverse
from test_plus.test import TestCase, settings

class TestHomeView(TestCase):

    def test_login_required(self):
        home_url = 'home'

        response = self.get(home_url)
        reversed_url = reverse(home_url)
        login_url = reverse(settings.LOGIN_URL)
        expected_url = "{0}?next={1}".format(login_url, reversed_url)
        self.assertRedirects(response, expected_url)


import logging

from run_match import play_matches, TEST_AGENTS, NUM_PROCS, NUM_ROUNDS, TIME_LIMIT
from argparse import Namespace
from isolation import Agent
from my_standard_player import AlphaBetaPlayer

logger = logging.getLogger(__name__)

args = Namespace()
setattr(args, 'debug', False)
setattr(args, 'fair_matches', True)
setattr(args, 'processes', NUM_PROCS)
setattr(args, 'rounds', NUM_ROUNDS)
setattr(args, 'time_limit', TIME_LIMIT)

if __name__ == "__main__":

    test_agent = Agent(AlphaBetaPlayer, "Alpha Beta Agent")
    custom_agent = TEST_AGENTS["SELF"]
    wins, num_games = play_matches(custom_agent, test_agent, args)

    logger.info("Your agent won {:.1f}% of matches against {}".format(
       100. * wins / num_games, test_agent.name))
    print("Your agent won {:.1f}% of matches against {}".format(
       100. * wins / num_games, test_agent.name))
    print()


# Write your code here :-)
from random import randint

while True:
    # Ask user for input
    player = input('rock(r), paper(p), or scissors(s)?')

    # Have computer choose 1-3
    chosen = randint(1,3)

    # Assign letters to the random numbers

    if chosen == 1:
        computer = "r"
    elif chosen == 2:
        computer = "p"
    elif chosen == 3:
        computer = "s"

    # Write out the chosen symbols
    print("Player: " + player + " vs Computer: " + computer)

    #Determine who won

    if player == computer:
        print("It's a tie!!!")
    elif player == "r" and computer == "s":
        print("You win!!!")
    elif player == "s" and computer == "p":
        print("You Win!!!")
    elif player == "p" and computer == "r":
        print("You Win!")
    else:
        print("You Lose!!!!")


# SF-482
import json
import pandas as pd

# from xcalar.solutions.singleton import Singleton_Controller
from xcalar.solutions.tools.connector import XShell_Connector
from colorama import Style
from tabulate import tabulate
from pygments import highlight
from pygments.lexers import JsonLexer
from pygments.formatters import TerminalFormatter
from .action_confirm import confirm

def dispatcher(line):
    help = {
        'show_all':
            f"""
Usage:

DATASET
    {Style.NORMAL}dataset {Style.DIM}-list{Style.RESET_ALL}                                                     {Style.BRIGHT}- lists all datasets in xd.{Style.RESET_ALL}
    {Style.NORMAL}dataset {Style.DIM}-show      <dataset> <#start : #rows>{Style.RESET_ALL}                     {Style.BRIGHT}- shows top 10 rows/[x:y rows] in the dataset.{Style.RESET_ALL}
    {Style.NORMAL}dataset {Style.DIM}-describe  <dataset>{Style.RESET_ALL}                                      {Style.BRIGHT}- shows information of a dataset, including number of records, etc.{Style.RESET_ALL}
    {Style.NORMAL}dataset {Style.DIM}-drop      <dataset>{Style.RESET_ALL}                                      {Style.BRIGHT}- deletes the dataset.{Style.RESET_ALL}
""",
        'dataset_list':
            f"""
Usage:
    dataset
    {Style.NORMAL}dataset {Style.DIM}-list{Style.RESET_ALL}                       {Style.BRIGHT}- lists all datasets in xd.{Style.RESET_ALL}
        """,
        'dataset_show':
            f"""
Usage:
    dataset
    {Style.NORMAL}dataset {Style.DIM}-show <dataset>{Style.RESET_ALL} <#start : #rows>            {Style.BRIGHT}- shows top 10 rows/[x:y rows] in the dataset.{Style.RESET_ALL}
        """,
        'dataset_describe':
            f"""
Usage:
    dataset
    {Style.NORMAL}dataset {Style.DIM}-describe <dataset>{Style.RESET_ALL}         {Style.BRIGHT}- shows information of a dataset, including number of records, etc.{Style.RESET_ALL}

        """,
        'dataset_drop':
            f"""
Usage:
    dataset
        {Style.NORMAL}dataset {Style.DIM}-drop <dataset>{Style.RESET_ALL}             {Style.BRIGHT}- deletes the dataset.{Style.RESET_ALL}
        """,
    }

    def show_dataset(dataset_name, start, num_rows):
        dataset = controller.orchestrator.dispatcher.xcalarClient.get_dataset(
            dataset_name)
        columns = list(map(lambda x: x['name'], dataset.get_info()['columns']))
        show_table_or_dataset(dataset, columns, start, num_rows)

    def show_table_or_dataset(table_or_dataset, columns, start, num_rows):
        data = []
        for row in table_or_dataset.records(
                start_row=start, num_rows=num_rows):
            r_data = []
            for col in columns:
                if col in row:
                    r_data.append(row[col])
                else:
                    r_data.append(None)
            data.append(tuple(r_data))
        print(
            tabulate(
                pd.DataFrame.from_records(data, columns=columns),
                showindex=range(start, start + len(data)),
                headers='keys',
                tablefmt='psql',
            ))

    tokens = line.split()

    if len(tokens) == 0:
        print(help['show_all'])
        return

    try:
        # singleton_controller = Singleton_Controller.getInstance()
        # controller = singleton_controller.get_controller()
        xshell_connector = XShell_Connector()
        controller = xshell_connector.get_controller()
        # dataset
        if tokens[0] == '-list':
            datasets = controller.orchestrator.dispatcher.xcalarClient.list_datasets(
            )
            names = list(map(lambda x: x.name, datasets))

            t = zip(names)
            print(tabulate(
                t,
                headers=['dataset'],
                tablefmt='psql',
            ))

        elif tokens[0] == '-show':
            if len(tokens) == 3 and tokens[1]:
                dataset_name = tokens[1]
                x = int(tokens[2].split(':')[0])
                y = int(tokens[2].split(':')[1])

                show_dataset(dataset_name, x, y)
            else:
                print(help['dataset_show'])

        elif tokens[0] == '-describe':
            if len(tokens) == 2 and tokens[1]:
                dataset = controller.orchestrator.dispatcher.xcalarClient.get_dataset(
                    tokens[1])
                info = dataset.get_info()

                json_object = json.loads(json.dumps(info))
                json_str = json.dumps(json_object, indent=4, sort_keys=True)
                print(highlight(json_str, JsonLexer(), TerminalFormatter()))

            else:
                print(help['dataset_describe'])

        elif tokens[0] == '-drop':
            if len(tokens) == 2 and tokens[1]:
                if confirm() is None:
                    return
                pass
            else:
                print(help['dataset_drop'])

        else:
            print(help['show_all'])

    except AttributeError as ex:
        print(f'{Style.DIM}Warning: {Style.RESET_ALL} {ex}')
    except KeyboardInterrupt:
        print(f'{Style.DIM}Warning: {Style.RESET_ALL} Ctrl-c detected.')
        return
    except Exception as e:
        print(f'{Style.DIM}Warning: {Style.RESET_ALL} {e}')

def load_ipython_extension(ipython, *args):
    def dataset_completers(self, event):
        return [
            '-list',
            '-show',
            '-describe',
            '-drop',
        ]

    ipython.register_magic_function(dispatcher, 'line', magic_name='dataset')
    ipython.set_hook('complete_command', dataset_completers, str_key='dataset')
    ipython.set_hook(
        'complete_command', dataset_completers, str_key='%dataset')

def unload_ipython_extension(ipython):
    pass


decrescente = True
anterior = int(input("Digite o primeiro numero: "))
valor = 1

while valor != 0 and decrescente:
    valor = int(input("Digite o proximo numero: "))
    if valor > anterior:
        decrescente = False
    anterior = valor

if decrescente: #Porque decrescente ja tem o valor True
    print("Esta em ordem decrescente")
else:
    print("Nao esta em ordem decrescente")


import numpy as np
import cv2
import pdb
import os
from ellipse_my import ellipse_my
from watershed import watershed

w_thr = 4
h_thr = 4
offset = 10
box_off =[[0, 0], [0, offset], [0, -offset], [offset, 0], [-offset, 0]]

def get_part_set(ellipse_info, part_num=128):
    '''
    Use ellipse_info to get part point set.
    '''
    part_label = ellipse_my(ellipse_info, part_num)

    return part_label

def get_single_old_box(cur_axis, next_axis):

    lx = np.min((cur_axis[1], next_axis[1]))
    rx = np.max((cur_axis[1], next_axis[1]))
    ly = np.min((cur_axis[0], next_axis[0]))
    ry = np.max((cur_axis[0], next_axis[0]))

    cx = (lx + rx) / 2
    cy = (ly + ry) / 2
    w = (rx - lx) / 2
    h = (ry - ly) / 2
    if w < w_thr:
        w = w_thr
    if h < h_thr:
        h = h_thr

    print('after (%d, %d)' % (w, h))

    print('cx: %d, cy: %d' % (cx, cy))

    box = [int(cx-w), int(cy-h), int(cx+w), int(cy+h)]
    #box = [int(lx), int(ly), int(rx), int(ry)]

    return box

def get_single_box(cur_axis, next_axis):

    cx = cur_axis[1]
    cy = cur_axis[0]
    w = w_thr
    h = h_thr

    #print('after (%d, %d)' % (w, h))

    #print('cx: %d, cy: %d' % (cx, cy))

    box = [int(cx-w), int(cy-h), int(cx+w), int(cy+h)]
    #box = [int(lx), int(ly), int(rx), int(ry)]

    return box

def get_diff_single_box(cur_axis, box_num=5):

    cx = cur_axis[1]
    cy = cur_axis[0]
    w = w_thr
    h = h_thr
    box_set = []

    for i in range(box_num):
        cx_n = cx + box_off[i][0]
        cy_n = cy + box_off[i][1]
        box = [int(cx_n-w), int(cy_n-h), int(cx_n+w), int(cy_n+h)]
        box_set.append(box)

    return box_set

def get_part_box(ellipse_info, part_num=64):

    box_list = []

    part_set = get_part_set(ellipse_info, part_num)

    for i in range(len(part_set)):

        cur_index = i
        next_index = (i+1) % len(part_set)
        box = get_single_box(part_set[cur_index], part_set[next_index])
        box_list.append(box)

    return box_list

def get_point_box(im, im_show):
    '''
    use every point which draw by cv2.ellipse as center to get box list.
    '''

    sz = im.shape
    pset = []
    box_list = []
    for i in range(sz[0]):
        for j in range(sz[1]):
            if im[i][j][0] == 0:
                pset.append([h_thr, w_thr])
                box = get_single_box([i, j], None)
                box_list.append(box)

                #cv2.rectangle(im_show, (box[0], box[1]), (box[2], box[3]),  (0,255,0), 1)
                #cv2.imwrite('0grad_dire.bmp', im_show)
                #pdb.set_trace()

    return box_list, pset

def get_adaptive_box(ellipse_info, part_num=128):

    box_list = []

    part_set = get_part_set(ellipse_info, part_num)

    for i in range(len(part_set)):

        cur_index = i
        box_set = get_diff_single_box(part_set[cur_index])
        box_list.append(box_set)

    return box_list

def threshold_(im):
    _, thresh = cv2.threshold(im, 80, 255, cv2.THRESH_BINARY_INV)

    return thresh

def otsu_threshold_(im):

    _,thresh = cv2.threshold(im, 0, 255, cv2.THRESH_BINARY+ cv2.THRESH_OTSU)

    return thresh

def canny_(im):
    cv2.GaussianBlur(im, ksize=(5,5), sigmaX=2)
    im = cv2.Canny(im, threshold1=127, threshold2=255)

    return im

def adaptiveThreshold_(im):

    #cv2.adaptiveThreshold(src, maxValue, adaptiveMethod, thresholdType, blockSize, C)
    im = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 15, 2)

    return im

def grad_(im):

    solelx = cv2.Sobel(im, cv2.CV_64F, 1, 0, ksize=3)
    solely = cv2.Sobel(im, cv2.CV_64F, 0, 1, ksize=3)
    grad = cv2.magnitude(solelx, solely)

    return grad

def grad_direction(im):

    im = cv2.phase(cv2.Sobel(im, cv2.CV_64F, 1, 0, ksize=3), cv2.Sobel(im,cv2.CV_64F, 0, 1, ksize=3), angleInDegrees=True)

    return im

def watershed_im(im, im_gray, ellipse_info):

    box_list = get_part_box(ellipse_info)
    for i in range(len(box_list)):
        box = box_list[i]
        im_crop = im[box[1]:box[3], box[0]:box[2]]
        watered_crop = watershed(im_crop)
        #watered_crop = threshold_(im_crop)
        im_gray[box[1]:box[3], box[0]:box[2]] = watered_crop

    return im_gray

def adpThreshold_im(im, im_gray, ellipse_info):

    box_list = get_part_box(ellipse_info)
    #im_c = im_gray.copy()
    im_c = im.copy()
    sz = im_gray.shape

    for i in range(len(box_list)):
        box = box_list[i]

        if box[0]<0 or box[1]<0 or box[2]>= sz[1] or box[3]>=sz[0]:
            continue
        im_crop = im_gray[box[1]:box[3], box[0]:box[2]]
        crop = adaptiveThreshold_(im_crop)
        #crop = otsu_threshold_(im_crop)
        ii = 0
        jj = 0

        b_cx = int((box[2]-box[0])/2)
        b_cy = int((box[3]-box[1])/2)
        flag = crop[b_cy][b_cx]
        for i in range(box[1], box[3]):
            for j in range(box[0], box[2]):
                #print('ii: %d, jj: %d' % (ii, jj))
                #print('i: %d, j:%d' % (i, j))
                if crop[ii][jj] == flag:
                    im_c[i][j] = 255
                jj += 1
            ii += 1
            jj = 0
        '''
        crop3 = np.zeros((crop.shape[0], crop.shape[1], 3))
        crop3[:,:,0] = crop
        crop3[:,:,1] = crop
        crop3[:,:,2] = crop
        im_c[box[1]:box[3], box[0]:box[2]] = crop3
        '''
    return im_c

def main():
    filename = 'img00001'
    im = cv2.imread('%s.bmp' % filename)

    lx, ly, rx, ry = 856, 261, 1346, 730
    w=rx-lx
    h=ry-ly
    cx=(lx+rx)/2
    cy=(ly+ry)/2

    ellipse_info = ((cx, cy), (w, h), 0)
    print(ellipse_info)
    box_list = get_part_box(ellipse_info)
    cv2.ellipse(im, ellipse_info, (0,255,0),1)

    for i in range(len(box_list)):
        box = box_list[i]
        cv2.rectangle(im, (box[0], box[1]), (box[2], box[3]),  (0,255,0), 1)

    cv2.imwrite('%s_re_box.bmp' %  filename, im)

def main_watershed():

    filename = 'img00004'
    im = cv2.imread('%s.bmp' % filename)
    im_gray = cv2.imread('%s.bmp' % filename, 0)

    lx, ly, rx, ry = 856, 261, 1346, 730
    w=rx-lx
    h=ry-ly
    cx=(lx+rx)/2
    cy=(ly+ry)/2

    ellipse_info = ((cx, cy), (w, h), 0)
    after_watershed = watershed_im(im, im_gray, ellipse_info)

    cv2.imwrite('%s_watershed.bmp' % filename, after_watershed)

def main_adap():

    filename = 'img00004'
    im = cv2.imread('%s.bmp' % filename)
    im_gray = cv2.imread('%s.bmp' % filename, 0)

    lx, ly, rx, ry = 856, 261, 1346, 730
    w=rx-lx
    h=ry-ly
    cx=(lx+rx)/2
    cy=(ly+ry)/2

    ellipse_info = ((cx, cy), (w, h), 0)
    after_adap = adpThreshold_im(im, im_gray, ellipse_info)

    cv2.imwrite('%s_watershed.bmp' % filename, after_adap)

def main_test_adap():

    filename = 'img00004'
    im = cv2.imread('%s.bmp' % filename)
    im_gray = cv2.imread('%s.bmp' % filename, 0)

    #im = adaptiveThreshold_(im_gray)
    im = otsu_threshold_(im_gray)

    cv2.imwrite('adap_%s.bmp' % filename, im)

def main_test_grad():

    filename = 'img00003'
    im = cv2.imread('%s.bmp' % filename)
    im_gray = cv2.imread('%s.bmp' % filename, 0)

    im = grad_(im_gray)

    cv2.imwrite('grad_%s.bmp' % filename, im)

def main_test_grad_dire():

    filename = 'img00003'
    im = cv2.imread('%s.bmp' % filename)
    im_gray = cv2.imread('%s.bmp' % filename, 0)

    im = grad_direction(im_gray)

    cv2.imwrite('grad_dire%s.bmp' % filename, im)

if __name__ == '__main__':
    #main()
    #main_watershed()
    #main_adap()
    main_test_grad()
    #main_test_grad_dire()


from googletrans import Translator
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

def start_func(update, context):
    update.message.reply_text("""سلام \nپیام انگلیسی یا فارسی خود را ارسال کنید.\n/about""")
    print('Start REQ from {}'.format(update.message.from_user.first_name))

def trans_func(update, context):
    user_text = update.message.text
    lang = Translator().detect(user_text).lang

    if lang == 'fa':
        transed = Translator().translate(user_text, dest='en').text
        update.message.reply_text(transed)
    elif lang == 'en':
        transed = Translator().translate(user_text, dest='fa').text
        update.message.reply_text(transed)
    else:
        transed = Translator().translate(user_text, dest='fa').text
        update.message.reply_text(transed)
def about_func(update, context):
	update.message.reply_text("coder @six_6_six\nchannel @freezed_cash\ngithub github.com/mohsenfn")

updater = Updater("token here", use_context=True)
updater.dispatcher.add_handler(CommandHandler("about", about_func))
updater.dispatcher.add_handler(CommandHandler("start", start_func))
updater.dispatcher.add_handler(MessageHandler(Filters.text, trans_func))
print("Running ...")
updater.start_polling()
updater.idle()
# done


import time
from django.core.management.base import BaseCommand
from ...fetcher import *

class Command(BaseCommand):
    help = "Fetches new commits from the repository under test every 10 minutes"

    def handle(self, *args, **options):
        while True:
            fetch_main_branch_revisions()
            fetch_staging_revisions()
            print("Sleeping for 10 mins...")
            time.sleep(10 * 60)