import asyncio
import aiohttp
import time
import hashlib
import hmac
import urllib.parse
from typing import List, Tuple
from aiohttp.client_exceptions import ClientError
from exchanges.base_api import BaseAPI
from logger import get_logger
logger = get_logger(__name__)

class PoloniexAPI(BaseAPI):
    def __init__(self, api_key: str, api_secret: str):
        super().__init__()
        self._base_url = 'https://poloniex.com/'
        self._request_interval = 0.17  # rate limit is 6 requests/sec
        self._api_key = api_key
        self._api_secret = api_secret
        loop = asyncio.get_event_loop()
        self._session = aiohttp.ClientSession(loop=loop, headers={})

    async def all_tickers(self, urgency: int = 0):
        return await self._safe_call(urgency, self._request_public, 'returnTicker')

    async def balances(self, urgency: int = 0):
        return await self._safe_call(urgency, self._request_private, 'returnBalances')

    async def buy(self, symbol: str, price: str, amount: str, urgency: int = 0):
        return await self._safe_call(urgency, self._request_private, 'buy', {
            'currencyPair': symbol,
            'rate': price,
            'amount': amount
        })

    async def sell(self, symbol: str, price: str, amount: str, urgency: int = 0):
        return await self._safe_call(urgency, self._request_private, 'sell', {
            'currencyPair': symbol,
            'rate': price,
            'amount': amount
        })

    async def order_status(self, order_id: str, urgency: int = 0):
        return await self._safe_call(urgency, self._request_private, 'returnOrderStatus', {'orderNumber': order_id})

    async def order_trades(self, order_id: str, urgency: int = 0):
        return await self._safe_call(urgency, self._request_private, 'returnOrderTrades', {'orderNumber': order_id})

    async def cancel_order(self, order_id: str, urgency: int = 0):
        return await self._safe_call(urgency, self._request_private, 'cancelOrder', {'orderNumber': order_id})

    async def measure_ping(self) -> Tuple[int, int, int]:
        pings = [
            await self._throttle(self._measure_ping_once)
            for i in range(10)
        ]
        avg = int(sum(pings) / len(pings))
        return min(pings), max(pings), avg

    async def stop(self):
        await super().stop()
        await self._session.close()

    async def _measure_ping_once(self) -> int:
        t = time.time()
        await self._request_private('returnBalances')
        return int((time.time() - t) * 1000)

    async def _request_public(self, command: str):
        data = {'command': command}
        url = f'public?{urllib.parse.urlencode(data)}'
        return await self._request('get', url)

    async def _request_private(self, command: str, data: dict = None) -> dict:
        if data is None:
            data = {}
        # preparing data
        data = {
            'command': command,
            'nonce': int(time.time() * 1000),
            **data
        }
        query = urllib.parse.urlencode(data)
        sig = hmac.new(self._api_secret.encode('utf8'), query.encode('utf8'), hashlib.sha512).hexdigest()
        kwargs = {
            'headers': {
                'Key': self._api_key,
                'Sign': sig
            },
            'data': data,
        }
        return await self._request('post', 'tradingApi', **kwargs)

    async def _request(self, verb: str, endpoint: str, **kwargs) -> dict:
        url = self._base_url + endpoint
        try:
            async with getattr(self._session, verb)(url, **kwargs) as response:
                result = await self._handle_response(response)
        except ClientError as e:
            raise PoloniexAPI.Error(str(e))
        return result

    async def _handle_response(self, response: aiohttp.ClientResponse) -> dict:
        try:
            r = await response.json()
        except ValueError:
            raise PoloniexAPI.Error(f'Invalid Response: {await response.text()}')
        # check if poloniex returned an error
        try:
            if 'result' in r:
                if 'error' in r['result']:
                    raise PoloniexAPI.Error(r['result']['error'])
                else:
                    return r['result']
            else:
                if 'error' in r:
                    raise PoloniexAPI.Error(r['error'])
                else:
                    return r
        except PoloniexAPI.Error as e:
            if 'Order not found' in e.message or 'is either completed or does not exist' in e.message:
                raise BaseAPI.OrderNotFound
            if 'Not enough' in e.message:
                raise PoloniexAPI.ErrorNoRetry(e.message)
            if 'Total must be at least' in e.message:
                raise PoloniexAPI.ErrorNoRetry(e.message)
            raise

async def main():
    from config import config

    api = PoloniexAPI(
        config.get('Exchange', 'APIKey'),
        config.get('Exchange', 'APISecret')
    )
    logger.info(f'Tickers: {await api.all_tickers()}')
    logger.info(f'Balances: {await api.balances()}')
    # logger.info(f'Placing order: {await api.buy("BTC_ETH", "0.01000000", "0.1")}')
    # logger.info(f'Cancelling order: {await api.cancel_order("661906638940")}')
    # logger.info(f'Nonexistent order status: {await api.order_status("123456")}')
    # logger.info(f'Nonexistent order trades: {await api.order_trades("123456")}')
    await api.stop()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())


# libraries
import pandas as pd
from keras.optimizers import Adam
from keras.layers import Dense
from keras.models import Sequential
from sklearn.model_selection import train_test_split

#reading the dataset
dataset = pd.read_csv('/code/wines.csv')

# pre-processing & cleaning the dataset
y = dataset['Class']
y_cat = pd.get_dummies(y)
x = dataset.drop('Class', axis=1)

# spliting the dataset
x_train, x_test, y_train, y_test = train_test_split(x,y_cat,test_size=0.1,random_state=20)

#creating the model
model = Sequential()
model.add(Dense(units=64, input_shape=(13,), activation='relu'))
model.add(Dense(units=3, activation='softmax'))
model.compile(loss='categorical_crossentropy', metrics=['accuracy'], optimizer=Adam())
model.fit(x_train,y_train, validation_data=(x_test,y_test), epochs=20, verbose=0)

#calculating accuracy
accuracy = model.evaluate(x_test, y_test, verbose=0)
accuracy = accuracy[1]*100

# storing accuracy
import os
os.system("sudo touch /code/accuracy.txt")
os.system("echo {} > /code/accuracy.txt".format(accuracy))

# saving the model to send to the client
model.save('/code/multiclassNN.h5')


import pytest
from search_in_a_binary_search_tree import Solution
from helpers.treenode import TreeNode

@pytest.mark.parametrize('arr, val, expected', [
    ([4,2,7,1,3], 2, [2,1,3]),
    ([4,2,7,1,3], 5, []),
])
def test_solution(arr, val, expected):
    root = TreeNode.from_array(arr)
    expected = TreeNode.from_array(expected)
    assert Solution().searchBST(root, val) == expected


import os, sys
import random

from collections import OrderedDict
_getwordsfile_dloadloc = 'http://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words'
_init_filelocs = [
    '/usr/share/dict/words'
]
_init_defaults = OrderedDict(dodownload=False, downloadloc=_getwordsfile_dloadloc, downloadout=None, filelocs=_init_filelocs)
def init(dodownload=2, downloadloc=_getwordsfile_dloadloc, downloadout=None, filelocs=_init_filelocs):
    global wordsfile, openwordsfile, openedwordsfile, wordslist
    global getwordsfile, getwordslist

    _defenc = sys.getdefaultencoding()
    _getwordsfile_dloadloc = 'http://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words'
    def getwordsfile(dodownload=False, downloadloc=_getwordsfile_dloadloc, downloadout=None):
        dictfile = ''

        for loc in filelocs:
            if os.path.isfile(loc):
                dictfile = loc
                break
        else:
            if dodownload == 1:
                if downloadout is None: downloadout = locs[0]
                import urllib.request as request, shutil
                fin = request.urlopen(downloadloc)
                outdir = '/'.join(downloadout.split('/')[:-1])
                if not os.path.exists(outdir): os.makedirs(outdir)
                fout = open(downloadout, 'wb')
                shutil.copyfileobj(fin, fout)
                fout.close()
                dictfile = downloadout
            elif dodownload == 0:
                raise FileNotFoundError
        return dictfile
    wordsfile = getwordsfile(dodownload)
    openwordsfile = lambda wordsfile=wordsfile: open(wordsfile)

    def getwordslist(wordsfile_=wordsfile):
        if wordsfile_ == wordsfile and openedwordsfile:
            openedwordsfile_ = openedwordsfile
        else:
            openedwordsfile_ = openwordsfile(wordsfile_)
        res = []
        for line in openedwordsfile_:
            res.append(line.strip())
        return res
    try:
        openedwordsfile = openwordsfile()
        wordslist = getwordslist()
    except OSError:
        openedwordsfile = None
        wordslist = []
init.__defaults__ = tuple(_init_defaults.values())
import inspect
def preinit(*args, **kwargs):
    argnames = inspect.getfullargspec(init)[0]
    for (i, val) in enumerate(args):
        _init_defaults[argnames[i]] = val
    _init_defaults.update(kwargs)
    init.__defaults__ = tuple(_init_defaults.values())

# lowerwordslist = lambda: (x.lower() for x in wordslist)

def scramble(word, random_=None):
    word = list(word)
    random.shuffle(word, random_)
    return ''.join(word)

def unscramble(word, lowercaps=True):
    if lowercaps: word = word.lower()
    word = list(word)
    worddef = word[:]
    if lowercaps: mywordslist = [x.lower() for x in wordslist]
    else: mywordslist = wordslist
    visited = set()
    for testword in mywordslist:
        if testword in visited: continue
        for (i, char) in enumerate(testword):
            if char in word:
                word.pop(word.index(char))
            else: break
            if i == len(testword) - 1 and word: break
        else:
            yield testword
            visited.add(testword)
        word = worddef[:]

def makewingui():
    form = Form()
    form.SuspendLayout()
    stxt = TextBox()
    utxt = TextBox()
    sbtn = Button()
    ubtn = Button()

    #
    # stxt
    #
    stxt.Location = Point(12, 8)
    stxt.Name = 'stxt'
    stxt.Size = Size(319, 20)
    stxt.TabIndex = 0
    #
    # utxt
    #
    utxt.Location = Point(12, 34)
    utxt.Name = 'utxt'
    utxt.Size = Size(319, 20)
    utxt.TabIndex = 2
    #
    # sbtn
    #
    sbtn.Anchor = AnchorStyles.Top | AnchorStyles.Right
    sbtn.Location = Point(337, 6)
    sbtn.Name = 'sbtn'
    sbtn.Size = Size(75, 23)
    sbtn.TabIndex = 1
    sbtn.Text = 'Scramble'
    sbtn.UseVisualStyleBackColor = True
    def sres(sender, e):
        stxt.Text = scramble(stxt.Text)
    sbtn.Click += EventHandler(sres)
    # ubtn.MouseEnter += EventHandler(sres)
    #
    # ubtn
    #
    ubtn.Anchor = AnchorStyles.Top | AnchorStyles.Right
    ubtn.Location = Point(337, 32)
    ubtn.Name = 'ubtn'
    ubtn.Size = Size(75, 23)
    ubtn.TabIndex = 3
    ubtn.Text = 'Unscramble'
    ubtn.UseVisualStyleBackColor = True
    def ures(sender, e):
        utxt.Text = '/'.join(unscramble(utxt.Text))
    ubtn.Click += EventHandler(ures)
    # ubtn.MouseEnter += EventHandler(ures)
    #
    # form
    #
    form.AutoScaleDimensions = SizeF(6.0, 13.0)
    form.AutoScaleMode = AutoScaleMode.Font
    form.ClientSize = Size(424, 61)
    form.Controls.Add(stxt)
    form.Controls.Add(utxt)
    form.Controls.Add(sbtn)
    form.Controls.Add(ubtn)
    form.FormBorderStyle = FormBorderStyle.Fixed3D
    form.Name = 'form'
    form.Text = os.path.basename(__file__)
    form.ResumeLayout(False)
    form.PerformLayout()

    Application.EnableVisualStyles()
    Application.Run(form)

