import json
from abc import abstractmethod
from typing import Tuple

from sommelier.utils import StringUtils

def expand_nested_keys(payload):
    # To represent json in flattened form use `.` for specifying nested fields
    # * Given json:
    #
    # {name: Bob, education: {level: bachelor, grade: good}}
    #
    # * Flattened form:
    #
    # name: Bob
    # education.level: bachelor
    # eduction.grade: good

    nested_keys = []
    for k in payload:
        if '.' in k:
            nested_keys.append(k)

    for k in nested_keys:
        value = payload[k]
        current_obj = payload
        # Zoom into the key which will create new objects or reuse existing
        key_list = k.split('.')
        for i in range(len(key_list)):
            subkey = key_list[i]
            if subkey in current_obj:
                # reuse existing object and keep zooming
                current_obj = current_obj[subkey]
            else:
                if i == len(key_list) - 1:
                    # we reached the end and need to save value
                    current_obj[subkey] = value
                else:
                    # we are still zooming
                    current_obj[subkey] = {}
                current_obj = current_obj[subkey]

        # nobody needs fully qualified key at the end of this procedure
        del payload[k]

    return _convert_indexed_obj_to_arr(payload)

def _convert_indexed_obj_to_arr(payload):
    if not isinstance(payload, dict):
        return payload
    arr = []
    arr_key = None
    for k in payload:
        if StringUtils.is_array(k):
            arr_key = k
            arr.append(payload[k])
        else:
            payload[k] = _convert_indexed_obj_to_arr(payload[k])

    if arr_key is not None:
        return arr
    else:
        return payload

if __name__ == '__main__':
    def display(data):
        print(json.dumps(data, ensure_ascii=False, sort_keys=True, indent=4))

    def perform_check(given, expected):
        result = expand_nested_keys(given)
        ok = (expected == result)
        if not ok:
            display(expected)
            display(result)
        else:
            print("Successful")
    test_cases = [
        {
            "given": {
                "data.[0].user": {
                    "name": "John"
                },
                "data.[1].user": {
                    "name": "Bob"
                }
            },
            "expected": {
                "data": [
                    {"user": {"name": "John"}},
                    {"user": {"name": "Bob"}}
                ]
            }
        },
        {
            "given": {
                "[0]": 1,
                "[1]": 2,
            },
            "expected": [1, 2]
        },
        {
            "given": {
                "data.first.[0]": "apple",
                "data.first.[1]": "banana",
                "data.second.[0]": "kiwi",
                "data.second.[1].box": "carrots",
            },
            "expected": {
                "data": {
                    "first": [
                        "apple",
                        "banana",
                    ],
                    "second": [
                        "kiwi",
                        {"box": "carrots"},
                    ]
                }
            }
        }
    ]

    for v in test_cases:
        perform_check(v["given"], v["expected"])

class TableXDimensions(object):
    # Represents parsed Behave Table

    def __init__(self, data) -> None:
        self.data = data

    @abstractmethod
    def rows(self):
        # Can iterate over each row
        pass

class Table2D(TableXDimensions):
    # Contains 2 columns

    def __init__(self, data) -> None:
        super().__init__(data)

    def rows(self) -> Tuple:
        payload = dict(self.data)
        for k, val in payload.items():
            if isinstance(val, str):
                payload[k] = StringUtils.try_convert_num(val)
            elif isinstance(val, list):
                payload[k] = [StringUtils.try_convert_num(x) for x in val]
            else:
                payload[k] = val
        for row in payload.items():
            yield str(row[0]), row[1]

    def dict(self) -> dict:
        # convert from CSV notation to JSON aka Python dictionary
        payload = {}
        for key, val in self.rows():
            payload[key] = val

        return expand_nested_keys(payload)

class Table1D(TableXDimensions):
    # Contains 1 column

    def __init__(self, data) -> None:
        super().__init__(data)

    def rows(self) -> str:
        for row in self.data:
            yield str(row[0])

    def list(self) -> list:
        return self.data


# easy fast
from collections import deque

N, M = map(int, input().split())
kakao_map = [list(map(int, input().split())) for _ in range(N)]

start = False
for i in range(N):
    for j in range(M):
        if kakao_map[i][j] == 2:
            start = (i, j)
            break
    if start:
        break
visited =[[0]*M for _ in range(N)]
dist = [[0]*M for _ in range(N)]
dist[start[0]][start[1]] = 0
Q = deque([start])
visited[start[0]][start[1]] = 1

move = [(1, 0), (0, 1), (-1, 0), (0, -1)]

while Q:
    x, y = Q.popleft()
    for i in range(4):
        nx = x + move[i][0]
        ny = y + move[i][1]
        if nx < 0 or ny < 0 or nx == N or ny == M:
            continue
        if not visited[nx][ny] and kakao_map[nx][ny]:
            visited[nx][ny] = 1
            if not dist[nx][ny]:
                dist[nx][ny] = dist[x][y] + 1
            elif dist[nx][ny] > dist[x][y] + 1:
                dist[nx][ny] = dist[x][y] + 1
            Q.append((nx, ny))

for i in range(N):
    for j in range(M):
        if not visited[i][j] and kakao_map[i][j]:
            dist[i][j] = -1

for i in dist:
    print(*i)


import os
import re
from datetime import datetime
from copy import deepcopy

from openpyxl import Workbook
from scrapy.selector import Selector

def clean(text):
    if isinstance(text, (int, float)):
        return text
    if not text:
        return ''
    for c in ['\r\n', '\n\r', u'\n', u'\r', u'\t', u'\xa0', '\\']:
        text = text.replace(c, ' ')
    return re.sub(' +', ' ', text).strip()

class ParseProductsXmlScript:
    # txt / xml files directory
    files_directory = 'xml_files'

    # Output Results CSV file in which transaction records stored
    transactions_fp = 'toptel_products.csv'

    csv_headers = [
        "product_id", "name", "ean", "categories", "image_urls", "description", "link",
    ]

    def __init__(self):
        super().__init__()
        self.csv_writer = self.get_csv_writer()
        self.wb = Workbook()
        self.sheet = self.wb.active
        self.sheet_row_index = 1
        self.create_xls_write_headers()

        for fp in self.get_files():
            try:
                print(f"Parsing file: {fp}")
                self.parse_xml(fp)
            except Exception as exc:
                print(f"Exception while parsing file-> {fp}\n{exc}")

        self.wb.save(f"toptel_products.xlsx")

    def parse_xml(self, xml_path):
        xml_data = open(xml_path, encoding='utf-8').read()
        raw_xml = xml_data.replace('<![CDATA[', '').replace(']]>', '')
        selector = Selector(text=raw_xml)

        for trans_s in selector.css('product'):
            try:
                if not trans_s or not self.get_sel_text(trans_s, 'product_id'):
                    continue
                product = self.get_item(trans_s)
                self.write_xls(product)
                # self.write_to_csv(product)
            except Exception as err:
                print(err)
            a = 0

    def get_item(self, trans_s):
        item = {}
        item["product_id"] = self.get_sel_text(trans_s, 'product_id')
        item["name"] = self.get_sel_text(trans_s, 'name')
        item['ean'] = self.get_sel_text(trans_s, 'ean')
        item["categories"] = self.get_categories(trans_s)
        item["description"] = self.get_description(trans_s)
        item["image_urls"] = self.get_image_urls(trans_s)
        item["link"] = re.findall(r'link>(.*)', trans_s.get())[0].split('<')[0]

        if '85' == item["product_id"]:
            a = 0
        return item

    def get_sel_text(self, trans_s, css, default=None):
        if default is None:
            default = ''
        return (trans_s.css(f'{css}::text').get('') or trans_s.css(f'{css.lower()}::text').get('')).strip() or default

    def get_attr_val(self, trans_s, tag, attr, default=None):
        if default is None:
            default = ""
        return trans_s.css(f'{tag}::attr({attr})').get() or \
               trans_s.css(f'{tag.lower()}::attr({attr.lower()})').get() or default

    def get_attr_all_vals(self, trans_s, tag, attr, default=None):
        if default is None:
            default = []
        vals = trans_s.css(f'{tag}::attr({attr})').getall() or \
               trans_s.css(f'{tag.lower()}::attr({attr.lower()})').getall() or default
        return ", ".join(f'"{v}"' for v in vals if clean(v))

    def write_to_csv(self, item):
        row = '$'.join('"{}"'.format(item.get(h, '')) for h in self.csv_headers) + '\n'
        self.csv_writer.write(row)
        print("Record inserted into CSV file.")
        print(item)

    def get_csv_writer(self):
        file = open(self.transactions_fp, mode='w', encoding='utf-8')
        file.write('$'.join(h for h in self.csv_headers) + '\n')
        return file

    def get_files(self):
        files = []

        for file_path in os.listdir(self.files_directory):
            if '.xml' not in file_path:
                continue
            file_path = self.files_directory + '/' + file_path
            files.append(file_path)

        return files

    def get_categories(self, trans_s):
        return ", ".join([clean(e) for e in trans_s.css('cat_name::text').getall()])

    def get_image_urls(self, trans_s):
        urls = [e for e in trans_s.css('photo::text, photo ::text').getall() if 'http:' in e] \
               or re.findall(r'photo>(.*)<', trans_s.get())
        if not urls:
            urls.append(f"https://toptel.com/files/fotob/product-{self.get_sel_text(trans_s, 'product_id')}.jpg")
        return ", ".join(urls)

    def get_description(self, trans_s):
        return clean(trans_s.css('desc').get())

    def create_xls_write_headers(self):
        for index, value in enumerate(self.csv_headers):
            self.sheet.cell(row=self.sheet_row_index, column=index + 1).value = value
        self.sheet_row_index += 1

    def write_xls(self, item):
        for idx, key in enumerate(self.csv_headers):
            self.sheet.cell(row=self.sheet_row_index, column=idx + 1).value = item.get(key, '')

        self.sheet_row_index += 1
        print(f"Product written in excel \n {item}")

# main function that is entry point of python script
if __name__ == "__main__":
    ParseProductsXmlScript()


# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from wsme import types as wtypes

from solum.api.controllers import common_types
from solum.api.controllers.v1.datamodel import types as api_types

class Extension(api_types.Base):
    """The Extension resource represents Provider modifications.

    This may include additional protocol semantics, resource types,
    application lifecycle states, resource attributes, etc. Anything may be
    added, as long as it does not contradict the base functionality offered
    by Solum.
    """

    version = wtypes.text
    "Version of the extension."

    documentation = common_types.Uri
    "Documentation URI to the extension."

    @classmethod
    def sample(cls):
        return cls(uri='http://example.com/v1/extensions/logstash',
                   name='logstash',
                   type='extension',
                   tags=['large'],
                   project_id='1dae5a09ef2b4d8cbf3594b0eb4f6b94',
                   user_id='55f41cf46df74320b9486a35f5d28a11',
                   description='This logstash extension provides a tool for '
                               'managing your application events and logs.',
                   version='2.13',
                   documentation='http://example.com/docs/ext/logstash')


import bs4
import re
from functools import reduce

def get_soup(arg):
    return bs4.BeautifulSoup(open(arg), "lxml")

def unpad(s):
    return re.sub(r"^[ \r\n\t]*", "",
                  re.sub(r"[ \r\n\t]*$", "", s))

def unwhitespace(s):
    return re.sub(r"[ \r\n\t]", "", s)

def clean_supervisors(s):
    s = re.sub(r",? *& *(, )?", ", ", s)
    s = re.sub(r",? +and *(, )?", ", ", s)
    s = re.sub(r"\xa0", "", s)
    name = re.compile(r"([A-Za-z]+[-\. ]*)+(\(([A-Za-z]+[-\., ]*)+\))")
    s = re.findall(name, s)
    return s

def extract_table(filename):
    soup = bs4.BeautifulSoup(open(filename), "lxml")
    [thead, tbody] = soup.find("table").children
    header = [unpad(i.text) for i in thead.find_all("th")]
    rows = [[unpad(j.text) for j in i.find_all("td")] for i in tbody.find_all("tr")]
    lod = [{i:j for (i,j) in zip(header, row)} for row in rows]
    return lod

if __name__ == '__main__':
    from decisions import lmap
    lod = extract_table("table.html")
    for item in lod:
        item["Supervisors"] = clean_supervisors(item["Supervisors"])
    sups = reduce(lambda a, b: a + b, lmap(lambda d: d["Supervisors"], lod))
    sups.sort()


#!/usr/bin/env python
"""
Test module for TwoPhaseFlow
"""
import pytest
import tables
import numpy as np
import proteus.defaults
from proteus import Context
from proteus import default_so
from proteus.iproteus import *
import os
import sys
Profiling.logLevel=1
Profiling.verbose=True

class TestTwoPhaseFlow(object):

    def setup_method(self,method):
        self._scriptdir = os.path.dirname(__file__)
        self.path = proteus.__path__[0]+"/tests/TwoPhaseFlow/"

    def teardown_method(self, method):
        """ Tear down function """
        FileList = ['marin.h5','marin.xmf'
                    'moses.h5','moses.xmf'
                    'damBreak.h5','damBreak.xmf'
                    'TwoDimBucklingFlow.h5','TwoDimBucklingFlow.xmf'
                    'filling.h5','filling.xmf'
                    ]
        for file in FileList:
            if os.path.isfile(file):
                os.remove(file)
            else:
                pass

    def compare_vs_saved_files(self,name,write=False):
        actual = tables.open_file(name+'.h5','r')

        expected_path = 'comparison_files/' + 'comparison_' + name + '_phi_t2.csv'
        #write comparison file
        if(write):
            np.array(actual.root.phi_t2).tofile(os.path.join(self._scriptdir, expected_path),sep=",")
        np.testing.assert_almost_equal(np.fromfile(os.path.join(self._scriptdir, expected_path),sep=","),np.array(actual.root.phi_t2).flatten(),decimal=6)

        expected_path = 'comparison_files/' + 'comparison_' + name + '_velocity_t2.csv'
        #write comparison file
        if(write):
            np.array(actual.root.velocity_t2).tofile(os.path.join(self._scriptdir, expected_path),sep=",")
        np.testing.assert_almost_equal(np.fromfile(os.path.join(self._scriptdir, expected_path),sep=","),np.array(actual.root.velocity_t2).flatten(),decimal=6)

        actual.close()

    # *** 2D tests *** #
    def test_risingBubble(self): #uses structured triangle mesh
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "risingBubble.py -l5 -v -C 'final_time=0.1 dt_output=0.1 refinement=1'")
        self.compare_vs_saved_files("risingBubble")

    def test_damBreak(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "damBreak.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.1'")
        self.compare_vs_saved_files("damBreak")

    def test_damBreak_hotstart(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "damBreak.py -l5 -v -H -C 'final_time=0.1 dt_output=0.1 he=0.1 hotstart=True'")

    @pytest.mark.skipif(sys.platform == "darwin", reason="does not run on macOS")
    def test_TwoDimBucklingFlow(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "TwoDimBucklingFlow.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.09'")
        self.compare_vs_saved_files("TwoDimBucklingFlow")

    def test_fillingTank(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "fillingTank.py -l5 -v -C 'final_time=0.02 dt_output=0.02 he=0.01'")
        self.compare_vs_saved_files("fillingTank")

    # *** 3D tests *** #
    @pytest.mark.skipif(sys.platform == "darwin", reason="does not run on macOS")
    def test_marin(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "marin.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.5'")
        self.compare_vs_saved_files("marin")

    def test_moses(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "moses.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.5'")
        self.compare_vs_saved_files("moses")

    def test_damBreak_genPUMI(self):
        os.system("parun --TwoPhaseFlow --genPUMI --path " + self.path + " "
                  "damBreak.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.1'")

    def test_damBreak_runPUMI(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "damBreak_PUMI.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.1 adapt=0'")
        self.compare_vs_saved_files("damBreak_PUMI")

    def test_damBreak_pseudo_CLSVOF(self):
        os.system("parun --TwoPhaseFlow --path " + self.path + " "
                  "damBreak_PUMI.py -l5 -v -C 'final_time=0.1 dt_output=0.1 he=0.1 adapt=1'")
        self.compare_vs_saved_files("damBreak_PUMI")


import matplotlib
matplotlib.use("TkAgg")
import matplotlib.pyplot as plt

import pickle
import numpy as np
from pandas import read_csv
from pandas import DataFrame
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix

def load_data(dtree=False):
	data = read_csv("data/pulsar_stars.csv")
	y_data = np.array(data['target_class'])
	x = data.drop(['target_class'], axis=1)
	x_data = np.array([(x[column] - np.min(x[column]))/(np.max(x[column]) - np.min(x[column])) for column in x]).transpose() #scale between 0/1

	x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.25, random_state=0)

	if dtree:
		x_test, x_prune, y_test, y_prune = train_test_split(x_test, y_test, test_size=0.5, random_state=0)

		train_test_data = {'x_train': x_train,
						   'y_train': y_train,
						   'x_test': x_test,
						   'y_test': y_test,
						   'x_prune': x_prune,
						   'y_prune': y_prune}
		with open('train_test_data_dtree.pkl', 'wb') as output:
			pickle.dump(train_test_data, output, -1)

	else:
		train_test_data = {'x_train': x_train,
						   'y_train': y_train,
						   'x_test': x_test,
						   'y_test': y_test}

		with open('train_test_data.pkl', 'wb') as output:
			pickle.dump(train_test_data, output, -1)

	print('(Training data loaded successfully)\n')

def read_data(dtree=False):
	if dtree:
		with open('train_test_data_dtree.pkl', 'rb') as input:
			train_test_data = pickle.load(input)

		x_train = train_test_data['x_train']
		y_train = train_test_data['y_train']

		x_test = train_test_data['x_test']
		y_test = train_test_data['y_test']

		x_prune = train_test_data['x_prune']
		y_prune= train_test_data['y_prune']

		print('(Training data read successfully)\n')

		return x_train, y_train, x_test, y_test, x_prune, y_prune

	else:
		with open('train_test_data.pkl', 'rb') as input:
				train_test_data = pickle.load(input)

		x_train = train_test_data['x_train']
		y_train = train_test_data['y_train']

		x_test = train_test_data['x_test']
		y_test = train_test_data['y_test']

		print('(Training data read successfully)\n')

		return x_train, y_train, x_test, y_test

def view_data(data):

	keys = list(data)

	print(keys)

	noise_points = data[data.target_class==0]
	pulsar_points = data[data.target_class==1]

	fig, ax = plt.subplots(2, 2)

	ax[0, 1].scatter(noise_points[keys[1]], noise_points[keys[2]],label="RF Noise",color="red",alpha=0.1)
	ax[0, 1].scatter(pulsar_points[keys[1]], pulsar_points[keys[2]],label="Pulsar",color="purple",alpha=0.1)
	ax[0, 1].set_xlabel(keys[1])
	ax[0, 1].set_ylabel(keys[2])
	ax[0, 1].legend()

	ax[0, 0].scatter(noise_points[keys[0]], noise_points[keys[3]],label="RF Noise",color="red",alpha=0.1)
	ax[0, 0].scatter(pulsar_points[keys[0]], pulsar_points[keys[3]],label="Pulsar",color="purple",alpha=0.1)
	ax[0, 0].set_xlabel(keys[0])
	ax[0, 0].set_ylabel(keys[3])

	ax[1, 0].scatter(noise_points[keys[4]], noise_points[keys[7]],label="RF Noise",color="red",alpha=0.1)
	ax[1, 0].scatter(pulsar_points[keys[4]], pulsar_points[keys[7]],label="Pulsar",color="purple",alpha=0.1)
	ax[1, 0].set_xlabel(keys[4])
	ax[1, 0].set_ylabel(keys[7])

	ax[1, 1].scatter(noise_points[keys[5]], noise_points[keys[6]],label="RF Noise",color="red",alpha=0.1)
	ax[1, 1].scatter(pulsar_points[keys[5]], pulsar_points[keys[6]],label="Pulsar",color="purple",alpha=0.1)
	ax[1, 1].set_xlabel(keys[5])
	ax[1, 1].set_ylabel(keys[6])

	fig.suptitle('Pulsar Star vs RF Noise Attributes')
	plt.show()

def test_metrics(x_test, y_test, clf_obj, do_print=False):
	y_predict = clf_obj.predict(x_test)
	conf_mat = confusion_matrix(y_test, y_predict)

	true_pos = conf_mat[1][1]
	false_pos = conf_mat[0][1]
	false_neg = conf_mat[1][0]
	if (true_pos + false_pos) == 0:
		return 0

	precision = true_pos/(true_pos + false_pos)
	recall = true_pos/(true_pos + false_neg)
	f1 = 2 * (precision*recall) / (precision+recall)
	if do_print:
		print('Recall: ', str(recall))
		print('Precision: ', str(precision))
		print('F-measure: ', str(f1))
		print('Accuracy: ', str(accuracy_score(y_test, y_predict)*100))
		print('Confusion matrix:')
		print(conf_mat)
		print()
	return f1


import pygame
import pygame.freetype
import random

#Variables and constants
FPS =  75
UNIT_SIZE = 25
SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500

xDirection = 1
yDirection = 0

foodX = 0
foodY = 0

score = 0
scoreText = "0"

run = False