if __name__ == '__main__':
    # wordsfile = getwordsfile(True)
    # openedwordsfile = openwordsfile()
    # wordslist = getwordslist()
    preinit(True)
    init()
    get = lambda name: sys.argv[sys.argv.index(name) + 1]
    if '--gui' in sys.argv:
        import clr
        clr.AddReference('System')
        from System import *
        clr.AddReference('System.Drawing')
        from System.Drawing import *
        clr.AddReference('System.Windows.Forms')
        from System.Windows.Forms import *
        makewingui()
        sys.exit()
    done = False
    if   '-s' in sys.argv:
        done = True
        print('Scrambled:')
        print('   ', scramble(get('-s')))
    elif '--scramble' in sys.argv:
        done = True
        print('Scrambled:')
        print('   ', scramble(get('--scramble')))
    if   '-u' in sys.argv:
        done = True
        print('Unscrambled:')
        for result in unscramble(get('-u'), not ('--caps' in sys.argv or '--capitalization' in sys.argv)):
            print('   ', result)
    elif '--unscramble' in sys.argv:
        done = True
        print('Unscrambled:')
        for result in unscramble(get('--unscramble'), not ('--caps' in sys.argv or '--capitalization' in sys.argv)):
            print('   ', result)
    if not done or '-h' in sys.argv or '--help' in sys.argv:
        print('Usage:', sys.executable, __file__, '[-h|--help]', '[--gui]', '[--caps|--capitalization]',
        '[-s|--scramble <word>]', '[-u|--unscramble <scrambled_word>]')
    # import pprint
    # pprint.pprint(list(unscramble(scramble('aloha'))))


import re

text = 'So do all who live to see such times.  But that is not for them to decide.  All we have to decide is what to do with the time that is given to us.'
pattern = r' [A-Za-z][A-Za-z] '     # need the 'r' to indicate raw input

m = re.search(pattern, text)    # only gets the first occurrence of regex match

print(m)

found = re.findall(pattern, text)   # gets all matches of regex

print(found)

pattern = input("Input your regex: ")   # keyboard input is already raw so no "r" needed

found = re.findall(pattern, text)   # gets all matches of regex

print(found)


import flask
import sqlite3

from flask import request, jsonify

app = flask.Flask(__name__)
app.config['DEBUG'] = True

@app.route('/api/v1/report', methods=['GET'])
def report():
    args = request.args
    if 'date' in args:
        date = args['date']
        with sqlite3.connect('app.db') as con:
            cur = con.cursor()
            customers = cur.execute(
                'SELECT COUNT(DISTINCT customer_id) FROM orders '
                'WHERE date(created_at)={}'.format(date)
            ).fetchone()[0]
            total_discount_amount = cur.execute(
                'SELECT SUM(discounted_amount) FROM order_lines '
                'INNER JOIN orders ON order_lines.order_id=orders.id '
                'WHERE date(created_at)={}'.format(date)
            ).fetchone()[0]
            items = cur.execute(
                'SELECT COUNT(*) FROM order_lines '
                'INNER JOIN orders ON order_lines.order_id=orders.id '
                'WHERE date(created_at)={}'.format(date)
            ).fetchone()[0]
            order_total_avg = cur.execute(
                'SELECT AVG(total_amount) FROM order_lines '
                'INNER JOIN orders ON order_lines.order_id=orders.id '
                'WHERE date(created_at)={}'.format(date)
            ).fetchone()[0]
            discount_rate_avg = cur.execute(
                'SELECT AVG(discount_rate) FROM order_lines '
                'INNER JOIN orders ON order_lines.order_id=orders.id '
                'WHERE date(created_at)={}'.format(date)
            ).fetchone()[0]
        con.close()
        return jsonify(
            {
                'customers': customers,
                'total_discount_amount': round(total_discount_amount, 2),
                'items': items,
                'order_total_avg': round(order_total_avg, 2),
                'discount_rate_avg': round(discount_rate_avg, 2)
            }
        )
    else:
        return jsonify(
            {
                'error': 'Please include a date in the request parameters.'
            }
        )

app.run()


# -*- coding: utf-8 -*-
"""
Credit to Akkana. Original code can be found here: https://github.com/akkana/scripts/blob/master/mapping/election2016/bluered-censusshapes.py.
"""
import sys
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon

from difflib import SequenceMatcher

# We need CSV to parse the county data:
import csv
# but then the county shapes are encoded inside the CSV as JSON, so
import simplejson as json

def draw_us_map():
    # Set the lower left and upper right limits of the bounding box:
    lllon = -119
    urlon = -64
    lllat = 22.0
    urlat = 50.5
    # and calculate a centerpoint, needed for the projection:
    centerlon = float(lllon + urlon) / 2.0
    centerlat = float(lllat + urlat) / 2.0

    m = Basemap(resolution='i',  # crude, low, intermediate, high, full
                llcrnrlon = lllon, urcrnrlon = urlon,
                lon_0 = centerlon,
                llcrnrlat = lllat, urcrnrlat = urlat,
                lat_0 = centerlat,
                projection='tmerc')

    # map.drawmapboundary(fill_color='ivory')
    # map.fillcontinents(color='coral', lake_color='aqua')

    # m.drawcoastlines()
    # m.drawcountries()

    # drawstates() is built into basemap -- but then there's no
    # way to associate the shapes with state names. Hence the shape files.
    # m.drawstates()

    # draw state boundaries.
    # data from U.S Census Bureau
    # http://www.census.gov/geo/www/cob/st2000.html
    shp_info = m.readshapefile('data/state-shapes/st99_d00', 'states',
                               drawbounds=True, color="lightgrey")

    # County data from Census Bureau
    shp_info = m.readshapefile('data/census-counties-2018/cb_2018_us_county_500k',
                               'counties',
                               drawbounds=True)

    maxstatefp = 0
    states = [None] * 75
    for state in m.states_info:
        statefp = int(state["STATE"])
        # print statefp, state["NAME"]
        if statefp > maxstatefp:
            maxstatefp = statefp
        # Many states have multiple entries in m.states (because of islands?).
        # Only need to add it once.
        if not states[statefp]:
            states[statefp] = state["NAME"]

    # print "max statefp:", maxstatefp
    # for i, s in enumerate(states):
    #     if s:
    #         print i, s

    return m, states

#############

def map_county_data(m, states):
    '''
    '''
    # fp = open("data/alamos.csv")
    # csv.field_size_limit(sys.maxsize)
    fp = open("data/tidy_data.csv")
    reader = csv.DictReader(fp)

    ax = plt.gca()     # get current axes instance

    # Make a dictionary of all counties and their colors.
    county_colors = {}
    for county in reader:
        # What color is this county?

        # Alaska has no results at all:
        if not county["votes16_clintonh"] or not county["votes16_trumpd"]:
            print ("No results for", cname)
            continue

        # print "keys:", county.keys()
        # The dataset holds at least one blank county in Alaska ...
        # which nevertheless has lots of demographic stats,
        # though no election results.
        if not county["name_16"]:
            # Alaska counties are all missing their county name,
            # but we might be able to get it from the longer County field.
            cname = county["County"][:-8]
            if cname.endswith(" Census Area"):
                cname = cname[:-12]
            elif cname.endswith(" City and Borough"):
                cname = cname[:-17]
            elif cname.endswith(" Borough"):
                cname = cname[:-8]
            else:
                print ("Not sure what", cname, "ends with")
                continue
            print ("County name was blank, using", cname)
        else:
            cname = county["name_16"]

        # What color is this county?
        # print "keys:", county.keys()
        # print county
        dem = float(county["votes16_clintonh"])
        rep = float(county["votes16_trumpd"])
        # pop = float(county["Total.Population"])
        pop = float(county["votes"])
        #print (county["name_16"], ":", dem, rep, pop, county["votes"])
        blue = dem/pop
        red = rep/pop

        # In the Deleetdk data, some counties end with "County" inappropriately.
        # Remove it, if so.
        if cname.lower().endswith(" county"):
            print ("Stripping -county", cname)
            cname = cname[:-7]
        county_colors["%s, %s" % (cname, county["State"])] \
            = (red, 0, blue)

    fp.close()

    # Now loop through all counties on the map, coloring them appropriately.
    for i, county in enumerate(m.counties_info):
        countyname = county["NAME"]
        try:
            statename = states[int(county["STATEFP"])]
        except IndexError:
            print (countyname, "has out-of-index statefp of", county["STATEFP"])
            continue

        # The file has no results for Puerto Rico and Alaska.
        if statename == "Puerto Rico" or statename == "Alaska":
            continue

        if not statename:
            print ("No state for", countyname)
            continue

        countystate = "%s, %s" % (countyname, statename)
        #print(countystate)

        try:
            ccolor = county_colors[countystate]
        except KeyError:
            # No exact match. Try for a fuzzy match.
            # Some counties in the Deleetdk are capitalized,
            # lack spaces between words, lack tildes or similar.
            fuzzyname = fuzzy_find(countystate, county_colors.keys())
            if fuzzyname:
                print ("Got a fuzzy match,", countystate, "=", fuzzyname)
                ccolor = county_colors[fuzzyname]
                county_colors[countystate] = ccolor
            else:
                print ("No match for", countystate)
                continue
        countyseg = m.counties[i]

        # Move Hawaii and Alaska:
        # http://stackoverflow.com/questions/39742305/how-to-use-basemap-python-to-plot-us-with-50-states
        # Offset Alaska and Hawaii to the lower-left corner.
        if statename == 'Alaska':
        # Alaska is too big. Scale it down to 35% first, then transate it.
            countyseg = list(map(lambda x: (0.35*x[0] + 1100000, 0.35*x[1]-1300000), countyseg))
        elif statename == 'Hawaii':
            countyseg = list(map(lambda x: (x[0] + 5750000, x[1]-1400000), countyseg))

        poly = Polygon(countyseg, facecolor=ccolor)  # edgecolor="white"
        #print(poly)
        ax.add_patch(poly)

###########