#initial snake values
bodyParts = 5
snake = [
    {"x": UNIT_SIZE*4, "y": 0}, #head index 0
    {"x": UNIT_SIZE*3, "y": 0},
    {"x": UNIT_SIZE*2, "y": 0},
    {"x": UNIT_SIZE*1, "y": 0},
    {"x": UNIT_SIZE*0, "y": 0}  #tail index 5
]

pygame.init()

SCORE_FONT = pygame.freetype.SysFont('Comic Sans MS', 30)
GAME_OVER_FONT = pygame.freetype.SysFont('Comic Sans MS', 70)
RESET_FONT = pygame.freetype.SysFont('Comic Sans MS', 20)

window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Snake in Python")

#methods
def startGame():
    global xDirection
    global yDirection

    xDirection = 1
    yDirection = 0

    newFood()
    gameLoop()

def newFood():

    global foodX
    global foodY

    foodY = random.randint(0, SCREEN_HEIGHT / UNIT_SIZE) * UNIT_SIZE
    foodX = random.randint(0, SCREEN_WIDTH / UNIT_SIZE) * UNIT_SIZE

    #Prevents food from spawning offscreen
    if foodX >= SCREEN_WIDTH:
        foodX -= UNIT_SIZE
    if foodY >= SCREEN_HEIGHT:
        foodY -= UNIT_SIZE

def drawFood():
    color = (255, 0, 0)
    pygame.draw.rect(window, color, pygame.Rect(foodX, foodY, UNIT_SIZE, UNIT_SIZE))

def drawSnake():
    for i in range(bodyParts):
        color = (0, 255, 0)
        pygame.draw.rect(window, color, pygame.Rect(snake[i]["x"], snake[i]["y"], UNIT_SIZE, UNIT_SIZE))

def moveSnake(xDir, yDir):

    global bodyParts
    global score
    global scoreText

    #moving the head of the snake
    snake.insert(0, {"x": (snake[0]["x"] + (xDir * UNIT_SIZE)), "y": (snake[0]["y"] + (yDir * UNIT_SIZE))})

    #if the snake eats food
    if snake[0]["x"] == foodX and snake[0]["y"] == foodY:
        score += 1
        scoreText = str(score)
        bodyParts += 1
        newFood()

    for i in range(bodyParts):
        if i == bodyParts:
            snake.pop(i)

def getDirection(key):
    #user input
    global xDirection
    global yDirection

    if key == pygame.K_w or key == pygame.K_UP:
        if yDirection != 1:
            yDirection = -1
            xDirection = 0
    elif key == pygame.K_s or key == pygame.K_DOWN:
        if yDirection != -1:
            yDirection = 1
            xDirection = 0
    elif key == pygame.K_a or key == pygame.K_LEFT:
        if xDirection != 1:
            xDirection = -1
            yDirection = 0
    elif key == pygame.K_d or key == pygame.K_RIGHT:
        if xDirection != -1:
            xDirection = 1
            yDirection = 0

def checkGameOver():

    if snake[0]["x"] >= SCREEN_WIDTH or snake[0]["x"] < 0 or snake[0]["y"] >= SCREEN_HEIGHT or snake[0]["y"] < 0:
        return False

    for i in range(bodyParts):
        if i != 0:
            if snake[0]["x"] == snake[i]["x"] and snake[0]["y"] == snake[i]["y"]:
                return False
    #if no game over occurs
    return True

def gameOver():

    global xDirection, yDirection, score, scoreText, snake, bodyParts

    window.fill((0,0,0))

    SCORE_FONT.render_to(window, (SCREEN_WIDTH/2 - 80, 10), "Final Score: "+scoreText, (0, 150, 255))
    GAME_OVER_FONT.render_to(window, (50, SCREEN_HEIGHT/2 - 20), "GAME OVER!", (255, 0, 50))
    RESET_FONT.render_to(window, (130, SCREEN_HEIGHT/2 + 75), "Press any key to restart", (0, 150, 255))

    pygame.display.update()

    resetCheck = True
    while resetCheck:
        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                resetCheck = False
                break
            elif event.type == pygame.KEYDOWN:

                #resetting to default values

                xDirection = 1
                yDirection = 0

                score = 0
                scoreText = "0"

                bodyParts = 5

                snake = [
                    {"x": UNIT_SIZE*4, "y": 0}, #head index 0
                    {"x": UNIT_SIZE*3, "y": 0},
                    {"x": UNIT_SIZE*2, "y": 0},
                    {"x": UNIT_SIZE*1, "y": 0},
                    {"x": UNIT_SIZE*0, "y": 0}  #tail index 5
                ]

                startGame()
                resetCheck = False

def gameLoop():

    global run

    #Game loop
    run = True
    while run:
        #resets window
        window.fill((0,0,0))

        #looks through events
        for event in pygame.event.get():
            #quits game
            if event.type == pygame.QUIT:
                run = False

            if event.type == pygame.KEYDOWN:
                getDirection(event.key)

        if checkGameOver() == False:
            run = False
            gameOver()

        moveSnake(xDirection, yDirection)
        drawSnake()
        drawFood()

        SCORE_FONT.render_to(window, (SCREEN_WIDTH/2 - 60, 10), "Score: "+scoreText, (0, 150, 255))

        pygame.display.update()

        pygame.time.wait(int(FPS))

#testing
startGame()

pygame.quit()


"""Test class ``atmcirclib.geo.BoundingBox``."""
from __future__ import annotations

# Third-party
import numpy as np
import pytest

# First-party
from atmcirclib.geo import BoundingBox

# pylint: disable=R0201  # no-self-use

class Test_Init:
    """Test initialization."""

    def test_noargs_fail(self) -> None:
        """Creating a new instance w/o arguments fails."""
        with pytest.raises(TypeError):
            BoundingBox()  # type: ignore

    def test_pos(self) -> None:
        """Use only positional arguments."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        assert bbx.llx == llx
        assert bbx.urx == urx
        assert bbx.lly == lly
        assert bbx.ury == ury

    def test_kw(self) -> None:
        """Use keyword arguments."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(
            lly=lly,
            llx=llx,
            ury=ury,
            urx=urx,
        )
        assert bbx.llx == llx
        assert bbx.urx == urx
        assert bbx.lly == lly
        assert bbx.ury == ury

class Test_Derive:
    """Test method ``derive`` to derive a new instance."""

    def test_equal(self) -> None:
        """Derive a new instance with the same coordinates."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx1 = BoundingBox(llx, urx, lly, ury)
        bbx2 = bbx1.derive()
        assert bbx1 is not bbx2
        assert bbx1 == bbx2

    def test_change(self) -> None:
        """Derive a new instance with changed coordinates."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx1 = BoundingBox(llx, urx, lly, ury)
        bbx2 = bbx1.derive(llx=-32, ury=12)
        assert bbx1 is not bbx2
        assert bbx1 != bbx2
        assert bbx2.llx == -32
        assert bbx2.urx == urx
        assert bbx2.lly == lly
        assert bbx2.ury == 12

class Test_FromCoords:
    """Test class method ``from_coords`` to create an instance from coords."""

    def test(self) -> None:
        """Create an instance from coordinate arrays."""
        xs = np.arange(-20, 5.1, 2)
        ys = np.arange(30, 45.1, 2)
        bbx = BoundingBox.from_coords(xs, ys)
        assert bbx.llx == xs[0]
        assert bbx.urx == xs[-1]
        assert bbx.lly == ys[0]
        assert bbx.ury == ys[-1]

class Test_Get:
    """Test methods ``get_*`` that return basic bbox properties."""

    def test_center(self) -> None:
        """Get center of box."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        cx, cy = bbx.get_center()
        assert np.isclose(cx, 0.5 * (llx + urx))
        assert np.isclose(cy, 0.5 * (lly + ury))

    def test_width(self) -> None:
        """Get width of box."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        w = bbx.get_width()
        assert np.isclose(w, urx - llx)

    def test_height(self) -> None:
        """Get height of box."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        h = bbx.get_height()
        assert np.isclose(h, ury - lly)

    def test_aspect(self) -> None:
        """Get aspect ratio of box."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        a = bbx.get_aspect()
        assert np.isclose(a, (urx - llx) / (ury - lly))

    def test_xlim(self) -> None:
        """Get limits of box in x-direction."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        xl = bbx.get_xlim()
        assert np.allclose(xl, (llx, urx))

    def test_ylim(self) -> None:
        """Get limits of box in y-direction."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        yl = bbx.get_ylim()
        assert np.allclose(yl, (lly, ury))

class Test_Shrink:
    """Test method ``shrink`` to reduce the size of the bbox."""

    def test_copy(self) -> None:
        """Check that the original instance is not affected by shrinking."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx1 = BoundingBox(llx, urx, lly, ury)
        bbx2 = bbx1.shrink(0)
        assert bbx1 is not bbx2
        bbx1.shrink(1)
        assert bbx1 == bbx2

    def test_scalar(self) -> None:
        """Shrink by the same amount in all directions."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        bbx = bbx.shrink(1)
        assert bbx.llx == llx + 1
        assert bbx.urx == urx - 1
        assert bbx.lly == lly + 1
        assert bbx.ury == ury - 1

    def test_tuple(self) -> None:
        """Shrink by different amounts in the x- and y-direction."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx = BoundingBox(llx, urx, lly, ury)
        bbx = bbx.shrink((2, 3))
        assert bbx.llx == llx + 2
        assert bbx.urx == urx - 2
        assert bbx.lly == lly + 3
        assert bbx.ury == ury - 3

    def test_overshrink(self) -> None:
        """Shrinking stops at the center of the box if it becomes too small."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx1 = BoundingBox(llx, urx, lly, ury)
        bbx2 = bbx1.shrink(100)
        assert bbx2.llx == bbx1.get_center()[0]
        assert bbx2.urx == bbx1.get_center()[0]
        assert bbx2.lly == bbx1.get_center()[1]
        assert bbx2.ury == bbx1.get_center()[1]

    def test_grow(self) -> None:
        """Grow in one direction (and overshrink in the other)."""
        (llx, urx, lly, ury) = (-46, 2, -15, 9)
        bbx1 = BoundingBox(llx, urx, lly, ury)
        bbx2 = bbx1.shrink((-5, 100))
        assert bbx2.llx == llx - 5
        assert bbx2.urx == urx + 5
        assert bbx2.lly == bbx1.get_center()[1]
        assert bbx2.ury == bbx1.get_center()[1]


from typing import TYPE_CHECKING, Dict, Optional

from snapcraft_legacy import formatting_utils
from snapcraft_legacy.internal import common, steps

if TYPE_CHECKING:
    from snapcraft_legacy.project import Project

    from . import PluginHandler

def get_snapcraft_global_environment(
    project: "Project", include_prime: bool = True
) -> Dict[str, str]:
    """
    Return a global environment for a part.

    include_prime defaults to True for behaviour not to change when using
    core and core18 bases.

    :param Project project: the Snapcraft project instance.
    :param bool include_prime: whether to include the prime directory in
                               the results.
    :returns: a dictionary with environment variables to apply.
    :rtype: dict
    """
    # The triple check is mostly for unit tests support until we completely
    # get rid of project.info.
    if project._snap_meta.name:
        name = project._snap_meta.name
    elif project.info is not None and project.info.name:
        name = project.info.name
    else:
        name = ""

    if project._snap_meta.version:
        version = project._snap_meta.version
    elif project.info is not None and project.info.version:
        version = project.info.version
    else:
        version = ""

    if project._snap_meta.grade:
        grade = project._snap_meta.grade
    elif project.info is not None and project.info.grade:
        grade = project.info.grade
    else:
        grade = ""

    content_dirs = project._get_provider_content_dirs()
    if content_dirs:
        content_dirs_envvar = formatting_utils.combine_paths(
            content_dirs, prepend="", separator=":"
        )
    else:
        content_dirs_envvar = ""

    return {
        "SNAPCRAFT_ARCH_BUILD_FOR": project.arch_build_for,
        "SNAPCRAFT_ARCH_BUILD_ON": project.arch_build_on,
        "SNAPCRAFT_ARCH_TRIPLET_BUILD_FOR": project.arch_triplet_build_for,
        "SNAPCRAFT_ARCH_TRIPLET_BUILD_ON": project.arch_triplet_build_on,
        "SNAPCRAFT_ARCH_TRIPLET": project.arch_triplet,
        "SNAPCRAFT_EXTENSIONS_DIR": common.get_extensionsdir(),
        "SNAPCRAFT_PARALLEL_BUILD_COUNT": str(project.parallel_build_count),
        "SNAPCRAFT_PRIME": project.prime_dir,
        "SNAPCRAFT_PROJECT_NAME": name,
        "SNAPCRAFT_PROJECT_VERSION": version,
        "SNAPCRAFT_PROJECT_DIR": project._project_dir,
        "SNAPCRAFT_PROJECT_GRADE": grade,
        "SNAPCRAFT_STAGE": project.stage_dir,
        "SNAPCRAFT_TARGET_ARCH": project.target_arch,
        "SNAPCRAFT_CONTENT_DIRS": content_dirs_envvar,
    }

def get_snapcraft_part_directory_environment(
    part: "PluginHandler", *, step: Optional[steps.Step] = None
) -> Dict[str, str]:
    env = {
        "SNAPCRAFT_PART_SRC": part.part_source_dir,
        "SNAPCRAFT_PART_SRC_WORK": part.part_source_work_dir,
    }

    if step is None or step == steps.BUILD:
        env.update(
            {
                "SNAPCRAFT_PART_BUILD": part.part_build_dir,
                "SNAPCRAFT_PART_BUILD_WORK": part.part_build_work_dir,
                "SNAPCRAFT_PART_INSTALL": part.part_install_dir,
            }
        )

    return env

def get_snapcraft_part_environment(
    part: "PluginHandler", *, step: steps.Step
) -> Dict[str, str]:
    """Return Snapcraft provided part environment."""
    part_environment = get_snapcraft_global_environment(
        part._project, include_prime=step == steps.PRIME
    )
    part_environment.update(get_snapcraft_part_directory_environment(part, step=step))

    paths = [part.part_install_dir, part._project.stage_dir]

    bin_paths = list()
    for path in paths:
        bin_paths.extend(common.get_bin_paths(root=path, existing_only=True))

    if bin_paths:
        bin_paths.append("$PATH")
        part_environment["PATH"] = formatting_utils.combine_paths(
            paths=bin_paths, prepend="", separator=":"
        )

    include_paths = list()
    for path in paths:
        include_paths.extend(common.get_include_paths(path, part._project.arch_triplet))

    if include_paths:
        for envvar in ["CPPFLAGS", "CFLAGS", "CXXFLAGS"]:
            part_environment[envvar] = formatting_utils.combine_paths(
                paths=include_paths, prepend="-isystem", separator=" "
            )

    library_paths = list()
    for path in paths:
        library_paths.extend(common.get_library_paths(path, part._project.arch_triplet))

    if library_paths:
        part_environment["LDFLAGS"] = formatting_utils.combine_paths(
            paths=library_paths, prepend="-L", separator=" "
        )

    pkg_config_paths = common.get_pkg_config_paths(path, part._project.arch_triplet)
    if pkg_config_paths:
        part_environment["PKG_CONFIG_PATH"] = formatting_utils.combine_paths(
            pkg_config_paths, prepend="", separator=":"
        )

    return part_environment


from distutils.core import setup
import os
from setuptools import setup

version = open('VERSION.txt').read()

setup(
    name='xml-parser',
    version=version,
    license='MIT',
    description='Parse MySQL XML datadump',
    author='John Nguyen',
    author_email='jolnguyen@ucdavis.edu',
    url='https://github.com/JohnlNguyen/xml-parser',
    packages=['parse'],
    zip_safe=False,
)


#!/usr/bin/env python
# pylint: disable=W0613
# type: ignore[union-attr]
# This program is dedicated to the public domain under the CC0 license.

import html
import json
import logging
import logging.config
import traceback
import os
import configparser

from firebase import firebase
from telegram import Update, ParseMode, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove, ReplyKeyboardMarkup
from telegram.ext import Updater, CommandHandler, MessageHandler, RegexHandler, Filters, ConversationHandler, CallbackQueryHandler, CallbackContext
from pycoingecko import CoinGeckoAPI

from pyfunction import *

config = configparser.ConfigParser()
config.read('config.ini')

# Firebase Database setting
# TOKEN = config['bot_dev']['TOKEN']
# DBLINK = config['bot_dev']['DBLINK']

TOKEN = os.environ["TOKEN"]
DBLINK = os.environ["DBLINK"]
PORT = int(os.environ.get('PORT', 5000))

firebase = firebase.FirebaseApplication(DBLINK, None)
# '[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s','%m-%d %H:%M:%S'

# Enable logging
logging.basicConfig(
    format='[%(asctime)s] p%(process)s {%(pathname)s:%(lineno)d} %(levelname)s - %(message)s', level=logging.INFO, filename='./log/lampBotLog.log', filemode='w',
)
logger = logging.getLogger(__name__)