def fuzzy_find(s, slist):
    '''Try to find a fuzzy match for s in slist.
    '''
    best_ratio = -1
    best_match = None

    ls = s.lower()
    for ss in slist:
        r = SequenceMatcher(None, ls, ss.lower()).ratio()
        if r > best_ratio:
            best_ratio = r
            best_match = ss
    if best_ratio > .75:
        return best_match
    return None

def init_map():
    '''Draw a map of the US, upon which we can graph county results.
    '''
    m, states = draw_us_map()

#     for i, shapedict in enumerate(m.states_info):
#         statename = shapedict['NAME']
# #         if statename == "New Mexico":
# #             seg = m.states[i]
# # #             poly = Polygon(seg, facecolor='red', edgecolor='red')
# # #             ax.add_patch(poly)

    return m, states

def show_map():
    # This gets rid of most of the extra horizontal whitespace,
    # and about half the vertical:
    plt.tight_layout(pad=0, w_pad=0, h_pad=0)

    plt.title('The Map')
    plt.show()
    # plt.savefig('test.png')

m, states = init_map()

map_county_data(m, states)

show_map()


import unittest
from circuit import Wire, Bus, TRUE, FALSE, CPU

class CPUTest(unittest.TestCase):
    def test_cpu(self):
        inputs = Bus([TRUE, FALSE])
        cpu = CPU()
        cpu.ram.registers[42].bit_registers[7].next_state = True

        for i in range(10):
            inputs.reset()
            inputs.propagate()
            print(cpu.hex_dump())


#!/usr/bin/env python3
import utils
from year_2017.day_11 import part_a

class Challenge(utils.BaseChallenge):
    def solve(self, _input, debug=False):
        """
        >>> Challenge().default_solve()
        1524
        """
        directions = part_a.DirectionsRotator()\
            .rotate_directions(_input.strip().split(','))
        max_distance = 0
        zero_point = utils.PointHex(0, 0)
        point = zero_point
        for direction in directions:
            point = point.move(direction)
            max_distance = max(max_distance, point.step_distance(zero_point))
        return max_distance

Challenge.main()
challenge = Challenge()


def binsearch(arr, key):
	arr = sorted(arr)
	start = 0
	end = len(arr) - 1
	#loop
	while(start <= end):
		m = (start+end)/2
		if arr[m] == key:
			return m
		if arr[m] > key:
			end = m-1
		else:
			start = m+1
	raise Exception("Key %d not found in %s" % (key, arr))

def main():
	arr = [1,2,4,5,7,8,10]


import logging,time
from selenium.webdriver.common.by import By
from page.base import PageBase
from common.tools import switch_execute

class PageHome(PageBase):
	def __init__(self,driver):
		# 首页 页面
		super().__init__(driver)
		self.btnReload={
			'Android':(By.ID,'com.cmbi.zytx:id/reload_btn'),
			'iOS':(By.IOS_PREDICATE,"name=='reload'")
		}
		self.eleRegister={
			'Android':(By.XPATH,"//*[text()='港美开户']"),
			'iOS':(By.IOS_PREDICATE,"name=='港美开户'")
		}
		self.eleCurrExchange={
			'Android':(By.XPATH,"//*[text()='货币兑换']"),
			'iOS':(By.IOS_PREDICATE,"name=='货币兑换'")
		}
		self.eleRegisterNow=(By.ID,"getAccount")

		#基金板块
		self.btnFundMore={
			'Android':(By.CLASS_NAME,"global-fund-more"),
			'iOS':(By.IOS_PREDICATE,"name=='查看更多'")
		}
		self.eleFund1={
			'Android':(By.CLASS_NAME,"global-fund-name"),
			'iOS':(By.IOS_PREDICATE,"name=='近一年收益率'")
		}
		self.eleFund1Name=(By.CLASS_NAME,"global-fund-name")
		#深度推荐板块
		self.btnArticleOne={
			'Android':(By.CLASS_NAME,"card"),
			'iOS':(By.XPATH,"//*[@name='关注']/../following-sibling::*[1]")
		}
		self.eleArticleTitle=(By.CLASS_NAME,"detailItem-title")

		self.passwordInput={
			'Android':(By.ID,'com.cmbi.zytx:id/input_trade_password'),
			'iOS':(By.IOS_PREDICATE,"type=='XCUIElementTypeSecureTextField'")
		}
		self.confirm={
			'Android':(By.ID,'com.cmbi.zytx:id/btn_submit'),
			'iOS':(By.IOS_PREDICATE,"name=='确定'")
		}

	@switch_execute
	def inputPwordIFneeded(self):
		try:
			self.findElement(self.passwordInput[self.PFN],timeout=3,screen=0).send_keys('aaaa1111')
			self.findElement(self.confirm[self.PFN],timeout=3,screen=0).click()
		except:
			pass

	# @switch_execute
	def clickReload(self):
		logging.info('点击 reload')
		self.findElement(self.btnReload[self.PFN]).click()
		time.sleep(5)

	def clickRegister(self):
		logging.info('点击 港美开户')
		if self.PFN=='Android':
			self.myTap(self.findElement(self.eleRegister[self.PFN]))
		else:
			self.clickRegister_IOS()

	@switch_execute
	def clickRegister_IOS(self):
		self.findElement(self.eleRegister[self.PFN]).click()

	@switch_execute
	def clickCurrExchange_IOS(self):
		self.findElement(self.eleCurrExchange[self.PFN]).click()

	def clickCurrExchange(self):
		logging.info('点击 货币兑换')
		if self.PFN=='Android':
			self.myTap(self.findElement(self.eleCurrExchange[self.PFN]))
		else:
			self.clickCurrExchange_IOS()
		time.sleep(3)
		self.inputPwordIFneeded()

	def clickRegisterNow(self):
		logging.info('点击 立即开户')
		self.myTap(self.findElement(self.eleRegisterNow))

	#基金板块
	def clickFundMore(self):
		logging.info('点击基金板块 更多 按钮')
		self.driver.execute_script(f'document.getElementById("hotTitle").scrollIntoView();')
		if self.PFN=='Android':
			self.myTap(self.findElement(self.btnFundMore[self.PFN]))
		else:
			self.clickFundMore_IOS()

	@switch_execute
	def clickFundMore_IOS(self):
		self.findElement(self.btnFundMore[self.PFN]).click()

	def textFund1(self):
		self.driver.execute_script('document.querySelector(".hot-fund-img").scrollIntoView();')
		txt=self.findElement(self.eleFund1Name,until='located').get_attribute("innerText")
		return txt

	def clickFund1(self):
		logging.info('点击基金板块中的第1个基金')
		if self.PFN=='Android':
			self.myTap(self.findElement(self.eleFund1[self.PFN]))
		else:
			self.clickFund1_IOS()

	@switch_execute
	def clickFund1_IOS(self):
		self.findElement(self.eleFund1[self.PFN]).click()

	#深度推荐板块
	def textArticleOne(self):
		time.sleep(3)
		self.driver.execute_script('document.getElementsByClassName("card-title")[0].scrollIntoView();')
		time.sleep(1)
		text=self.driver.execute_script('return document.getElementsByClassName("card-title")[0].textContent;')
		return text

	def clickArticleOne(self):
		logging.info('点击深度推荐板块中的第1篇文章')
		time.sleep(3)
		self.driver.execute_script('document.getElementsByClassName("card-title")[0].scrollIntoView();')
		time.sleep(1)
		if self.PFN=='Android':
			self.myTap(self.findElement(self.btnArticleOne[self.PFN]))
		else:
			self.clickArticleOne_IOS()

	@switch_execute
	def clickArticleOne_IOS(self):
		self.findElement(self.btnArticleOne[self.PFN]).click()

	def textArticleTitle(self):
		for i in range(10):
			txt=self.findElement(self.eleArticleTitle).text
			if txt:return txt
			else:time.sleep(1)


from classes import Funcionario
from random import randint

def menu(cadastro, conta):
    opt = int(input(f"\nMenu da conta {conta}\nSelecione uma das opções do menu.\n1 - Saque\n2 - Saldo\n"
                    f"3 - Pedir demissão\n4 - Sair\n"
                    f"nSelecione uma das opções: "))
    if opt == 1:
        cadastro[conta].saque(float(input("Informe o valor a sacar em R$: ")))
        menu(cadastro, conta)
    elif opt == 2:
        print(cadastro[conta])
        menu(cadastro, conta)
    elif opt == 3:
        cadastro[conta] = None
        print("Você foi demitido.\n")
        proletario(cadastro)
    else:
        print("Encerrando o programa...")
        exit()

def proletario(funcionarios):
    print("Login:\n")
    conta = int(input("Bem-vinde ao banco que te remunera muitíssimo bem!\nInforme seu código de funcionário: "))
    if conta >= len(funcionarios):
        print("Código inválido. Tente novamente.")
        proletario(funcionarios)
    else:
        menu(funcionarios, conta)

if __name__ == "__main__":
    print("Executando terminal de funcionário...\n")

    with open("nomes.txt", 'r', encoding='utf-8') as arquivo:
        nomes = [nome.strip() for nome in arquivo]

    funcionarios = []

    for iteracao in range(50):
        funcionarios.append(Funcionario(nomes[randint(0, len(nomes)) - 1], randint(100000000000, 999999999999), "cargo",
                                        randint(1000, 9999), funcionarios))

    proletario(funcionarios)


#Escenario
#Tu tarea es escribir una función capaz de ingresar valores enteros
#y verificar si están dentro de un rango especificado.
def readint(prompt, min, max):
    try:
        if int(prompt)>min and int(prompt)<max:
            return int(prompt)
        else:
            print("Error: el valor no está dentro del rango permitido (",min,"..",max,")")
            readint(input("Ingresa un numero de -10 a 10: "),min,max)
    except:
        print("Error: entrada incorrecta")
        readint(input("Ingresa un numero de -10 a 10: "),min,max)

v = readint("Ingresa un numero de -10 a 10: ", -10, 10)

print("El numero es:", v)


#!/usr/bin/env python3
# -*-encoding: utf-8-*-

"""
модуль з функціями для лінійної апроксимації

розв'язання системи лінійних рівнянь проводиться методом квадратного кореня
"""

import numpy as np
import random
from numpy import sign
from math import sqrt

def print_system(a, b):
    """
    Виводить на екран систему рівнянь.

    :param a: numpy 2-вимірний масив коефіцієнтів
    :param b: numpy масив вільних членів
    """
    print("Система:")
    for i in range(a.shape[0]):

        # a.shape[0] - кількість рядків, a.shape[1] - кількість стовпчиків матриці
        row = ["{}*x{}".format(a[i, j], j + 1) for j in range(a.shape[1])]
        print(" + ".join(row), " = ", b[i])
    print()

def tabulate_with_fault(func, a: float, b: float, n: int, eps: float):
    """
    процедура табулювання функції з похибкою

    :param func: функція
    :param a: ліва межа відрізку
    :param b: права межа відрізку
    :param n: к-ть точок
    :param eps: похибка фізичного експерименту
    :return: x - масив numpy точок
             y - масив numpy значень функції

    """
    x = np.linspace(a, b, n)
    eta = 1
    while eta == 1:
        eta = random.uniform(0, 1)

    try:
        y = func(x) + eta * eps
    except Exception as e:
        print("exception:", e)
        y = np.zeros(n)
        for i in range(n):
            y[i] = func(x[i]) + eta * eps
    return x, y

def linear_eq_system(x: np.ndarray, y: np.ndarray, n1: int, eps: float):
    """
    створення системи лінійних рівнянь для апроксимації методом найменших квадратів
    :param x: numpy масив точок функції
    :param y: numpy масив значень функції в точках x
    :param n1: к-ть ітерацій
    :param eps:
    :return:
    """
    a = np.zeros((n1, n1))    # матриця коефіцієнтів
    b = np.zeros(n1)          # матриця вільних членів
    p = eps ** (-2)
    n2 = x.size
    for m in range(n1):
        for i in range(n2):               # реалізація формули (2)
            b[m] += p * y[i] * x[i] ** m

        for j in range(n1):
            for i in range(n2):
                a[m, j] += p * x[i] ** (j + m)
    return a, b

def _sds_decomposition(a: np.matrix):
    """
    функція, яка розкладає матрицю А на добуток матриць S^T * D * S
    :param a: матриця numpy
    :return: tmp_s - матриця numpy (S)
             tmp_d - матриця numpy (D)
    """
    tmp_s = np.matrix(np.zeros(a.shape))     # створення матриць з нулями
    tmp_d = np.matrix(np.zeros(a.shape))

    for k in range(a.shape[0]):   # поелементне знаходження всіх елементів

        tmp_sum = 0
        for i in range(k):       # проміжний результат для формул
            tmp_sum += tmp_d[i, i] * abs(tmp_s[i, k]) ** 2

        tmp_res = a[k, k] - tmp_sum
        tmp_d[k, k] = sign(tmp_res)          # діагональний елемент матриці D
        tmp_s[k, k] = sqrt(abs(tmp_res))     # діагональний елемент матриці S

        for l in range(a.shape[0]):          # заповнення інших елементів у рядку (верхньотрикутних)
            if k + 1 <= l:
                tmp_sum = sum(tmp_d[i, i] * tmp_s.transpose()[i, k] * tmp_s[i, l] for i in range(k))
                tmp_s[k, l] = (a[k, l] - tmp_sum) / (tmp_s[k, k] * tmp_d[k, k])
    print(tmp_s, '\n', tmp_d)
    return tmp_s, tmp_d

def square_method(a: np.matrix, b: np.ndarray):
    """
    розв'язує симетричну слр методом квадратного кореня
    :param a: матриця коефіцієнтів
    :param b: матриця вільних членів
    :return: матриця невідомих
    """
    tmp_s, tmp_d = _sds_decomposition(a)    # розклад симетричної матриці
    tmp_s_t = tmp_s.transpose()             # транспонування
    n = a.shape[0]

    y = np.zeros(n)            # створення допоміжної матриці з проміжними невідомими

    y[0] = b[0] / (tmp_s[0, 0] * tmp_d[0, 0])     # заповнення матриці проміжних невідомих
    for i in range(1, n):
        y[i] = (b[i] - sum(tmp_d[l, l] * y[l] * tmp_s_t[l, i] for l in range(i))) / \
               (tmp_s[i, i] * tmp_d[i, i])

    x = np.zeros(n)     # заповнення матриці кінцевих невідомих
    x[n-1] = y[n-1] / tmp_s[n-1, n-1]
    for i in range(n-1, -1, -1):
        x[i] = (y[i] - sum(tmp_s[l, i] * x[l] for l in range(i + 1, n))) / (tmp_s[i, i])

    return x

def result_func(coeff, x, n):
    """
    рахує значення апроксимативної функції в точках
    :param coeff: масив коефіцієнтів (корені слр)
    :param x: масив точок
    :param n: к-ть точок
    :return: масив значень
    """
    res = sum(coeff[i] * x ** i for i in range(n))
    return res

if __name__ == '__main__':

    test_a = np.matrix([[1, 2, 3], [2, 1, 2], [3, 2, 1]])
    test_b = np.array([0, 3, 2])
    result = square_method(test_a, test_b)

    print(result)


from fastapi import Form
from pydantic import BaseModel

class ProductForm(BaseModel):
    name: str
    price: float

    class Config:
        orm_mode = True

    @classmethod
    def as_form(
            cls,
            name: str = Form(...),
            price: str = Form(...)
    ):
        return cls(name=name,price=price)


from enum import Enum
from typing import Optional, Dict
import cv2
import numpy as np

from utils.images import imread, imwrite

class Color(Enum):
    """An enum that defines engine colors.

    Contains red, green, blue, cyan, yellow, magenta, white and black.
    """
    red = (0, 0, 255)
    green = (0, 255, 0)
    blue = (255, 0, 0)
    cyan = (255, 255, 0)
    yellow = (0, 255, 255)
    magenta = (255, 0, 255)
    white = (255, 255, 255)
    black = (0, 0, 0)

def color_val(color):
    """Convert various input to color tuples.

    Args:
        color (:obj:`Color`/str/tuple/int/ndarray): Color inputs

    Returns:
        tuple[int]: A tuple of 3 integers indicating BGR channels.
    """
    if isinstance(color, str):
        return Color[color].value
    if isinstance(color, Color):
        return color.value
    if isinstance(color, tuple):
        assert len(color) == 3
        for channel in color:
            assert 0 <= channel <= 255
        return color
    if isinstance(color, int):
        assert 0 <= color <= 255
        return color, color, color
    if isinstance(color, np.ndarray):
        assert color.ndim == 1 and color.size == 3
        assert np.all((color >= 0) & (color <= 255))
        color = color.astype(np.uint8)
        return tuple(color)
    raise TypeError(f'Invalid type for color: {type(color)}')

def imshow(img, win_name='', wait_time=0):
    """
    Show an image.

    Args:
        img (str or ndarray): The image to be displayed.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param.
    """
    cv2.imshow(win_name, imread(img))
    if wait_time == 0:  # prevent from hanging if windows was closed
        while True:
            ret = cv2.waitKey(1)

            closed = cv2.getWindowProperty(win_name, cv2.WND_PROP_VISIBLE) < 1
            # if user closed window or if some key pressed
            if closed or ret != -1:
                break
    else:
        ret = cv2.waitKey(wait_time)

def show_result(img: str,
                result: Dict[int, float],
                text_color: str = 'green',
                font_scale: float = 0.5,
                row_width: int = 20,
                show: bool = False,
                win_name: str = '',
                wait_time: int = 0,
                out_file: Optional[str] = None) -> None:
    """Mark the results on the picture.

    Args:
        img (str): The image to be displayed.
        result (dict): The classification results to draw over `img`.
        text_color (str or tuple or :obj:`Color`): Color of texts.
        font_scale (float): Font scales of texts.
        row_width (int): width between each row of results on the image.
        show (bool): Whether to show the image. Default: False.
        win_name (str): The window name.
        wait_time (int): Value of waitKey param. Default: 0.
        out_file (str or None): The filename to write the image. Default: None.

    Returns:
        None
    """
    img = imread(img, mode="RGB")
    img = img.copy()

    # Write results on left-top of the image.
    x, y = 0, row_width
    text_color = color_val(text_color)
    for k, v in result.items():
        if isinstance(v, float):
            v = f'{v:.2f}'
        label_text = f'{k}: {v}'
        cv2.putText(img, label_text, (x, y), cv2.FONT_HERSHEY_COMPLEX,
                    font_scale, text_color)
        y += row_width

    # If out_file specified, do not show image in window.
    if out_file:
        show = False
        imwrite(img, out_file)

    if show:
        imshow(img, win_name, wait_time)


# -*- coding: utf-8 -*-

import maya.cmds as mc
import maya.mel as mel
from Qt.QtWidgets import *
from Qt.QtCore import *
from Qt.QtGui import *
from miraLibs.mayaLibs import get_maya_win

class NormalCopy:
    def __init__(self):
        self.select_list = mc.ls(sl=1, l=1)
        self.load_plugin()

    @staticmethod
    def load_plugin():
        if not mc.pluginInfo('normalCopy', q=1, l=1):
            mc.loadPlugin('normalCopy.mll')

    def do_normal_copy(self):
        if not len(self.select_list) == 2:
            maya_win = get_maya_win.get_maya_win("PySide")
            QMessageBox.information(maya_win, 'error', 'select two objects ,please')
            return
        src_obj = self.select_list[0]
        tar_obj = self.select_list[1]
        _cmd = "normalCopy -src \"%s\" -tar \"%s\"" % (src_obj, tar_obj)
        mel.eval(_cmd)

def main():
    op = NormalCopy()
    op.do_normal_copy()

if __name__ == '__main__':
    main()


#hangman by alexandra sergueeva and joshua yu
import random
import time
import pickle
from datetime import datetime
add_library("minim")
def setup():
    global minim, click, bloop, scoreadded, gamemode, font, playerName, wrongGuesses, hangmanImage, guessLimit, keyboard, listGuessed, listWrongGuesses, points, hintChosen, highscoreDict
    gamemode = "startMenu"
    font = loadFont("BradleyHandITC-48.vlw")
    words = getFileInfo("hangmanwords.txt")
    hangmanImage = {0:loadImage("hangman.png"), 1:loadImage("hangman1.png"), 2:loadImage("hangman2.png"), 3:loadImage("hangman3.png"), 4:loadImage("hangman4.png"), 5:loadImage("hangman5.png"), 6:loadImage("hangman6.png")}
    keyboard = [[['q', True],['w', True],['e', True],['r', True],['t', True],['y', True],['u', True],['i', True],['o', True],['p', True]],
                [['a', True],['s', True],['d', True],['f', True],['g', True],['h', True],['j', True],['k', True],['l', True]],
                [['z', True],['x', True],['c', True],['v', True],['b', True],['n', True],['m', True]]]
    wordGenerator()
    listGuessed = []
    listWrongGuesses = []
    ###print(words)
    size(800,600)
    playerName = []
    wrongGuesses = 0
    guessLimit = 6
    points = 0
    highscoreDict = {}
    hintChosen = False
    scoreadded = False
    add_library('minim')
    minim = Minim(this)
    click = minim.loadFile("click.wav")
    bloop = minim.loadFile("correct.wav")

def draw():
    imageMode(CENTER)
    if gamemode == "startMenu":
        startMenu()
    if gamemode == "playerMenu":
        playerMenu()
    if gamemode == "scoresMenu":
        scoresMenu()
    if gamemode == "helpMenu":
        helpMenu()
    if gamemode == "inGame":
        game()
        keyboardDisplay()
        hintDisplay()
    if gamemode == "end":
        endScreen()
    if gamemode == "won":
        wonScreen()