def start(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /start is issued."""
    print("start")
    keyboard = []
    chat_id = str(update.effective_chat.id)
    isDone = False
    _msg = ""
    dbRes = firebase.get('/'+str(chat_id)+'/Setting','')

    if dbRes:
        isDone = True

    else:
        isDone = False
        setting = {
            "KIDDING_MODE":True,
            "ICON_DISPLAY":"SQUARE",
            "LANG":"zh",
            "PHOTO1":"https://media.whatscap.com/0dd/34c/0dd34c70b56a7e7097744379a69f06f6674f45b8_b.jpg"
        }
        res = firebase.put('/'+chat_id, "Setting", setting)

    _msg = "個bot set 好左喇, 試下用 /help 教你點用啦"
    update.message.reply_text(_msg, parse_mode="HTML", disable_web_page_preview=True)

def functionSelect(update: Update, context: CallbackContext) -> None:
    query = update.callback_query
    query.answer()

    if query.data:
        listCoin(update, context)

    query.edit_message_text(text=f"Selected option: {query.data}")

def addCoin(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /addCoin is issued."""
    print("addCoin")
    resStr = ""
    reply_markup = ""
    keyboard = []
    chat_id = str(update.effective_chat.id)
    username = update.message.from_user.first_name
    userid = update.message.from_user.id

    context.user_data["triggerUserID"] = userid
    context.user_data["triggerUserName"] = username

    if len(context.args) == 1:
        """ Handling single add coin """
        coin = context.args[0].upper()
        chkCoinExist = firebase.get('/'+chat_id+'/coinsList/',coin)

        if chkCoinExist:
            """ If coin is exist """
            resStr += ('{}\n{}').format(genFriendlyMsg('addMsg'), coinBuySell(chat_id, coin, username, userid, 'buy', firebase))

        else:
            """ If coin is NOT exist """
            searchRes = searchCoinIDBySymbol(coin.lower())
            if len(searchRes) == 1:
                res = createNewCoinInDB(chat_id, searchRes[0], username, userid, firebase)
                resStr += res

            elif len(searchRes) > 1:
                print("B")
                tmp = []
                tmpStr = ""
                for dtl in searchRes:
                    print(dtl)
                    tmp.append(InlineKeyboardButton(dtl['name'], callback_data='add_'+dtl['id']))
                    tmpStr += "" + dtl['name'].capitalize() + "\n"

                keyboard.append(tmp)
                reply_markup = InlineKeyboardMarkup(keyboard)

                resStr += ('${} duplicate symbol found! Please select.\n').format(coin.upper())
                resStr += tmpStr

            else:
                toDB = {
                    "ReplyTitle":"",
                    "ID" : "",
                    "Symbol" : coin.upper(),
                    "Name" : "",
                    "Dapp" : "",
                    "Holders" : {userid : username}
                    # "Platform" : searchRes['asset_platform_id']
                }

                res = firebase.put('/'+chat_id+'/coinsList', coin.upper(),toDB)
                resStr = ('{}\n${}\nBut not listed on CoinGecko, so no price provided').format(genFriendlyMsg('addMsg'), coin.upper())

    elif len(context.args) > 1:
        """ Handling multiple add coin: igrone DApp, coin_id """
        resStr = "Not support multiple buy coin"

    elif len(context.args) == 0:
        """ Wrong format """
        resStr = "Please enter coin name after the command\nExample: /buy mdo"

    if reply_markup:
        update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True, reply_markup=reply_markup)
    else:
        update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def removeCoin(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /removeCoin is issued."""
    print('removeCoin')
    chat_id = str(update.effective_chat.id)
    username = update.message.from_user.first_name
    userid = update.message.from_user.id
    resStr = ""
    success = False
    fail = False

    successStr = ""
    failStr = ""

    if len(context.args) != 0:
        for arg in context.args:
            coin = arg.upper()
            result = firebase.get('/'+chat_id+'/coinsList/'+coin+'/Holders',userid)

            if result:
                # Found in List
                successStr += (", " if len(successStr) != 0 else "") + coinBuySell(chat_id, coin, username, userid, 'sell', firebase)
                success = True

            else:
                failStr += (", " if len(failStr) != 0 else "") + '$' + coin
                fail = True
    else:
        resStr = "Please enter coin name after the command\nExample: /sell mdo"

    if success:
        resStr += genFriendlyMsg('delMsg') + "\n" + successStr + "\n"

    if fail:
        resStr += genFriendlyMsg('noBuyMsg') + "\n" + failStr + "\n"

    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def listCoin(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /listCoin is issued."""
    print("listCoin")
    resStr = ""
    reply_markup = ""
    keyboard = []

    dbRes = firebase.get('/'+str(update.effective_chat.id)+'/coinsList','')
    if dbRes:
        resStr += ('呢個大戶Group有{}隻已登記既coin(s):\n').format(str(len(dbRes)))
        listArr = []

        for coin in dbRes:
            if 'Holders' in dbRes[coin]:
                listArr.append(InlineKeyboardButton('{} [{}]'.format(coin, str(len(dbRes[coin]['Holders']))), callback_data='/sh_{}'.format(coin)))

                if len(listArr) == 3:
                    keyboard.append(listArr)
                    listArr = []

        keyboard.append(listArr)
        reply_markup = InlineKeyboardMarkup(keyboard)

    else:
        resStr += '未有coin!\n請用/addcoin [coin name] 新增'

    if reply_markup:
        update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True, reply_markup=reply_markup)
    else:
        update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def showCoinHolder(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /showholder is issued."""
    print("showCoinHolder")
    coinID = (update.message.text.replace('/sh_', '').replace('@lamped_bot', '')).upper()
    chat_id = update.effective_chat.id

    resStr = showCoin(coinID, chat_id, firebase)
    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def handleReply(update: Update, context: CallbackContext) -> None:
    """Send a message when user no need to coin"""
    print("handleReply")
    chat_id = str(update.effective_chat.id)

    query = update.callback_query
    query.answer()
    userReply = query.data.split("_")

    action = userReply[0]
    coinID = userReply[1]

    if action == 'add':
        userid = context.user_data["triggerUserID"]
        username = context.user_data["triggerUserName"]

        searchRes = searchCoinByID(coinID.lower())
        if searchRes:
            res = createNewCoinInDB(chat_id, searchRes, username, userid, firebase)
            query.edit_message_text(res)

    elif action == '/sh':
        resStr = showCoin(coinID, chat_id, firebase)
        query.edit_message_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

    elif query.data == 'N':
        query.edit_message_text("Bye!")

def showSpecificUserList(update: Update, context: CallbackContext) -> None:
    """ handle show speicfic user """
    print("showSpecificUserList")

    coinArr = []
    coinPriceArr = []
    chat_id = str(update.effective_chat.id)
    userid = str(update.message.from_user.id)
    username = update.message.from_user.first_name

    update.message.reply_text("Load緊....", parse_mode="HTML", disable_web_page_preview=True)
    resStr = ""
    dbRes = firebase.get('/'+chat_id+'/coinsList','')
    if dbRes:
        resStr += ('{}持有既coins\n').format(username)
        for coin in dbRes:
            dbRes2 = firebase.get('/'+chat_id+'/coinsList/'+coin+'/Holders','')
            if dbRes2:
                for Holders in dbRes[coin]['Holders']:
                    if Holders == userid:
                        if dbRes[coin]['ID'] != '':
                            coinPriceArr.append(dbRes[coin]['ID'])
                            coinArr.append({"ID":dbRes[coin]['ID'], "Symbol":dbRes[coin]['Symbol'],  "Name":dbRes[coin]['Name'], "Dapp":dbRes[coin]['Dapp']})

                        else:
                            coinArr.append({"ID":"", "Symbol":dbRes[coin]['Symbol'], "Name":"", "Dapp":""})

        resStr += holdGetPrice(coinArr, coinPriceArr, 'hold', chat_id, firebase)

    else:
        resStr = '呢條友冇買過coins'

    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def alertCoinHolder(update: Update, context: CallbackContext) -> None:
    """ handle alert coin holder """
    print("alertCoinHolder")
    chat_id = str(update.effective_chat.id)
    username = update.message.from_user.first_name
    userid = update.message.from_user.id
    resStr = ""
    args = context.args

    if len(args) == 2:
        coin = args[0].upper()
        coinArr = []
        coinPriceArr = []
        dbRes = firebase.get('/'+chat_id+'/coinsList',coin)
        if dbRes:
            # Found in List
            if dbRes['ID'] != '':
                coinPriceArr.append(dbRes['ID'])
                coinArr.append({"ID":dbRes['ID'], "Symbol":dbRes['Symbol'],  "Name":dbRes['Name'], "Dapp":dbRes['Dapp']})
            else:
                coinArr.append({"ID":"", "Symbol":dbRes['Symbol'], "Name":"", "Dapp":""})

            resStr += holdGetPrice(coinArr, coinPriceArr, '', chat_id, firebase)
            resStr += args[1] + "\n"

            for Holder in dbRes['Holders']:
                resStr += "{} ".format(str(Holder), dbRes['Holders'][Holder])

        else:
            # Not found in List
            resStr = ('冇人有 ${} 呢隻幣\n').format(coin)
    else:
        resStr = "Wrong command format\nExample: /alert mdo 走鬼喇!"

    #
    if getBotSetting(chat_id, "PHOTO1", firebase):
        update.message.bot.send_photo(chat_id, getBotSetting(chat_id, "PHOTO1", firebase), resStr, parse_mode="HTML")
    else:
        update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def future(update: Update, context: CallbackContext) -> None:
    """Calculate Future"""
    print("future")
    chat_id = str(update.effective_chat.id)
    userid = update.message.from_user.id
    resStr = ""

    if len(context.args) == 4:
        side = ""
        p = float(context.args[0])
        loss = float(context.args[1])
        sp = float(context.args[2])
        sl = float(context.args[3])
        amount = (p*(loss/100))/(sp-sl)
        light = {'green':'\U0001F7E2', 'red':'\U0001F534'}

        if amount > 0:
            side = "Long"
            color = light['green']
        else:
            side = "Short"
            color = light['red']

        resStr = ("{} Position {}\n計算方式: (本金*可接受損失百份比)/(開倉價-止蝕價)\n\n你個情況: ({}*{})/({}-{})\n建議倉位: {}\n\n Remark:\n
倉位負數 = Short, 倉位正數 = Long
").format(side, color, p, str(loss)+"%", sp, sl, amount)
    else:
        resStr = "Formula:(本金*可接受損失百份比)/(開倉價-止蝕價) \n Format Error \n E.g. /future 1000 2 2250 2240"

    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

# TODO  Phase 2 - OTC Reminder
# TODO  Phase 3 - My coin list with Price
# TODO  Phase 4 - Set timer check wallet

# TODO Option - Setting
def setting(update: Update, context: CallbackContext) -> None:
    """Send a message for kidding."""
    print("setting")
    chat_id = str(update.effective_chat.id)
    userid = update.message.from_user.id
    resStr = ""

    if str(userid) == "622225198":
        if len(context.args) == 2:
            setting = context.args[0].upper()
            var = context.args[1].upper()
            updateBotSetting(chat_id, setting, var, firebase)
            resStr = "Setting Updated."
        else:
            resStr = "Available command. \n - Kidding_mode [on/off] \n - Icon_Display [circle/square] \n - Lang [en/zh]"

    else:
        resStr = "唔關你事"

    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def fixCoin(update: Update, context: CallbackContext) -> None:
    print("fixCoin")
    resStr = ""
    chat_id = str(update.effective_chat.id)
    dbRes = firebase.get('/'+str(chat_id)+'/coinsList','')
    username = update.message.from_user.first_name
    userid = update.message.from_user.id
    user = update.message.from_user.username
    count = 0
    fail_list = ""

    if str(userid) == "622225198":
        _res = []
        cg = CoinGeckoAPI()
        coinlist = cg.get_coins_list()
        if dbRes:
            for coin in dbRes:
                # Step 1: Replace username to userid
                try:
                    if dbRes[coin]['Holders']:
                        coinDtl = TMPsearchCoinIDBySymbol(coin.lower(), coinlist)
                        if len(coinDtl) == 1:
                            searchRes = searchCoinByID(coinDtl[0]['id'].lower())

                            firebase.put('/'+chat_id+'/coinsList/'+coin, "ReplyTitle", "")
                            firebase.put('/'+chat_id+'/coinsList/'+coin, "ID", searchRes['id'])
                            firebase.put('/'+chat_id+'/coinsList/'+coin, "Symbol", searchRes['symbol'])
                            firebase.put('/'+chat_id+'/coinsList/'+coin, "Name", searchRes['name'])
                            firebase.put('/'+chat_id+'/coinsList/'+coin, "Dapp", searchRes ['link'])

                            firebase.delete('/'+chat_id+'/coinsList/'+coin, 'id')
                        else:
                            fail_list += (", " if len(fail_list) != 0 else "") + coin

                except:
                    firebase.delete('/'+chat_id+'/coinsList',coin)

        resStr = "Completed, Please manual update the following: "+ fail_list

    else:
        resStr = "唔關 你事!"

    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

def fix(update: Update, context: CallbackContext) -> None:
    """Send a message for kidding."""
    print("fix")
    resStr = ""
    chat_id = str(update.effective_chat.id)
    dbRes = firebase.get('/'+str(chat_id)+'/coinsList','')
    username = update.message.from_user.first_name
    userid = update.message.from_user.id
    user = update.message.from_user.username

    _res = []
    cg = CoinGeckoAPI()
    coinlist = cg.get_coins_list()
    # print(coinlist)

    if dbRes:
        for coin in dbRes:
            # Step 1: Replace username to userid
            try:
                for Holders in dbRes[coin]['Holders']:
                    if Holders == user:
                        resStr += coinBuySell(chat_id, coin, user, user, 'sell', firebase)
                        resStr += coinBuySell(chat_id, coin, user, userid, 'buy', firebase)

            except:
                firebase.delete('/'+chat_id+'/coinsList',coin)

    update.message.reply_text("[Update] UserID Completed", parse_mode="HTML", disable_web_page_preview=True)

def help_command(update: Update, context: CallbackContext) -> None:
    """Send a message when the command /help is issued."""
    update.effective_message.reply_html(
        f'/buy COIN_NAME = 加幣入你個portfolio\n'
        f'/sell COIN_NAME = 係你個portfolio到Remove隻幣\n'
        f'/hold = 睇自己portfolio持有咩幣\n'
        f'/coinlist = 睇成group持有咩幣\n'
        f'/note COIN_NAME MESSAGE = Message + Tag有呢隻既谷友\n\n'
        f'Remark:\n'
        f'1. /sell 可以支援同時幾隻幣\n'
        f'2. 使用 /buy 加幣果陣, 如果係CoinGecko 搵唔到呢隻幣, 會照加入去你個portfolio到, 但用 /hold 果陣就唔會show幣價\n'
    )

def kidding(update: Update, context: CallbackContext) -> None:
    """Send a message for kidding."""
    print("kidding")
    update.message.reply_text("dnlm", parse_mode="HTML", disable_web_page_preview=True)

def error(update: Update, context: CallbackContext):
    """Log Errors caused by Updates."""
    resStr = "Something wrong. {}\n#Error".format(622225198, 'Ringo (Lampgo)')
    update.message.reply_text(resStr, parse_mode="HTML", disable_web_page_preview=True)

    logger.warning('Update "%s" caused error "%s"', update, context.error)

def main():
    """Start the bot."""
    expression = '((http|https)\:\/\/)?[a-zA-Z0-9\.\/\?\:@\-_=#]+\.([a-zA-Z]){2,6}([a-zA-Z0-9\.\&\/\?\:@\-_=#])*'
    updater = Updater(TOKEN, use_context=True)
    dispatcher = updater.dispatcher

    ## Call the BOT
    dispatcher.add_handler(CommandHandler("start", start))
    dispatcher.add_handler(MessageHandler(Filters.text("dnlm"), kidding))

    ## Handle Add coins
    dispatcher.add_handler(CommandHandler("buy", addCoin))
    dispatcher.add_handler(CallbackQueryHandler(handleReply))

    ## Handle Remove coins
    dispatcher.add_handler(CommandHandler("sell", removeCoin))

    ## Handle Show coin list
    dispatcher.add_handler(CommandHandler("coinlist", listCoin))
    dispatcher.add_handler(MessageHandler(Filters.regex(r'^(/sh_[a-zA-Z0-9\.\/\?\:@\-_=#]+)$'), showCoinHolder))
    dispatcher.add_handler(CommandHandler("hold", showSpecificUserList))
    dispatcher.add_handler(CommandHandler("hodl", showSpecificUserList))
    dispatcher.add_handler(CommandHandler("note", alertCoinHolder))

    ## Others
    dispatcher.add_handler(CommandHandler("set", setting))
    dispatcher.add_handler(CommandHandler("future", future))
    dispatcher.add_handler(CommandHandler("help", help_command))

    dispatcher.add_handler(CommandHandler("fix", fix))
    dispatcher.add_handler(CommandHandler("fixCoin", fixCoin))

    # log all errors
    dispatcher.add_error_handler(error)

    # Start the Bot
    # Testing
    # updater.start_polling()

    # Production
    updater.start_webhook(listen="0.0.0.0",
                        port=int(PORT),
                        url_path=TOKEN)
    updater.bot.setWebhook('https://lampedbot.herokuapp.com/' + TOKEN)
    updater.idle()

if __name__ == '__main__':
    main()


'''
    func:爬取知乎每日最热话题
    date:2018/11/15
    author:monty
'''
from bs4 import BeautifulSoup as bs
import requests
import lxml
from pyquery import PyQuery as pq

def getPage(url):
    headers={
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36',
    }

    response=requests.get(url,headers=headers)
    return response.text

def pageparse(html):
    soup=bs(html,'lxml')
    result=soup.select('.explore-feed')
    rs=[]
    for i in result:
        r={}
        r['title']=i.find('h2').text.strip()
        r['click']=i.select('.zm-item-vote')[0].text.strip()
        r['author']=i.select('.author-link-line')[0].text.strip()
        r['authorurl']="https://www.zhihu.com"+i.select('span a')[0].attrs['href']
        doc=pq(i.select('.content')[0].text)
        doc.remove('a')
        r['content']=doc.text().strip()
        rs.append(r)
    return rs
def save(items,filename):
    file=open(filename,'a',encoding='utf-8')
    for item in items:
        file.write(item['title']+"\n作者："+item['author']+"\t"*2+"作者联系方式:"+item['authorurl']+"\t"*2+"点赞数："+item['click']+"\n"+item['content'])
        file.write("\n"+"="*120+"\n\n\n")
    file.close()
if __name__=="__main__":
    url='https://www.zhihu.com/explore'
    html=getPage(url)
    rs=pageparse(html)
    save(rs,'zhihu.txt')


# Machine Learning Program 2

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import KFold
from matplotlib.backends.backend_pdf import PdfPages
from sklearn.preprocessing import MinMaxScaler, StandardScaler
from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score

def sigF(z):
    return 1.0 / (1.0 + np.exp(-z))

def ypred(x_test, weights):
    # x_test = np.c_[np.ones(x_test.shape[0]), x_test]
    ypred = x_test.dot(weights)
    return ypred

def plotS(Averages, title, range, yticks, xticks, ylabel, xlabel):
    fig = plt.figure(figsize=(8, 10), dpi=100)
    plt.title(title)
    plt.bar(range, Averages, 0.35)
    plt.yticks(yticks)
    plt.xticks(x, xticks, rotation='vertical')
    plt.ylabel(ylabel)
    plt.xlabel(xlabel)
    plt.show()
    return fig

# tolerance conversion: takes the Ypredicted value and uses the sigmoid function to return a value between
# 0 and 1.  anything below .5 is a 0 anything above is a 1.  Replace in ypred

def tolconv(ypred, tol):
    for index, item in enumerate(ypred):
        s = sigF(item)
        if s >= tol:
            ypred[index] = 1
        elif s < tol:
            ypred[index] = 0
    return ypred

# calculate the accuracy precision recall and F1 and prints to a file
# Kfold prints each iteration of the loop with a final average from the Kfold.
# 50/50 prints the scores

def avgmetrics(metrics, k, atmetrics):
    sumaccuracy = 0
    sumprecision = 0
    sumrecall = 0
    sumfone = 0
    iter = 1
    # holds the performance Average of Kfold and performance of 50/50
    performance = []
    if k > 1:
        f.write('K\tAccuracy\tPrecision\tRecall\tF1 \n')
    for i in metrics:
        if k > 1:
            f.write('{:d}'.format(iter))
            f.write('\t{:.3f}'.format(i[0]))
            f.write('\t\t{:.3f}'.format(i[1]))
            f.write('\t\t{:.3f}'.format(i[2]))
            f.write('\t\t{:.3f}\n'.format(i[3]))
        sumaccuracy += i[0]
        sumprecision += i[1]
        sumrecall += i[2]
        sumfone += i[3]
        iter += 1
    if k > 1:
        f.write('\nKfolds Averages\n')
        f.write('Accuracy\tPercision\tRecall\tF1 \n')
        f.write('{:.3f}'.format((sumaccuracy / k)))
        performance.append((sumaccuracy / k))
        f.write('\t\t{: .3f}'.format((sumprecision / k)))
        performance.append((sumprecision / k))
        f.write('\t{: .3f}'.format((sumrecall / k)))
        performance.append((sumrecall / k))
        f.write('\t{: .3f}\n\n'.format((sumfone / k)))
        performance.append((sumfone / k))
    else:
        f.write('Accuracy\tPercision\tRecall\tF1 \n')
        for i in metrics:
            f.write('{:.3f}'.format(i[0]))
            performance.append(i[0])
            f.write('\t\t{: .3f}'.format(i[1]))
            performance.append(i[1])
            f.write('\t{: .3f}'.format(i[2]))
            performance.append(i[2])
            f.write('\t{: .3f}\n\n'.format(i[3]))
            performance.append(i[3])
    # atmetrics holds the performance values from each run to be compared later in a datatable.
    atmetrics.append(performance)
    return

# calculate the Batch Gradient Decent
# alpha = learning rate '0.1, 0.01, 0.001' | nepoch = iterations

def BatchGD(alpha, x, y, nepoch):
    m = x.shape[0]  # number of samples
    theta = np.random.uniform(size=x.shape[1])
    for iter in range(0, nepoch):
        hypothesis = sigF(x.dot(theta))
        error = hypothesis - y
        # J = np.sum(error ** 2) / (2 * m)
        # print("iter %s | J: %.3f" % (iter+1, J))
        gradient = np.dot(x.T, error) / m
        theta = theta - (alpha*gradient)  # update the theta for for next loop
    return theta

def regBatchGD(alpha, x, y, nepoch, lam):
    m = x.shape[0]  # number of samples
    theta = np.random.uniform(size=x.shape[1])
    for iter in range(0, nepoch):
        hypothesis = sigF(x.dot(theta))
        error = hypothesis - y
        # J = np.sum(error ** 2) / (2 * m)
        # print("iter %s | J: %.3f" % (iter+1, J))
        gradient = np.dot(x.T, error)
        theta = theta - (alpha * gradient + (lam/m)*theta)  # update the theta for for next loop
    return theta

def REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, alpha, nepoch, k, atmetrics, lam):
    kf = KFold(n_splits=k)
    metrics = []
    metricssplit = []
    for train_index, test_index in kf.split(dftrain_x):
        # print('train: ', train_index, 'test: ', test_index)
        X_train, X_test = dftrain_x[train_index], dftrain_x[test_index]
        Y_train, Y_test = dftrain_y[train_index], dftrain_y[test_index]
        thetas = regBatchGD(alpha, X_train, Y_train, nepoch, lam)
        y_pred = np.dot(X_test, thetas)
        y_pred = tolconv(y_pred, 0.50)
        # cm = confusion_matrix(Y_test, y_pred)
        #metrics.append(metricscores(cm))
        metrics.append(metricscores(Y_test, y_pred))
    f.write('KFolds cross-validation, K ={:d} alpha={:.4f} nepoch={:d}\n'.format(k, alpha, nepoch))
    avgmetrics(metrics, k, atmetrics)

    # 50% train vs 50% test data sets.
    f.write('50% Train 50% test metrics, alpha={:.4f} nepoch={:d}\n'.format(alpha, nepoch))
    thetas = regBatchGD(alpha, dftrain_x, dftrain_y, nepoch, lam)
    y_pred = np.dot(dftest_x, thetas)
    y_pred = tolconv(y_pred, 0.50)
    # cm = confusion_matrix(dftest_y, y_pred)
    metricssplit.append(metricscores(dftest_y, y_pred))
    k = 1
    avgmetrics(metricssplit, k, atmetrics)
    return

def dataaverages(metrics, averages, precision, recall, fone):
    a_sum = 0
    p_sum = 0
    r_sum = 0
    f_sum = 0
    count = 0
    for index, item in enumerate(metrics):
        a_sum += item[0]
        p_sum += item[1]
        r_sum += item[2]
        f_sum += item[3]
        count += 1
    averages.append(a_sum / count)
    precision.append(p_sum / count)
    recall.append(r_sum / count)
    fone.append(f_sum / count)
    return
# calculate the metric scores accuracy precision recall F1

def metricscores(y_test, y_pred):
    scores = []
    # TN=cm00 | FN=cm10 | TP=cm11 | FP=cm01
    # accuracy (TP+TN) / (TP+TN+FP+FN)
    # accuracy = (cm[0][0] + cm[1][1]) / (cm[0][0] + cm[1][1] + cm[0][1] + cm[1][0])
    accuracy = accuracy_score(y_test, y_pred)
    scores.append(accuracy)
    # precision (TP) / (TP +FP)
    # if (cm[1][1] + cm[0][1]) == 0:
    #     precision = 1
    # else:
    #     precision = (cm[1][1]) / (cm[1][1] + cm[0][1])
    precision = precision_score(y_test, y_pred)
    scores.append(precision)
    # recall (TP) / (TP + FN)
    # if (cm[1][1] + cm[1][0]) == 0:
    #     recall = 1
    # else:
    #     recall = (cm[1][1]) / (cm[1][1] + cm[1][0])
    recall = recall_score(y_test, y_pred)
    scores.append(recall)
    # f1 2 * (precision * recall) / (precision + recall)
    # if (precision + recall) == 0:
    #     fone = 1
    # fone = 2 * (precision * recall) / (precision + recall)
    fone = f1_score(y_test, y_pred)
    # if the result of fone is nan due to division by zero
    scores.append(fone)
    # print('Confusion Matrix F1: {:.2f}'.format(fone))
    return scores

# Do logistic Regression with the set of perams

def doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, alpha, nepoch, k, atmetrics):
    kf = KFold(n_splits=k)
    metrics = []
    metricssplit = []
    for train_index, test_index in kf.split(dftrain_x):
        # print('train: ', train_index, 'test: ', test_index)
        X_train, X_test = dftrain_x[train_index], dftrain_x[test_index]
        Y_train, Y_test = dftrain_y[train_index], dftrain_y[test_index]
        thetas = BatchGD(alpha, X_train, Y_train, nepoch)
        y_pred = np.dot(X_test, thetas)
        y_pred = tolconv(y_pred, 0.50)
        # cm = confusion_matrix(Y_test, y_pred)
        #metrics.append(metricscores(cm))
        metrics.append(metricscores(Y_test, y_pred))
    f.write('KFolds cross-validation, K ={:d} alpha={:.4f} nepoch={:d}\n'.format(k, alpha, nepoch))
    avgmetrics(metrics, k, atmetrics)

    # 50% train vs 50% test data sets.
    f.write('50% Train 50% test metrics, alpha={:.4f} nepoch={:d}\n'.format(alpha, nepoch))
    thetas = BatchGD(alpha, dftrain_x, dftrain_y, nepoch)
    y_pred = np.dot(dftest_x, thetas)
    y_pred = tolconv(y_pred, 0.50)
    # cm = confusion_matrix(dftest_y, y_pred)
    metricssplit.append(metricscores(dftest_y, y_pred))
    k = 1
    avgmetrics(metricssplit, k, atmetrics)
    return

if __name__ == '__main__':
    f = open('report.doc', 'w')
    pp = PdfPages('myplots.pdf')
    dftrain = pd.read_csv('bank-small-train.csv', sep=';')
    dftest = pd.read_csv('bank-small-test.csv', sep=';')
    for column in dftrain:
        if dftrain[column].dtypes == object:
            dftrain[column] = dftrain[column].astype('category')
            dftrain[column] = dftrain[column].cat.codes
            dftrain[column] = dftrain[column].astype(np.int64)

    for column in dftest:
        if dftest[column].dtypes == object:
            dftest[column] = dftest[column].astype('category')
            dftest[column] = dftest[column].cat.codes
            dftest[column] = dftest[column].astype(np.int64)

    dftrain_x = dftrain.iloc[:, :-1].values
    dftrain_x = np.c_[np.ones(dftrain_x.shape[0]), dftrain_x]
    dftrain_y = dftrain.iloc[:, -1].values

    dftest_x = dftest.iloc[:, :-1].values
    dftest_x = np.c_[np.ones(dftest_x.shape[0]), dftest_x]
    dftest_y = dftest.iloc[:, -1].values

    atmetrics = []
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, atmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, atmetrics)
    # create a datafram with the performance of the above runs and export to csv file
    df = pd.DataFrame(atmetrics)
    df.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    new_col = ['Kfold 0.1, 100', '0.1, 100', 'Kfold 0.01, 100', '0.01, 100', 'Kfold 0.001, 100', '0.001, 100',
               'Kfold 0.1, 500', '0.1, 500', 'Kfold 0.01, 500', '0.01, 500', 'Kfold 0.001, 500', '0.001, 500',
               'Kfold 0.1, 1000', '0.1, 1000', 'Kfold 0.01, 1000', '0.01, 1000', 'Kfold 0.001, 1000', '0.001, 1000']
    df.insert(loc=0, column='Alpha, nepoch', value=new_col)
# *************************************************************************************
# Min max
    f.write('Min-Max scaling results\n')
    dftrain_x = dftrain.iloc[:, :-1].values
    dftrain_y = dftrain.iloc[:, -1].values
    dftest_x = dftest.iloc[:, :-1].values
    dftest_y = dftest.iloc[:, -1].values

    scaler = MinMaxScaler()
    scaler.fit(dftrain_x)
    MinMaxScaler(copy=True, feature_range=(0, 1))
    dftrain_x = scaler.transform(dftrain_x)
    dftrain_x = np.c_[np.ones(dftrain_x.shape[0]), dftrain_x]

    scaler.fit(dftest_x)
    MinMaxScaler(copy=True, feature_range=(0, 1))
    dftest_x = scaler.transform(dftest_x)
    dftest_x = np.c_[np.ones(dftest_x.shape[0]), dftest_x]

    btmetrics = []
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, btmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, btmetrics)
    # create a datafram with the performance of the above runs and export to csv file
    df1 = pd.Series([], name='Min-Max')
    df2 = pd.DataFrame(btmetrics)
    df2.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df2.insert(loc=0, column='Alpha, nepoch', value=new_col)

# ***********************************************************************
# Standardization
    f.write('Standardization results\n')
    dftrain_x = dftrain.iloc[:, :-1].values
    dftrain_y = dftrain.iloc[:, -1].values
    dftest_x = dftest.iloc[:, :-1].values
    dftest_y = dftest.iloc[:, -1].values

    scaler = StandardScaler()

    dftrain_x = scaler.fit_transform(dftrain_x)
    dftrain_x = np.c_[np.ones(dftrain_x.shape[0]), dftrain_x]

    dftest_x = scaler.fit_transform(dftest_x)
    dftest_x = np.c_[np.ones(dftest_x.shape[0]), dftest_x]

    ctmetrics = []
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, ctmetrics)
    doregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, ctmetrics)
    # create a datafram with the performance of the above runs and export to csv file
    df3 = pd.Series([], name='Standardization')
    df4 = pd.DataFrame(ctmetrics)
    df4.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df4.insert(loc=0, column='Alpha, nepoch', value=new_col)

# *********************************************************************
# Regularized logistic regression with Standarization Xtrain Xtest lambda = 0
    f.write('Regularized Logistic Regression with Standardization data: Lambda = 0 \n')
    dtmetrics = []
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, dtmetrics, lam=0)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, dtmetrics, lam=0)
    df5 = pd.Series([], name='Regularized LG, Lambda=0')
    df6 = pd.DataFrame(dtmetrics)
    df6.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df6.insert(loc=0, column='Alpha, nepoch', value=new_col)
# ***************************************************
# lambda = 1
    f.write('Regularized Logistic Regression with Standardization data: Lambda = 1 \n')
    etmetrics = []
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, etmetrics, lam=1)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, etmetrics, lam=1)
    df7 = pd.Series([], name='Regularized LG, Lambda=1')
    df8 = pd.DataFrame(etmetrics)
    df8.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df8.insert(loc=0, column='Alpha, nepoch', value=new_col)
#************************************************************
# lambda = 10
    f.write('Regularized Logistic Regression with Standardization data: Lambda = 10 \n')
    ftmetrics = []
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, ftmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, ftmetrics, lam=10)
    df9 = pd.Series([], name='Regularized LG, Lambda=10')
    df10 = pd.DataFrame(ftmetrics)
    df10.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df10.insert(loc=0, column='Alpha, nepoch', value=new_col)
#***************************************************************
# lambda = 100
    f.write('Regularized Logistic Regression with Standardization data: Lambda = 100 \n')
    gtmetrics = []
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, gtmetrics, lam=10)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, gtmetrics, lam=100)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, gtmetrics, lam=100)
    df11 = pd.Series([], name='Regularized LG, Lambda=100')
    df12 = pd.DataFrame(gtmetrics)
    df12.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df12.insert(loc=0, column='Alpha, nepoch', value=new_col)
# ************************************************************
# lambda = 1000
    f.write('Regularized Logistic Regression with Standardization data: Lambda = 1000 \n')
    htmetrics = []
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 100, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 100, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 100, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 500, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 500, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 500, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.1, 1000, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.01, 1000, 10, htmetrics, lam=1000)
    REGdoregression(dftrain_x, dftrain_y, dftest_x, dftest_y, 0.001, 1000, 10, htmetrics, lam=1000)
    df13 = pd.Series([], name='Regularized LG, Lambda=1000')
    df14 = pd.DataFrame(htmetrics)
    df14.columns = ['Accuracy', 'Percision', 'Recall', 'F1']
    df14.insert(loc=0, column='Alpha, nepoch', value=new_col)
    result = pd.concat([df, df1, df2, df3, df4, df5, df6, df7, df8, df9, df10, df11, df12, df13, df14], axis=1)
# ***************************************************
# Plot Accuracy Averages from each set
    Averages = []
    Precision = []
    Recall = []
    FOne = []
    dataaverages(atmetrics, Averages, Precision, Recall, FOne)
    dataaverages(btmetrics, Averages, Precision, Recall, FOne)
    dataaverages(ctmetrics, Averages, Precision, Recall, FOne)
    dataaverages(dtmetrics, Averages, Precision, Recall, FOne)
    dataaverages(etmetrics, Averages, Precision, Recall, FOne)
    dataaverages(ftmetrics, Averages, Precision, Recall, FOne)
    dataaverages(gtmetrics, Averages, Precision, Recall, FOne)
    dataaverages(htmetrics, Averages, Precision, Recall, FOne)
    x = np.arange(8)
    title = 'Accuracy Performance Averages'
    yticks = np.arange(0, 1, 0.05)
    ylabel = 'Performance'
    xlabel = 'Params'
    xticks = ['Pure', 'MinMax', 'Standardized', 'Regularized', 'Lambda0', 'Lambda1', 'Lambda10', 'Lambda100', 'Lambda1000']
    plot1 = plotS(Averages, title, x, yticks, xticks, ylabel, xlabel)
    title = 'Precision Performance Averages'
    yticks = np.arange(0, 0.50, 0.02)
    plot2 = plotS(Precision, title, x, yticks, xticks, ylabel, xlabel)
    title = 'Recall Performance Averages'
    plot3 = plotS(Recall, title, x, yticks, xticks, ylabel, xlabel)
    title = 'F1 Performance Averages'
    plot4 = plotS(FOne, title, x, yticks, xticks, ylabel, xlabel)
    pp.savefig(plot1)
    pp.savefig(plot2)
    pp.savefig(plot3)
    pp.savefig(plot4)
    result.to_csv('Table.csv', sep=',')
    pp.close()
    f.close()


import sys # Allows us to know about the state of the OS
print(sys.path[0])

import re # Regular expressions
text = "My phone number is 555 555555, country code is 55 and my lucky number is also 5"
result = re.findall("[0-9]+", text) # Find every number in the string.
print(result)

import time # Date and time
timestamp = time.time() # Time in Unix format
print(timestamp)

local = time.localtime() # Local time
result = time.asctime(local) # Formats the date
print(result)

import collections # Mainly for managing lists
numbers = [1, 1, 2, 1, 2, 1, 4, 5, 3, 3, 21]
counter = collections.Counter(numbers) # Creates a dictionary with the frecuency of each number
print(counter)


import sys
sys.path.append('/Users/davidblanco/Documents/personal/Advent_of_Code_2021')
from utils.tools import input_parser, current_stars
from functools import reduce
import math

def solution(array, part=1, current_value=0, last_sum=math.inf):
    cost = summ_of_diffs(array, current_value, part)
    return solution(array, part, current_value+1, last_sum=cost) if cost < last_sum else last_sum

def summ_of_diffs(array, val, part=1):
    if part==2:
        return reduce(lambda a,b: a+b, map(lambda b: + factorial_summ(abs(b - val)), array))
    return reduce(lambda a,b: a+b, map(lambda b: + abs(b - val), array))

def factorial_summ(n):
    return reduce(lambda a,b: a+b, range(n+1))

if __name__ == '__main__':

    ex = [16,1,2,0,4,2,7,1,2,14]
    input_7 = input_parser(day=7, t="intlist")
    print(f"Example Part 1: {solution(ex)}")
    print(f"Example Part 2: {solution(ex, part=2)}")
    print(f"Solution Part 1: {solution(input_7)}")
    print(f"Solution Part 2: {solution(input_7, part=2)}")
    print(current_stars())


import cv2
import glob
from matplotlib import pyplot as plt

def substImage(path):
    img_src1 = cv2.imread("../SubstImage.jpg", 1)
    img_src2 = cv2.imread(path, 1)

    fgbg = cv2.bgsegm.createBackgroundSubtractorMOG()

    fgmask = fgbg.apply(img_src1)
    fgmask = fgbg.apply(img_src2)

    return fgmask

def binaryCvt(path,thresh):
	image = cv2.imread(path,1)
	gray  = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY)

	ret, binary =cv2.threshold(gray,thresh,255,cv2.THRESH_BINARY)
	# ret, binary =cv2.threshold(gray,thresh,1,cv2.THRESH_OTSU)

	return binary
	# return gray

def cutLamp(binary):
	pWork={
     	'y1':75, 'y2':95,
        'x1':345,'x2':365}
	pPump={
     	'y1'    :175,'y2'    :195,
        '1offx1':330,'1offx2':350,
        '1onx1' :360,'1onx2' :380,
        '2offx1':385,'2offx2':405,
        '2onx1' :410,'2onx2' :430}
	pTanks={
		'fully1':250,"fully2":270,
		"lowy1" :275,'lowy2' :300,
		"Hx1"   :345,'Hx2'   :365,
		'Lx1'	:400,'Lx2'	 :420}

	# print(pWork,pPump,pTanks)

	working=binary[pWork['y1']:pWork['y2'],pWork['x1']	  :pWork['x2']]
	no1_off=binary[pPump['y1']:pPump['y2'],pPump['1offx1']:pPump['1offx2']]
	no1_on =binary[pPump['y1']:pPump['y2'],pPump['1onx1'] :pPump['1onx2'] ]
	no2_off=binary[pPump['y1']:pPump['y2'],pPump['2offx1']:pPump['2offx2']]
	no2_on =binary[pPump['y1']:pPump['y2'],pPump['2onx1'] :pPump['2onx2'] ]
	H_full =binary[pTanks['fully1']:pTanks['fully2'],pTanks['Hx1']:pTanks['Hx2']]
	H_low  =binary[pTanks['lowy1'] :pTanks['lowy2'], pTanks['Hx1']:pTanks['Hx2']]
	L_full =binary[pTanks['fully1']:pTanks['fully2'],pTanks['Lx1']:pTanks['Lx2']]
	L_low  =binary[pTanks['lowy1'] :pTanks['lowy2'], pTanks['Lx1']:pTanks['Lx2']]

	cv2.rectangle(binary,(pWork['x1'],pWork['y1']),(pWork['x2'],pWork['y2']),230,1)
	cv2.rectangle(binary,(pPump['1offx1'],pPump['y1']),(pPump['1offx2'],pPump['y2']),230,1)
	cv2.rectangle(binary,(pPump['1onx1'] ,pPump['y1']),(pPump['1onx2'] ,pPump['y2']),230,1)
	cv2.rectangle(binary,(pPump['2offx1'],pPump['y1']),(pPump['2offx2'],pPump['y2']),230,1)
	cv2.rectangle(binary,(pPump['2onx1'] ,pPump['y1']),(pPump['2onx2'] ,pPump['y2']),230,1)
	cv2.rectangle(binary,(pTanks['Hx1'],pTanks['fully1']),(pTanks['Hx2'],pTanks['fully2']),230,1)
	cv2.rectangle(binary,(pTanks['Hx1'],pTanks['lowy1'] ),(pTanks['Hx2'],pTanks['lowy2'] ),230,1)
	cv2.rectangle(binary,(pTanks['Lx1'],pTanks['fully1']),(pTanks['Lx2'],pTanks['fully2']),230,1)
	cv2.rectangle(binary,(pTanks['Lx1'],pTanks['lowy1'] ),(pTanks['Lx2'],pTanks['lowy2'] ),230,1)

	return [working,no1_off,no1_on,no2_off,no2_on,H_full,H_low,L_full,L_low],binary

def calcBW(bw_image,percent):
  image_size = bw_image.size
  whitePixels = cv2.countNonZero(bw_image)
  blackPixels = bw_image.size - whitePixels
  whiteAreaRatio = (whitePixels/image_size)*100#[%]
  blackAreaRatio = (blackPixels/image_size)*100#[%]
  print("White Area [%] : ", whiteAreaRatio)
  print("Black Area [%] : ", blackAreaRatio)
  if whiteAreaRatio > percent:
	  return '1'
  else:
	  return '0'

def draw(image):
	fig = plt.figure()
	ax1 = fig.add_subplot(111)
	ax1.imshow(binary, cmap = 'gray')
	ax1.tick_params(labelbottom = False, bottom = False)
	ax1.tick_params(labelleft = False, left = False)
	fig.tight_layout()
	plt.show()
	plt.close()

def writeFile(path,lamplist,f,percent):
	lampFlag=[]
	lampFlag.append(path[10:20])

	for bw_image in lampList:
		lampFlag.append(calcBW(bw_image,percent))
		# f=open(path[10:14]+'.txt','a')
	print(lampFlag)
	f.writelines(' '.join(lampFlag))
	f.writelines('\n')

pathList = glob.glob('image_*')
print(pathList)
print(pathList[0][10:14])

f=open(pathList[0][10:14]+'.txt',mode='w')
f.write("wrok No1_off No1_on No2_off No2_on HTank_full HTank_low LTank_full LTank_low\n")
f=open(pathList[0][10:14]+'.txt',mode='a')

for path in pathList:
  binary = binaryCvt(path,245)
#   binary = substImage(path)
  lampList,binary = cutLamp(binary)
#   draw(binary)
  writeFile(path,lampList,f,12)

f.close()


"""Convert SAS7BDAT files to CSV."""

import os
import sys
import typing

from sas7bdat import SAS7BDAT

def convert_files(files: typing.List[str]) -> None:
    """Create a csv file for each matching sas7bdat file."""

    matching = [f for f in files if f.endswith('.sas7bdat')]
    num_files = len(matching)
    if num_files != len(files):
        print('Ignoring {:d}/{:d} files that were not .sas7bdat files.'.format(
            len(files) - num_files, len(files)))
    print('Attempting to convert {:d} files'.format(num_files))

    for i, filename in enumerate(sorted(matching)):
        csv_filename = filename.rsplit('.sas7bdat', 1)[0] + '.csv'
        print('{:d}/{:d}: Converting {} to {}'.format(
            i + 1, num_files, filename, csv_filename))
        if os.path.exists(csv_filename):
            print('Skipping, resulting csv already exists')
            continue
        with SAS7BDAT(filename) as infile:
            infile.convert_file(csv_filename)

if __name__ == '__main__':
    convert_files(sys.argv[1:])


import glob
import os
import pickle
import sys

sys.path.append(os.getcwd())
sys.path.append("")

import torch

# if gpu is to be used
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

import numpy as np

from game.hint_play_game import TwoRoundHintGame
from train_qlearner import obs_to_agent

def sample_games(p1, p2, episodes=10000, verbose=False):
    hp1 = p1.hp
    hp2 = p2.hp
    env = TwoRoundHintGame(hp=hp1)

    rewards = []

    #     print(f'agents are {hp1.agent_type} and {hp2.agent_type}')

    for i_episode in range(episodes):
        # Initialize the environment and state
        obs1, info = env.reset()
        if verbose:
            env.render()
        obs1_a1, obs1_a2 = obs_to_agent(obs1, hp=hp1)
        if hp1.agent_type != 'FF':
            obs1_a1 = obs1_a1.reshape(-1, hp1.nlab1 + hp1.nlab2).T
        # P1 select and perform a hint
        # obs1_a1 = torch.tensor(obs1_a1, device=device)
        a1 = p1.select_action(torch.tensor([obs1_a1], device=device), evaluate=True)
        obs2, _, _, _ = env.step(a1)
        if verbose:
            env.render()
        # P2 plays a card
        obs2_a1, obs2_a2 = obs_to_agent(obs2, hp=hp2)
        if hp2.agent_type != 'FF':
            obs2_a2 = obs2_a2.reshape(-1, hp2.nlab1 + hp2.nlab2).T
        a2 = p2.select_action(torch.tensor([obs2_a2], device=device), evaluate=True)
        _, r, _, _ = env.step(a2)
        r = torch.tensor([r[0]], device=device)
        rewards.append(r.numpy()[0])
        if verbose:
            env.render()
    return np.array(rewards)

if __name__ == "__main__":
    agent1s = []
    agent2s = []
    aid = 11
    for filename in sorted(glob.glob(os.path.join("res/Att3_hs_5_l1_3_l2_3_TrueTrue3000000", "*.pkl"))):
        with open(filename, "rb") as f:
            res = pickle.load(f)
            agent1s += [res['p1']]
            agent2s += [res['p2']]
    print(sample_games(agent1s[aid], agent2s[aid], episodes=10, verbose=True))