def getFileInfo(fileName):
    global fileInfo
    file = open(fileName)
    fileInfo = []
    fileText = file.readlines()
    for x in fileText:
        x = x.strip()
        x = x.split(",")
        fileInfo.append(x)
    return fileInfo

def startMenu(): #start menu
    background(255)
    textFont(font)
    textAlign(CENTER)
    textSize(48)
    fill(0)
    text("hangman", width/2, height/5)
    if width/2-50 <= mouseX <= width/2+50 and 200 <= mouseY <= 270:
        fill(225)
        text("play", width/2, (height/5)*2)
        fill(0)
    else:
        fill(0)
        text("play", width/2, (height/5)*2)
    if width/2-50 <= mouseX <= width/2+50 and 325 <= mouseY <= 380:
        fill(225)
        text("help", width/2, (height/5)*3)
        fill(0)
    else:
        fill(0)
        text("help", width/2, (height/5)*3)
    if width/2-60 <= mouseX <= width/2+60 and 460 <= mouseY <= 485:
        fill(225)
        text("scores", width/2, (height/5)*4)
        fill(0)
    else:
        fill(0)
        text("scores", width/2, (height/5)*4)

def playerMenu(): #where you select number of players and input names
    global minLimit
    background(255)
    minLimit = 3
    textFont(font)
    textAlign(CENTER)
    textSize(48)
    fill(0)
    text("type your name", width/2, height/3)
    text(getPlayerName(), width/2, height/2)
    if width/2-60 <= mouseX <= width/2+60 and 460 <= mouseY <= 485 or len(playerName) < minLimit:
        fill(225)
        text("begin", width/2, (height/5)*4)
        fill(0)
    else:
        fill(0)
        text("begin", width/2, (height/5)*4)
    if 35 <= mouseX <= 64 and 24 <= mouseY <= 48:
        fill(225)
        text("<", 50, 50)
        fill(0)
    else:
        fill(0)
        text("<", 50, 50)

def getPlayerName():
    global curKey, playerName
    curKey = ""
    return str("".join(playerName))

def helpMenu(): #help menu
    global helpmode, prevGamemode
    imageMode(CORNER)
    background(255)
    textFont(font)
    textAlign(CENTER)
    textSize(48)
    fill(0)
    if helpmode == "help1":
        help = loadImage("help1.jpg")
        image(help,0,60,830,450)
        stroke(255,0,0)
        line(539,209,575,209)
        stroke(0)
        if 700 <= mouseX <= 735 and 510 <= mouseY <= 540:
            fill(225)
            text(">", 720, 540)
            fill(0)
        else:
            fill(0)
            text(">", 720, 540)
    if helpmode == "help2":
        help = loadImage("help2.jpg")
        image(help,0,80,830,400)
    if 35 <= mouseX <= 64 and 24 <= mouseY <= 48:
        fill(225)
        text("<", 50, 50)
        fill(0)
    else:
        fill(0)
        text("<", 50, 50)

def scoresMenu(): #scores menu
    global highscoreDict, points, playerName, fromhighscore, tohighscore
    filename = 'highscores'
    infile = open(filename, 'rb')
    try:
        highscoreDict = pickle.load(infile)
    except EOFError:
        highscoreDict = {}
    infile.close()
    background(255)
    fill(0)
    textSize(30)
    textAlign(CENTER)
    text("Scores", width/5, 50)
    text("Name", (width/5)*2, 50)
    text("Date", (width/5)*3, 50)
    text("Time", (width/5)*4, 50)
    itemlist = highscoreDict.items()
    sortlist(itemlist)
    if len(itemlist) > 10:
        numloop = 10
    else:
        numloop = len(itemlist)
    for x in range(numloop):
        text(str(itemlist[x][1]), width/5, 100+50*x)
        namedatetimelist = itemlist[x][0].split(", ")
        text(str(namedatetimelist[0]), (width/5)*2, 100+50*x)
        text(str(namedatetimelist[1]), (width/5)*3, 100+50*x)
        text(str(namedatetimelist[2]), (width/5)*4, 100+50*x)
    textSize(48)
    if 35 <= mouseX <= 64 and 24 <= mouseY <= 48:
        fill(225)
        text("<", 50, 50)
        fill(0)
    else:
        fill(0)
        text("<", 50, 50)

def sortlist(itemlist):
    for z in range(len(itemlist)-1, 0, -1): #sorting by score
        for y in range(z):
            if itemlist[y][1] < itemlist[y+1][1]:
                itemlist[y], itemlist[y+1] = itemlist[y+1], itemlist[y]
    for z in range(len(itemlist)-1, 0, -1): #sorting by datetime
        for y in range(z):
            if itemlist[y][1] == itemlist[y+1][1]:
                datetimeobj1 = datetime.strptime(itemlist[y][0].split(", ", 1)[1], "%m/%d/%Y, %H:%M:%S")
                datetimeobj2 = datetime.strptime(itemlist[y+1][0].split(", ", 1)[1], "%m/%d/%Y, %H:%M:%S")
                if datetimeobj1 > datetimeobj2:
                    itemlist[y], itemlist[y+1] = itemlist[y+1], itemlist[y]
    return itemlist

def game():
    global wrongGuesses, fileInfo, guessWord, displayWord, gamemode
    background(255)
    textFont(font)
    textAlign(CENTER)
    textSize(48)
    fill(0)
    image(hangmanImage[wrongGuesses], width/5, height/4, 300, 300)
    strokeWeight(15)
    line(0, 300, width, 300)
    strokeWeight(1)
    for letter in range(len(displayWord)): #put correctly guessed letters on screen
        if displayWord[letter] != "_":
            text(displayWord[letter], (550-(len(displayWord)*40/2)+(40*letter)), 250)
        line((535-(len(displayWord)*40/2)+(40*letter)),250,(565-(len(displayWord)*40/2)+(40*letter)),250)
    textAlign(LEFT, BOTTOM)
    textSize(25)
    text("Points: "+str(points), 20, height-20)
    if wrongGuesses == guessLimit:
        gamemode = "end"
    textAlign(RIGHT, BOTTOM)
    if 735 <= mouseX <= 780 and 555 <= mouseY <= 575:
        fill(225)
    text("help",width-20, height-20)
    if 660 <= mouseX <= 720 and 555 <= mouseY <= 575:
        fill(225)
    else:
        fill(0)
    text("Menu",width-80, height-20)

def wordGenerator(): #get random guess word from list
    global displayWord, guessWord, worth, wordHint, gamemode
    if len(fileInfo) != 0:
        randWord = random.randint(0,len(fileInfo) - 1)
        guessWord = fileInfo[randWord][0]
        wordHint = fileInfo[randWord][1]
        displayWord = ["_"]*len(guessWord)
        fileInfo.pop(randWord) #pop word from list when it is guessed correctly
    elif len(fileInfo) == 0: #if there are no words left in the list, player won
        gamemode = "won"

def hintDisplay():  #if player clicks for hint, display hint
    textFont(font)
    textAlign(CENTER, CENTER)
    textSize(32)
    fill(0)
    if hintChosen:
        text("Click for Hint", 550, 30)
        text(wordHint, 550, 60)
    elif 450 <= mouseX <= 650 and 15 <= mouseY <= 50:
        fill(225)
        text("Click for Hint", 550, 30)
    else:
        fill(0)
        text("Click for Hint", 550, 30)

def keyboardDisplay(): #display letters
    global keyboard
    textFont(font)
    textAlign(CENTER, CENTER)
    textSize(48)
    for x in range(len(keyboard)): #displays the keyboard
        for y in range(len(keyboard[x])):
            if keyboard[x][y][1] == False:
                fill(225)
            else:
                fill(0)
            text(keyboard[x][y][0],40+width/2-((80*len(keyboard[x]))/2)+(80*y), 350+(80*x))

def endScreen():
    global guessWord, scoreadded
    textFont(font)
    textAlign(CENTER, CENTER)
    textSize(48)
    background(255)
    fill(0)
    text("The word was " + guessWord, width/2, height/5)
    text(getPlayerName()+", you lost!", width/2, (height/5)*2)
    text("Final Score: "+str(points), width/2, (height/5)*3)
    if 250 <= mouseX <= 550 and 470 <= mouseY <= 510:
        fill(225)
    text("Click to restart", width/2, (height/5)*4)
    if scoreadded == False:
        addscore()
        scoreadded = True

def wonScreen():
    global playerName, highscoreDict, points, scoreadded
    textFont(font)
    textAlign(CENTER, CENTER)
    textSize(48)
    background(255)
    fill(0)
    text(getPlayerName()+ ", you won!", width/2, height/3)
    text("Final Score: "+str(points), width/2, height/2)
    if 250 <= mouseX <= 550 and 390 <= mouseY <= 420:
        fill(225)
    text("Click to restart", width/2, height/3*2)
    if scoreadded == False:
        addscore()
        scoreadded = True

def addscore():
    global highscoreDict, points, playerName, fromhighscore, tohighscore
    filename = 'highscores'
    ##print("before open")
    infile = open(filename, 'rb')
    ##print("before load")
    try:
        highscoreDict = pickle.load(infile)
    except EOFError:
        highscoreDict = {}
    infile.close()
    itemlist = highscoreDict.items()
    if len(highscoreDict) < 10 or points > sortlist(itemlist)[9][1]:
        outfile = open(filename, 'wb')
        highscoreDict[str("".join(playerName))+", "+str(datetime.now().strftime("%m/%d/%Y, %H:%M:%S"))] = points
        if len(highscoreDict) > 10:
            itemlist = highscoreDict.items()
            del highscoreDict[sortlist(itemlist)[9][0]]
        pickle.dump(highscoreDict, outfile)
        outfile.close()

def restart(): #restarts the game
    global points, gamemode, playerName, wrongGuesses, keyboard, listWrongGuesses, listGuessed, hintChosen, scoreadded
    gamemode = "startMenu"
    playerName = []
    getFileInfo("hangmanwords.txt")
    wordGenerator()
    keyboard = [[['q', True],['w', True],['e', True],['r', True],['t', True],['y', True],['u', True],['i', True],['o', True],['p', True]],
    [['a', True],['s', True],['d', True],['f', True],['g', True],['h', True],['j', True],['k', True],['l', True]],
    [['z', True],['x', True],['c', True],['v', True],['b', True],['n', True],['m', True]]]
    wrongGuesses = 0
    listWrongGuesses = []
    listGuessed = []
    hintChosen = False
    scoreadded = False
    points = 0

def mousePressed():
    global helpmode, prevGamemode, gamemode, minLimit, wrongGuesses, keyboard, guessWord, listWrongGuesses, points, listGuessed, hintChosen, playerName, bloop, click
    #center coords of each letter on screen
    keyCoords = [[40, 350], [120, 350], [200, 350], [280, 350], [360, 350], [440, 350], [520, 350], [600, 350], [680, 350], [760, 350], [80, 430], [160, 430], [240, 430], [320, 430], [400, 430], [480, 430], [560, 430], [640, 430], [720, 430], [160, 510], [240, 510], [320, 510], [400, 510], [480, 510], [560, 510], [640, 510]]
    print(mouseX, mouseY)
    if gamemode == "startMenu" and mouseButton == LEFT:

        #if "start" clicked
        if width/2-50 <= mouseX <= width/2+50 and 200 <= mouseY <= 270:
            gamemode = "playerMenu"
            click = minim.loadFile("click.wav")
            click.play()

        #if "help" clicked
        if width/2-50 <= mouseX <= width/2+50 and 325 <= mouseY <= 380:
            gamemode = "helpMenu"
            helpmode = "help1"
            prevGamemode = "startMenu"
            print(gamemode)

        #if "scores clicked"
        if width/2-60 <= mouseX <= width/2+60 and 460 <= mouseY <= 485:
            gamemode = "scoresMenu"
            print("scores")

    if gamemode == "helpMenu":
        if 35 <= mouseX <= 64 and 24 <= mouseY <= 48:
            if helpmode == "help1":
                gamemode = prevGamemode
            if helpmode == "help2":
                gamemode = "helpMenu"
                helpmode = "help1"
        #if next arrow clicked in help menu
        if 700 <= mouseX <= 735 and 510 <= mouseY <= 540:
            helpmode = "help2"

    #if "begin" clicked
    if gamemode == "playerMenu" and mouseButton == LEFT:
        if width/2-60 <= mouseX <= width/2+60 and 460 <= mouseY <= 485:
            if len(playerName) >= minLimit:
                gamemode = "inGame"
                time.sleep(0.5)
        #if back arrow clicked
        if 35 <= mouseX <= 64 and 24 <= mouseY <= 48:
            gamemode = "startMenu"
            playerName = []

    if gamemode == "scoresMenu":
        if 35 <= mouseX <= 64 and 24 <= mouseY <= 48:
            gamemode = "startMenu"
    if gamemode == "inGame" and mouseButton == LEFT:
        for x in range(len(keyCoords)):
            if keyCoords[x][0]-20 <= mouseX <= keyCoords[x][0]+20 and keyCoords[x][1]-20 <= mouseY <= keyCoords[x][1]+20:
                if 0 <= x <= 9:
                    row = 0
                    column = x
                if 10 <= x <= 18:
                    row = 1
                    column = x - 10
                if 19 <= x <= 25:
                    row = 2
                    column = x - 19
                ###print("key "+str(x)+" clicked")
                if keyboard[row][column][1] == True:  #if letter clicked, turn it off and add letter to listGuessed[]
                    keyboard[row][column][1] = False
                    listGuessed.append(keyboard[row][column][0])
                for y in range(len(listGuessed)):
                    if listGuessed[y] in guessWord: #if clicked letter is in the guess word, add letter to displayWord[]
                        for z in range(guessWord.count(listGuessed[y])):
                            ###print("correct letter guessed")
                            displayWord[[i for i, n in enumerate(list(guessWord)) if n == listGuessed[y]][z]] = listGuessed[y]
                        if ''.join(displayWord) == guessWord: #if letters in displayWord[] match the guessWord, add points and generate new word, and reset keyboard, num wrong guesses, and list of guessed letters
                            bloop = minim.loadFile("correct.wav")
                            bloop.play()
                            if hintChosen == True:
                                points += int(round(len(guessWord)/2))
                            else:
                                points += len(guessWord)
                            wordGenerator()
                            keyboard = [[['q', True],['w', True],['e', True],['r', True],['t', True],['y', True],['u', True],['i', True],['o', True],['p', True]],
                            [['a', True],['s', True],['d', True],['f', True],['g', True],['h', True],['j', True],['k', True],['l', True]],
                            [['z', True],['x', True],['c', True],['v', True],['b', True],['n', True],['m', True]]]
                            wrongGuesses = 0
                            listWrongGuesses = []
                            listGuessed = []
                            hintChosen = False
                    elif listGuessed[y] not in listWrongGuesses:
                        listWrongGuesses.append(listGuessed[y])
                        wrongGuesses = len(listWrongGuesses)
                        ###print("wrong guesses: "+str(wrongGuesses))
                ###print(listGuessed)
                ###print(keyboard)
                ###print(displayWord)
            #if "click for hint" clicked
            if 450 <= mouseX <= 650 and 15 <= mouseY <= 50:
                hintChosen = True
        #if "help" in game mode clicked
        if 735 <= mouseX <= 780 and 555 <= mouseY <= 575:
            gamemode = "helpMenu"
            helpmode = "help1"
            prevGamemode = "inGame"
        #if "menu" in game mode clicked
        if 660 <= mouseX <= 720 and 555 <= mouseY <= 575:
            gamemode = "startMenu"
    if gamemode == "end":
        if 250 <= mouseX <= 550 and 470 <= mouseY <= 510: #if "click to restart" clicked
            restart()
    if gamemode == "won":
        if 250 <= mouseX <= 550 and 390 <= mouseY <= 420:
            restart()

def keyPressed():  #player name
    global gamemode, playerName, guessLimit
    nameLimit = 20
    validKeys = "abcdefghijklmnopqrstuvwxyz1234567890 "
    if gamemode == "playerMenu":
        if keyCode != SHIFT and key in validKeys and len(playerName) < nameLimit:
            curKey = key
            playerName.append(curKey)
            ###print(curKey)
        if key == BACKSPACE and len(playerName) > 0:
            playerName.pop()


def histogram(test):
    """Given a string representing a space separated lowercase letters, return a dictionary
    of the letter with the most repetition and containing the corresponding count.
    If several letters have the same occurrence, return all of them.

    Example:
    histogram('a b c') == {'a': 1, 'b': 1, 'c': 1}
    histogram('a b b a') == {'a': 2, 'b': 2}
    histogram('a b c a b') == {'a': 2, 'b': 2}
    histogram('b b b b a') == {'b': 4}
    histogram('') == {}

    """
    hist = {}
    for letter in test.split():
        hist[letter] = hist.get(letter, 0) + 1
    return hist

misc/Experiment results/Amazon CodeWhisperer/Original Experiment New Results/code_generation/111/prompt_111.py


"""empty message

Revision ID: 151d6d25be16
Revises: 5e352cc76d16
Create Date: 2020-08-21 16:38:59.387656

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '151d6d25be16'
down_revision = '5e352cc76d16'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('artists', sa.Column('seeking_description', sa.Text(), nullable=True))
    op.add_column('artists', sa.Column('seeking_venue', sa.Boolean(), nullable=False))
    op.alter_column('artists', 'genres',
               existing_type=sa.VARCHAR(length=120),
               nullable=False)
    op.create_unique_constraint(None, 'artists', ['facebook_link'])
    op.create_unique_constraint(None, 'artists', ['website_link'])
    op.create_unique_constraint(None, 'artists', ['phone'])
    op.create_unique_constraint(None, 'artists', ['name'])
    op.drop_column('artists', 'seeking_performance')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('artists', sa.Column('seeking_performance', sa.BOOLEAN(), autoincrement=False, nullable=False))
    op.drop_constraint(None, 'artists', type_='unique')
    op.drop_constraint(None, 'artists', type_='unique')
    op.drop_constraint(None, 'artists', type_='unique')
    op.drop_constraint(None, 'artists', type_='unique')
    op.alter_column('artists', 'genres',
               existing_type=sa.VARCHAR(length=120),
               nullable=True)
    op.drop_column('artists', 'seeking_venue')
    op.drop_column('artists', 'seeking_description')
    # ### end Alembic commands ###


import graphene

from ....page.models import Page
from ...tests.utils import get_graphql_content

def test_delete_pages(staff_api_client, page_list, permission_manage_pages):
    query = """
    mutation pageBulkDelete($ids: [ID]!) {
        pageBulkDelete(ids: $ids) {
            count
        }
    }
    """

    variables = {
        "ids": [graphene.Node.to_global_id("Page", page.id) for page in page_list]
    }
    response = staff_api_client.post_graphql(
        query, variables, permissions=[permission_manage_pages]
    )
    content = get_graphql_content(response)

    assert content["data"]["pageBulkDelete"]["count"] == len(page_list)
    assert not Page.objects.filter(id__in=[page.id for page in page_list]).exists()


from dataclasses import dataclass
from typing import List
from environs import Env

@dataclass
class TgBot:
    token: str
    admin_ids: List[int]
    use_redis: bool

@dataclass
class Misc:

    credentials_file: str

@dataclass
class Config:
    tg_bot: TgBot
    misc: Misc

def load_config(path: str = None):
    env = Env()
    env.read_env(path)

    return Config(
        tg_bot=TgBot(
            token = env.str("BOT_TOKEN"),
            admin_ids = list(map(int, env.list("ADMINS"))),
            use_redis=env.bool("USE_REDIS")
        ),
        misc=Misc(
            credentials_file = env.str("CREDENTIALS")
        )
    )


import sys
import numpy as np

from neural_network import NeuralNetwork
from ae import LATENT_OUPUT_LAYER, TEST_FILE, load_data, decode, print_row, to_col, test_row

def encoding_to_string(encoding):
    # return "".join(f"{digit}:{x[0]:.4f} " for digit, x in enumerate(encoding))
    max_idx = np.argmax(encoding)
    _str = ""
    for idx, val in enumerate(encoding):
        _str += f" [{idx}]{val[0]:.4f}"
        if idx == max_idx:
            _str += "<-"
    return _str

if __name__ == "__main__":
    # get the target digit and print it
    idx = int(sys.argv[1]) if len(sys.argv) > 1 else -1
    test_data = load_data(TEST_FILE, delimiter=",", dtype=int)
    print(f"printing data for row {idx} from {TEST_FILE}")
    print_row(test_data[idx])

    ae_nn = NeuralNetwork.load("ae.pkl")

    # run the target digit through the autoencoder and print the result
    digit, data = test_data[idx][0], test_data[idx][1:]
    output = ae_nn.forward_pass(to_col(data)) * 255
    row = [digit] + output.flatten().tolist()
    print_row(row)
    encoding = ae_nn._layer_inputs[LATENT_OUPUT_LAYER]
    print(f"encoding={encoding_to_string(encoding)}")

    max_idx = np.argmax(encoding)
    norm_encoding = encoding/encoding[max_idx][0]
    output = decode(ae_nn, norm_encoding) * 255
    row = [digit] + output.flatten().tolist()
    print(f"\n\nnomalized encoding = {encoding_to_string(norm_encoding)}")
    print_row(row)

    print("\n-------- enumerated decreasing normalized decodings --------\n")
    iters = 10
    dnorm_encoding = norm_encoding / iters
    for iter in range(iters):
        norm_encoding = norm_encoding - dnorm_encoding
        norm_encoding[max_idx] = 1
        output = decode(ae_nn, norm_encoding) * 255
        row = [iter] + output.flatten().tolist()
        print(f"norm_encoding iter {iter} = {encoding_to_string(norm_encoding)}")
        print_row(row)

    # print("\n-------- enumerated decodings --------\n")
    # for digit in range(10):
    #     # encoding = np.zeros((10, 1)) + 3.5
    #     # encoding[digit] = 8
    #     encoding = np.zeros((10, 1))
    #     encoding[digit] = 1
    #     output = decode(ae_nn, encoding) * 255
    #     row = [digit] + output.flatten().tolist()
    #     print(f"encoding for digit {digit} = {encoding_to_string(encoding)}")
    #     print_row(row)


from typing import Protocol, List, Iterable, Type
from pydantic import BaseModel
from dataclasses import dataclass, field
from sqlalchemy.orm import DeclarativeBase, sessionmaker
from sqlalchemy import create_engine
from tqdm import tqdm
from abcs import StateCampaignFinanceConfigs
from logger import Logger
from sqlalchemy.dialects.postgresql import insert

@dataclass
class PostgresLoader:
    _base: Type[DeclarativeBase]
    table: Type[DeclarativeBase] = field(init=False)
    models: Iterable[DeclarativeBase] = field(init=False)
    __logger: Logger = field(init=False)

    def __post_init__(self):
        self.__logger = Logger(PostgresLoader.__class__.__name__)

    def build(self, engine: create_engine):
        self._base.metadata.create_all(engine)
        print("Created Postgres tables")

    def create(self, values: List[dict], table: Type[DeclarativeBase]):
        self.table = table

        _models = []
        for v in tqdm(values, desc=f"Creating {table.__tablename__} models"):
            _v = dict(v)
            _models.append(table(**_v))
        self.models = iter(_models)
        return self.table, self.models

    def load(self, session: sessionmaker):

        def upload_records(records):
            _errors = []
            with session() as upload:
                try:
                    upload.add_all(records)
                    upload.commit()
                except Exception as e:
                    upload.rollback()
                    self.__logger.error(f"Error: {e}")
                    _errors.append(e)
            return _errors
        errors = []
        _queue = []
        for model in tqdm(self.models, desc=f"Loading to {self.table.__tablename__}"):
            _queue.append(model)
            if len(_queue) == 16000:
                _errors = upload_records(_queue)
                _queue = []
                errors.append(_errors)
        _errors = upload_records(_queue)
        errors.append(_errors)
        return errors

    def _get_model(self, _validator: BaseModel, _config: StateCampaignFinanceConfigs):
        if _validator.__name__ == "TECExpense":
            _model = _config.EXPENSE_MODEL
        elif _validator.__name__ == "TECContribution":
            _model = _config.CONTRIBUTION_MODEL
        elif _validator.__name__ == "TECFiler":
            _model = _config.FILERS_MODEL
        else:
            raise ValueError(f"Invalid type: {_validator.__name__}")
        return _model

    # def insert_to_db(self, _list: list, _validator: BaseModel, _config: StateCampaignFinanceConfigs):
    #     _model = self._get_model(_validator, _config)
    #     with _config.DB_SESSION() as upload:
    #         _list = [dict(x) for x in _list]
    #         _add = insert(_model).values(_list).on_conflict_do_nothing()
    #         upload.execute(_add)
    #         upload.commit()

    def add_to_db(self, _list: list,  _validator: BaseModel, _config: StateCampaignFinanceConfigs):
        self.__logger.debug(f"Called _load_to_db() for {_validator}...")
        _model = self._get_model(_validator, _config)
        _loader = PostgresLoader(_config.DB_BASE)
        _loader.build(engine=_config.DB_ENGINE)
        _loader.create(values=_list, table=_model)
        _loader.load(session=_config.DB_SESSION)
        self.__logger.debug(f"Loaded {len(_list):,} records to database...")


#!/usr/bin/env python3
import random

import utils

def boxEmUp(args):
    filedata = ""
    if args.infile:
        fileopen = open(args.infile, 'r')
        filedata = fileopen.read()
        fileopen.close()

    if args.encoder == "base64":
        s = utils.standardEncoding(filedata)
        filedata = s.baseE64()
    if args.encoder == "hex":
        s = utils.standardEncoding(filedata)
        filedata = s.hexE()

    if args.obfu == "ranenc":
        re = utils.encoderGenrator(filedata)
        filedata = re.codeGenrator()
    if args.obfu == "strcla":
        sc = utils.stringObjuscator(filedata)
        filedata = sc.obfuscat()

    if args.packer:
        t = utils.packer(filedata)
        filedata = t.returnString()

    if args.encryption:
        ec = utils.basicEncryption(filedata)
        filedata = ec.encrypt()

    if args.random:
        a = [1,2,3,4,5,6]
        random.shuffle(a)

        for x in a:
            if x == 1:
                s = utils.standardEncoding(filedata)
                filedata = s.baseE64()
            elif x == 2:
                s = utils.standardEncoding(filedata)
                filedata = s.hexE()
            elif x == 3:
                re = utils.encoderGenrator(filedata)
                filedata = re.codeGenrator()
            elif x == 4:
                sc = utils.stringObjuscator(filedata)
                filedata = sc.obfuscat()
            elif x == 5:
                t = utils.packer(filedata)
                filedata = t.returnString()
            elif x == 6:
                ec = utils.basicEncryption(filedata)
                filedata = ec.encrypt()
    if args.outfile:
        with open(args.outfile, 'w') as file:
            file.write(filedata)
    else:
        print(filedata)

def main():
    print("\n\tJack In The Box\nby Michael Provenzano")
    print("        \n\n\n                 What is anti-malware.\n\n\n !!! PYTHON file ONLY !!!")
    arg = utils.age()
    args = arg.get_args()

    if args.encoders:
        arg.enco()
        exit()

    if args.obfus:
        arg.obfuscators()
        exit()

    if args.infile:
        boxEmUp(args)

if __name__ == "__main__":
    main()


import json
import os
import shutil
import tempfile

from scilpy.io.fetcher import get_testing_files_dict, fetch_data, get_home

# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tracking.zip'])
tmp_dir = tempfile.TemporaryDirectory()

def test_help_option(script_runner):
    ret = script_runner.run('scil_score_bundles.py',
                            '--help')
    assert ret.success

def test_score_bundles(script_runner):
    os.chdir(os.path.expanduser(tmp_dir.name))
    in_tractogram = os.path.join(get_home(), 'tracking', 'pft.trk')

    # Pretend we have our segmented bundles on disk
    shutil.copyfile(in_tractogram, './NC.trk')
    os.mkdir('./segmented_VB')
    shutil.copyfile(in_tractogram, './segmented_VB/bundle1_VS.trk')
    shutil.copyfile(in_tractogram, './segmented_VB/bundle2_VS.trk')
    os.mkdir('./segmented_IB')
    shutil.copyfile(in_tractogram, './segmented_IB/roi1_roi2_VS.trk')

    json_contents = {
        "bundle1": {
            "gt_mask": os.path.join(get_home(), 'tracking',
                                    'seeding_mask.nii.gz'),
        },
        "bundle2": {
            "gt_mask": os.path.join(get_home(), 'tracking',
                                    'seeding_mask.nii.gz'),
        }
    }
    with open(os.path.join("config_file.json"), "w") as f:
        json.dump(json_contents, f)

    ret = script_runner.run('scil_score_bundles.py',
                            "config_file.json", "./", '--no_bbox_check')

    assert ret.success


class Solution:
    def frequencySort(self, s: str) -> str:
        freq = collections.Counter(s)

        # put c * f together
        # for c, f in freq in reverse order of f

        # bucket[i] = \sum_{f==i} c * f
        bucket = [''] * (max(freq.values()))

        for c, f in freq.items():
            bucket[f - 1] += c * f

        return ''.join(reversed(bucket))


from pyspark.sql import SparkSession
from pyspark.conf import SparkConf

conf = SparkConf().setAppName("Counter").setMaster("spark://spark:7077")

spark = SparkSession.builder.config(conf=conf).getOrCreate()

sc = spark.sparkContext

text_file = sc.textFile("/tmp/data/lorem.txt")

counts = text_file.flatMap(lambda linea: linea.split(" ")).countByValue()

for word, count in counts.items():
    print("------------------")
    print("{} : {}".format(word, count))

sc.stop()


# Definimos nuestra excepción personalizada
class SaldoInsuficienteError(Exception):
    def __init__(self, saldo_actual, cantidad_retirada):
        super().__init__(f"Saldo insuficiente. Saldo actual: ${saldo_actual}. Intento de retiro: ${cantidad_retirada}.")
        self.saldo_actual = saldo_actual
        self.cantidad_retirada = cantidad_retirada

class CuentaBancaria:
    def __init__(self, titular, saldo_inicial=0):
        self.titular = titular
        self.saldo = saldo_inicial

    def depositar(self, cantidad):
        self.saldo += cantidad
        return self.saldo

    def retirar(self, cantidad):
        if cantidad > self.saldo:
            raise SaldoInsuficienteError(self.saldo, cantidad)
        self.saldo -= cantidad
        return self.saldo

# Crear una cuenta y realizar algunas operaciones
try:
    cuenta_de_juan = CuentaBancaria("Juan", 100)
    print(f"Saldo inicial: ${cuenta_de_juan.saldo}")
    cuenta_de_juan.depositar(50)
    print(f"Saldo después del depósito: ${cuenta_de_juan.saldo}")
    cuenta_de_juan.retirar(200)  # Esto debería lanzar nuestra excepción personalizada
except SaldoInsuficienteError as e:
    print(f"Error: {e}")


'''
    滑块控件（QSilder）
'''

import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

class QSliderDemo(QWidget):
    def __init__(self):
        super(QSliderDemo, self).__init__()
        self.initUI()

    def initUI(self):
        self.setWindowTitle('滑块控件演示')
        self.resize(800, 800)

        layout = QVBoxLayout()
        self.label = QLabel('你好，PyQt5')
        self.label.setAlignment(Qt.AlignCenter)

        layout.addWidget(self.label)

        self.silder = QSlider(Qt.Horizontal)
        # 设置最小值
        self.silder.setMinimum(12)
        # 设置最大值
        self.silder.setMaximum(48)
        # 设置步长
        self.silder.setSingleStep(3)

        # 设置当前值
        self.silder.setValue(18)

        # 设置刻度的位置，刻度在下方
        self.silder.setTickPosition(QSlider.TicksBelow)
        # 设置刻度的间隔
        self.silder.setTickInterval(6)

        layout.addWidget(self.silder)

        self.silder.valueChanged.connect(self.valueChange)

        self.setLayout(layout)

    def valueChange(self):
        print('当前值：%s' % self.silder.value())
        size = self.silder.value()
        self.label.setFont(QFont('Arial', size))

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = QSliderDemo()
    main.show()

    sys.exit(app.exec_())


import csv
import pathlib

def main():
    rajs = set()
    for f in pathlib.Path('./results').glob('*_verification.csv'):
        rajs.add((f.name).split('_')[0])

    for raj in rajs:
        csv_data_list = []
        with open(f'./results/{raj}_verification.csv', 'r', newline='') as csvfile:
            csv_data = csv.reader(csvfile, delimiter=';', quotechar='"')
            next(csv_data)
            for row in csv_data:
                csv_data_list.append(row)

        d = {}
        for row in csv_data_list:
            month_value = row[2][:7]
            err_code_value = row[36]
            key = f'{month_value}_{err_code_value}'
            if key not in d:
                d[key] = [0, 0]
                d[month_value] = [0, 0]

        for row in csv_data_list:
            key = f'{row[2][:7]}_{row[36]}'
            d[key][0] += 1
            d[row[2][:7]][0] += 1
            if len(row) >= 61 and row[61] == 'P':
                d[key][1] += 1
                d[row[2][:7]][1] += 1

        arr = [['Місяць', 'Код помилки', 'Кількість рекомендацій надано',
                'Кількість рекомендацій опрацьовано', '%']]
        for k, v in sorted(d.items()):
            if len(k) == 7:
                arr.append([k, 'Загальна', v[0], v[1],
                           f'{round(v[1]/v[0]*100)}%'])
            else:
                arr.append([k.split('_')[0], k.split('_')[1],
                           v[0], v[1], f'{round(v[1]/v[0]*100)}%'])

        with open(f'./results/{raj}_report.csv', 'w', newline='') as csvfile:
            writer = csv.writer(csvfile, delimiter=';', quotechar='"')
            for row in arr:
                writer.writerow(row)

if __name__ == '__main__':
    main()


import pandas as pd
import re
import string
import numpy as np
import mywordtokenizer
from wordSenseByContext import SenseContextWordDict
from nltk.tokenize import sent_tokenize

def createSentimentDF(filename):
    sentiment_df = pd.read_csv(filename, index_col='Word')
    sentiment_df = sentiment_df[['V.Mean.Sum', 'A.Mean.Sum', 'D.Mean.Sum']]
    sentiment_df = sentiment_df.rename(columns={'V.Mean.Sum': 'Valence',
                                                'A.Mean.Sum': 'Arousal',
                                                'D.Mean.Sum': 'Dominance'})
    return sentiment_df

def gutenberg_iterator(filename):
    """Yields paragraphs (as defined simply by multiple
    newlines in a row).

    Parameters
    ----------
    filename : str
        Full path to the file.

    Yields
    ------
    multiline str

    """
    with open(filename) as f:
        contents = f.read()
    for para in re.split(r"[\n\s*]{2,}", contents):
        yield para

def comparison_table(paragraphstring, myDict, sentiment_df):
    """Create a table that represents arousal, valence, and dominance ratings for words and their most frequent
    alternatives across time within a paragraph.

    Parameters
    ----------
    paragraphstring : str
        The string representing the paragraph to convert into a table.

    Returns
    -------
    a dataframe with containing frequency, arousal, valence, and dominance ratings for words and their most
    frequent alternatives. The index numbers in this df represent the word's position in the sentence. Any number
    that is not available will be assigned np.nan.

    """
    paragraph = sent_tokenize(paragraphstring)

    comparison_table_df = pd.DataFrame(columns=['Word', 'WordA', 'WordV', 'WordD', 'MostFreqAlt',
                                                'AltA', 'AltV', 'AltD'])

    for sentstring in paragraph:
        sentence = mywordtokenizer.simple(sentstring)
        for word in sentence:
            newLine = {'Word': word}      # starts a line to be updated with all known information

            if sentiment_df.index.contains(word):
                newLine['WordA'] = sentiment_df.at[word, 'Arousal']
                newLine['WordV'] = sentiment_df.at[word, 'Valence']
                newLine['WordD'] = sentiment_df.at[word, 'Dominance']

            mostFreqAlt = myDict.mostFrequentAlternative(word, sentence)
            if word != mostFreqAlt and not mostFreqAlt is None:
                newLine['MostFreqAlt'] = mostFreqAlt
                if sentiment_df.index.contains(mostFreqAlt):
                    newLine['AltA'] = sentiment_df.at[mostFreqAlt, 'Arousal']
                    newLine['AltV'] = sentiment_df.at[mostFreqAlt, 'Valence']
                    newLine['AltD'] = sentiment_df.at[mostFreqAlt, 'Dominance']

            comparison_table_df = comparison_table_df.append(newLine, ignore_index=True) # add updated line to data frame

    return comparison_table_df

def comparison_table_available_values(table):
    """Update a table with arousal, valence, and dominance ratings for words and their most frequent
    alternatives across time within a paragraph to include only lines that have semantic dimension ratings for both
    the word and a known most frequent alternative.

    Parameters
    ----------
    table : a data frame
        The data frame representing arousal, valence, and dominance ratings for words and their most frequent
        alternatives across time within a paragraph

    Returns
    -------
    a dataframe without unknown ratings for semantic dimensions

    """
    table = table[table.WordA.notnull() &
                  table.WordV.notnull() &
                  table.WordD.notnull() &
                  table.AltA.notnull() &
                  table.AltV.notnull() &
                  table.AltD.notnull()]
    return table

def biggest_differences_words(prunedTable):
    """ Finds the words that are most different from their most frequent alternative across each semantic dimension

    Parameters
    ----------
    prunedTable : a data frame
        The data frame representing arousal, valence, and dominance ratings for words and their most frequent
        alternatives across time within a paragraph

    Returns
    -------
    a dictionary mapping from a semantic dimension to row indexing information about the word with the greatest
    difference for that dimension

    """
    prunedTable = prunedTable.assign(absADiff = (prunedTable['WordA'] - prunedTable['AltA']).abs(),
                                     absVDiff = (prunedTable['WordV'] - prunedTable['AltV']).abs(),
                                     absDDiff = (prunedTable['WordD'] - prunedTable['AltD']).abs())
    biggestDifferencesWords = {'Arousal': prunedTable.loc[prunedTable['absADiff'].idxmax()],
                               'Valence': prunedTable.loc[prunedTable['absVDiff'].idxmax()],
                               'Dominance': prunedTable.loc[prunedTable['absDDiff'].idxmax()]}
    return biggestDifferencesWords

def paragraphAverages(filename, myDict, sentiment_df, stop = -1):
    """Create a table that represents paragraphs' average arousal, valence, and dominance ratings for words and
    their most frequent alternatives across a given text.

    Parameters
    ----------
    filename : string
        The string representing the file name to be read

    (optional): int
        the number of paragraphs the user wants to be measured. Useful, if you don't want to look at the entire file
        but say the first 20 paragraphs. (reduces waiting time). the default is to process everything.

    Returns
    -------
    a dataframe with paragraphs' average arousal, valence, and dominance ratings for words and
    their most frequent alternatives across a given text

    """
    avgs = pd.DataFrame(columns=['WordAAvg', 'WordVAvg', 'WordDAvg', 'AltAAvg', 'AltVAvg','AltDAvg'])
    file_iterator = gutenberg_iterator(filename)
    paragraphNum = 0
    for paragraphstring in file_iterator:
        if stop != -1 and paragraphNum >= stop:
            return avgs
        table = comparison_table(paragraphstring, myDict, sentiment_df)
        availableValTable = comparison_table_available_values(table)
        newLine = {'WordAAvg': availableValTable['WordA'].mean(),
                   'WordVAvg': availableValTable['WordV'].mean(),
                   'WordDAvg': availableValTable['WordD'].mean(),
                   'AltAAvg': availableValTable['AltA'].mean(),
                   'AltVAvg': availableValTable['AltV'].mean(),
                   'AltDAvg': availableValTable['AltD'].mean()}
        avgs = avgs.append(newLine, ignore_index=True)
        paragraphNum+=1
    return avgs

def biggest_differences_paragraphs(table):
    """ Finds the paragraphs with greatest average differences between words and their most frequent alternative
        across each semantic dimension

    Parameters
    ----------
    table : a data frame
        The data frame representing average a paragraph's arousal, valence, and dominance ratings for words and
        their most frequent alternatives across time in a text

    Returns
    -------
    a dictionary mapping from a semantic dimension to a row indexing information about the paragraph with the greatest
    difference for that dimension

    """
    table = table.assign(absAAvgDiff = (table['WordAAvg'] - table['AltAAvg']).abs(),
                         absVAvgDiff = (table['WordVAvg'] - table['AltVAvg']).abs(),
                         absDAvgDiff = (table['WordDAvg'] - table['AltDAvg']).abs())
    biggestDifferencesParagraphs = {'Arousal': table.loc[table['absAAvgDiff'].idxmax()],
                                    'Valence': table.loc[table['absVAvgDiff'].idxmax()],
                                    'Dominance': table.loc[table['absDAvgDiff'].idxmax()]}
    return biggestDifferencesParagraphs

"""===================================================================
Place all function calls below the following conditional so that they
are called only if this module is called with

`python ling278_assign02.py`

No functions should execute if it is instead imported with

import ling278_assign02

in the interactive shell.
"""

if __name__ == '__main__':
    pass


# Based on the beautiful tutorial by John from Codemy.com (https://www.youtube.com/c/Codemycom)
# freeCodeCamp.org (2019) Tkinter Course - Create Graphic User Interfaces in Python Tutorial https://www.youtube.com/watch?v=YXPyB4XeYLA

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
root.geometry("400x400")

def show_selection():
    label = Label(root, text=var.get()).pack()

#var = IntVar()
var = StringVar()
c = Checkbutton(root, text="Check if you want it super size", variable=var, onvalue="Supersize", offvalue="Regular")
c.deselect()
c.pack()

button = Button(root, text="show selection", command=show_selection).pack()

root.mainloop()


import cv2
import numpy as np

def nothing(x):
	pass

cv2.namedWindow('Color Capture')

#Create TrackBars
cv2.createTrackbar('M1', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('S1', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('V1', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('M2', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('S2', 'Color Capture', 0, 255, nothing)
cv2.createTrackbar('V2', 'Color Capture', 0, 255, nothing)

frame = cv2.imread('test2.jpg')
frame = cv2.resize(frame,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)

while(1):

	cv2.imshow('Color Capture', frame)

	hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

	if cv2.waitKey(1) & 0xFF == ord('q'):
		break

	m1 = cv2.getTrackbarPos('M1', 'Color Capture')
	s1 = cv2.getTrackbarPos('S1', 'Color Capture')
	v1 = cv2.getTrackbarPos('V1', 'Color Capture')

	m2 = cv2.getTrackbarPos('M2', 'Color Capture')
	s2 = cv2.getTrackbarPos('S2', 'Color Capture')
	v2 = cv2.getTrackbarPos('V2', 'Color Capture')

	lower_color=np.array([m1, s1, v1])
	upper_color=np.array([m2, s2, v2])
	#apply mask
	mask = cv2.inRange(hsv, lower_color, upper_color)
	res = cv2.bitwise_and(frame, frame, mask=mask)
	#show the result
	cv2.imshow('res', res)
file.close()
cap.release()
cv2.destroyAllWindows()