import asyncio
import logging
from typing import Type, Optional
from uuid import UUID

import aiohttp
from fastapi import Depends
from fastapi import Request
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession

from api.authenticator import Authenticator
from lib.db.models.mixins.filtermixin import FilterParam
from api.settings import settings
from lib.db.dbasync import redis, async_maker
from lib.messenger import Messenger
from lib.db.dbsync import BaseMixin
from lib.models import BaseModel
from lib.db.redis import rpc

default_authenticator = Authenticator(
    redis,
    session_expiration=48 * 60 * 60,
    session_cookie_name=settings.session_cookie_name,
)

messenger = Messenger(redis)

def get_authenticator() -> Authenticator:
    return default_authenticator

def get_dc_rpc_client():
    return rpc.Client("discord", redis, timeout=10)

_http_session: Optional[aiohttp.ClientSession] = None

def get_http_session():
    return _http_session

def set_http_session(http_session: aiohttp.ClientSession):
    global _http_session
    _http_session = http_session

async def get_db() -> AsyncSession:
    logging.info("Creating session")
    db: AsyncSession = async_maker()
    # The cleanup code has to be shielded, see:
    # https://github.com/tiangolo/fastapi/issues/4719
    try:
        yield db
    except SQLAlchemyError:
        await asyncio.shield(db.rollback())
    finally:
        await asyncio.shield(db.close())

async def get_user_id(
    request: Request, authenticator=Depends(get_authenticator)
) -> UUID:
    return await authenticator.verify_id(request)

def get_messenger():
    return messenger

class FilterQueryParamsDep:
    def __init__(self, table: Type[BaseMixin], model: Type[BaseModel]):
        self.table = table
        self.model = model

    def __call__(self, request: Request):
        filters = []
        for key in request.query_params.keys():
            try:
                filters.append(
                    FilterParam.parse(
                        key, request.query_params.getlist(key), self.table, self.model
                    )
                )
            except ValueError:
                continue
        return filters


# 从客户端远程执行服务器命令
import subprocess
res = subprocess.Popen(
    "dir",                   # 在终端运行的命令
    shell=True,              # 新开一个终端
    stdout=subprocess.PIPE,  # 执行完命令, 将正确输出放到一个管道里
    stderr=subprocess.PIPE,  # 将错误输出放到一个管道里
)
result = res.stdout.read()   # 拿到的是 bytes 格式的字符
result= str(result,encoding="gbk")  # 在windows需要使用gbk编码,linux和mac上是"utf-8"
print(result)


"""

"""

def obtener_detalle(tipo):
    """ """

    lista1 = ["aprobado", "reprobado"]
    lista2 = ["Usted fue aprobado en el curso", "Usted fue reprobado en el curso"]

    for d in range(0, len(lista1)):
        if lista1[d] == tipo:
            return lista2[d]
    return "tipo equivocado"

def obtener_detalle_dos(tipo):
    """ """

    lista1 = ["aprobado", "reprobado"]
    lista2 = ["Usted fue aprobado en el curso", "Usted fue reprobado en el curso"]
    lista3 = zip(lista1, lista2)
    for d, e in lista3:
        if d == tipo:
            return e
    return "tipo equivocado"

if __name__ == "__main__":
    print("Inicio de proceso")
    # print(obtener_detalle("aprobado"))
    print(obtener_detalle_dos("aprobado2"))


#==============================================================================
# REAL LIFE CLASSIFICATION
#==============================================================================
import tensorflow as tf
from keras.applications import imagenet_utils
from keras.applications import VGG16
from keras.applications import ResNet50
import cv2, threading
import numpy as np

# Initialize global variables to be used by the classification thread
# and load up the network and save it as a tensorflow graph
frame_to_predict = None
classification = True
label = ''
score = .0

print('Loading network...')
# model = VGG16(weights='imagenet')
model = ResNet50(weights='imagenet')
graph = tf.get_default_graph()
print('Network loaded successfully!')

class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        global label
        global frame_to_predict
        global classification
        global model
        global graph
        global score

        with graph.as_default():

            while classification is True:
                if frame_to_predict is not None:
                    frame_to_predict = cv2.cvtColor(frame_to_predict, cv2.COLOR_BGR2RGB).astype(np.float32)
                    frame_to_predict = frame_to_predict.reshape((1, ) + frame_to_predict.shape)
                    frame_to_predict = imagenet_utils.preprocess_input(frame_to_predict)
                    predictions = model.predict(frame_to_predict)
                    (imageID, label, score) = imagenet_utils.decode_predictions(predictions)[0][0]

# Start a keras thread which will classify the frame returned by openCV
keras_thread = MyThread()
keras_thread.start()

# Initialize OpenCV video captue
video_capture = cv2.VideoCapture(0) # Set to 1 for front camera
video_capture.set(4, 800) # Width
video_capture.set(5, 600) # Height

# Start the video capture loop
while (True):

    # Get the original frame from video capture
    ret, original_frame = video_capture.read()
    # Resize the frame to fit the imageNet default input size
    frame_to_predict = cv2.resize(original_frame, (224, 224))

    # Add text label and network score to the video captue
    cv2.putText(original_frame, "Label: %s | Score: %.2f" % (label, score),
                (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
    # Display the video
    cv2.imshow("Classification", original_frame)

    # Hit q or esc key to exit
    if (cv2.waitKey(1) & 0xFF == ord('q')):
        break;

classification = False
video_capture.release()
cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
from django.conf import settings

class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
            name='Log',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('fecha', models.DateTimeField(auto_now_add=True)),
                ('status', models.CharField(max_length=25)),
            ],
            options={
                'verbose_name': 'Log',
                'verbose_name_plural': 'Logs',
            },
            bases=(models.Model,),
        ),
        migrations.CreateModel(
            name='Suscripcion',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('fecha', models.DateTimeField(auto_now_add=True)),
                ('id_cliente', models.CharField(max_length=25)),
                ('id_suscripcion', models.CharField(max_length=25)),
                ('status', models.CharField(max_length=15)),
                ('activo', models.BooleanField(default=False)),
                ('usuario', models.OneToOneField(to=settings.AUTH_USER_MODEL)),
            ],
            options={
                'verbose_name': 'Suscripci\xf3n',
                'verbose_name_plural': 'Suscripciones',
            },
            bases=(models.Model,),
        ),
        migrations.AddField(
            model_name='log',
            name='suscripcion',
            field=models.ForeignKey(related_name='logs', to='suscripciones.Suscripcion'),
            preserve_default=True,
        ),
    ]


# Exercício 5
compactar = [32, 33, 34, 34, 34, 34, 34, 34, 34, 35, 37, 37, 37, 37, 37, 37, 35, 34, 35]
compactado = []
byte_spc = 'RPT'
contador = 1
for valor in compactar:
    contador = compactar.count(valor)
    if valor not in compactado and contador > 1:
        compactado.append(byte_spc)
        compactado.append(valor)
        compactado.append(contador)
        contador = 1
    elif contador == 1:
        compactado.append(valor)
print('Dados compactados:', compactado)


import usb.core

# Inspired by ebswift, https://www.ebswift.com/reverse-engineering-spl-usb.html

# The Wensn WS1381 answers these bRequests
# 1 seems to be constant - array of 2 bytes returned
# 2 readMode - array of 1 byte returned
# 3 setMode - array of 1 byte returned
# 4 read SPL - array of 2 bytes returned
# 82 array of 4 bytes returned

ranges = ["30-80", "40-90", "50-100", "60-110", "70-120", "80-130", "30-130"]
speeds = ["fast", "slow"]
weights = ["A", "C"]
maxModes = ["instant", "max"]

def connect():
    dev = usb.core.find(idVendor=0x16c0, idProduct=0x5dc)
    assert dev is not None
    print(dev)
    return dev

def readBRequest(dev, bRequest):
    ret = dev.ctrl_transfer(0xC0, bRequest, 0, 10, 200)
    print(ret),
    for elem in ret:
        print(format(elem, '#010b')),
    print

def readMode(dev):
    ret = dev.ctrl_transfer(0xC0, 2, 0, 10, 200)
    #print(ret)
    #print(format(ret[0], '#010b'))

    rangeN = (ret[0]&7) # bits 1,2,3 in ret[0] return rangeN from 0 to 6
    weightN = (ret[0]&8)>>3 # bit 3 in ret[0] returns weight
    speedN = (ret[0]&16)>>4 # bit 4 in ret[0] returns speed
    maxModeN = (ret[0]&32)>>5 # bit 5 in ret[0] returns maxMode

    return(ranges[rangeN], weights[weightN],
           speeds[speedN], maxModes[maxModeN])

def setMode(dev, range="30-80", speed="slow", weight="A", maxMode="instant"):
    rangeN = ranges[0:4].index(range)
    # For rangeN, setting over USB supports only 2 bits of range,
    #   although 7 values (0 to 6) can be set with buttons on unit.
    speedN = speeds.index(speed)
    weightN = weights.index(weight)
    maxModeN = maxModes.index(maxMode)

    print("setMode: range:%s weight:%s speed:%s maxMode:%s" %
          (range, weight, speed, maxMode))
    #wvalue = rangeN | weightN<<3 | speedN<<4 | maxModeN<<5
    wvalue = (rangeN&3) | (weightN&1)<<3 | (speedN&1)<<4 | (maxModeN&1)<<5
    # Function of bits 6 and 7 is unknown (nothing?)

    dev.ctrl_transfer(0xC0, 3, wvalue, 0, 200)

peak = 0
def readSPL(dev):
    global peak

    ret = dev.ctrl_transfer(0xC0, 4, 0, 10, 200) # wvalue (3rd arg) is ignored
    #print(ret)
    #print(format(ret[1], '#010b'))

    rangeN = (ret[1]&28)>>2 # bits 2,3,4 in ret[1] return rangeN from 0 to 6
    weightN = (ret[1]&32)>>5 # bit 5 in ret[1] return weightN
    speedN = (ret[1]&64)>>6 # bit 6 in ret[1] return speedN
    # bit 7 seems to alternate every 1 second?

    dB = (ret[0] + ((ret[1] & 3) * 256)) * 0.1 + 30
    if dB > peak:
        peak = dB
    return(dB, ranges[rangeN], weights[weightN], speeds[speedN])

if __name__ == "__main__":
    import logroll
    import datetime
    import time

    # connect to WS1381 over USB
    dev = connect()

    # set default modes: "A" weighting, "slow"
    setMode(dev)

    log = logroll.LogRoll(logdir="logs")
    while True:
        now = datetime.datetime.now()
        # roll over to a new log whenever the filename changes - in this case, every hour.
        log.open_or_reopen(now.strftime('%Y-%m-%d-%H-%M.log'))

        dB, range, weight, speed = readSPL(dev)
        print("%.2f,%s,%s,%s"
              % (dB, weight, speed, now.strftime('%Y,%m,%d,%H,%M,%S')),
              file = log.fp)
        print("%.2f,%s,%s,%s"
              % (dB, weight, speed, now.strftime('%Y,%m,%d,%H,%M,%S')))

        log.fp.flush()
        time.sleep(1)


"""
:mod:`maputils` -- mapping functions
====================================

.. module:: maputils
    :synopsis: Mapping functions.

.. moduleauthor:: Craig Arthur <craig.arthur@ga.gov.au>

Contains mapping functions that operate on arrays. Supercedes some of
the functions lying around in some unusual places (like DataProcess).

"""

import logging

import numpy as np
import math
from . import metutils
import warnings
try:
    from . import fmaputils
except ImportError:
    warnings.warn("Compiled maputils not found - defaulting to slower python wind models")

# C weave code disabled for now.  The code speeds up the windfield interface module by ~6% but
# does not appear to work on some systems.
#from scipy import weave
#from scipy.weave import converters

logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())

def xy2r(x, y):
    """
    Given x and y arrays, returns the distance between consecutive
    elements.

    :param x: x-coordinate of points.
    :param y: y-coordinate of points.
    :type x: :class:`numpy.ndarray`
    :type y: :class:`numpy.ndarray`

    :returns: Distance (in native units) between consecutive points.
    :rtype: :class:`numpy.ndarray`
    """

    #if len(x) != len(y):
    #   raise ArrayMismatch, "Input array sizes do not match"
    return np.sqrt(x**2 + y**2)

def latLon2Azi(lat, lon, ieast=1, azimuth=0, wantdeg=True):
    """
    Returns the bearing and distance (in km) between consecutive
    members of the array pair (lat,lon).

    :param lat: Latitudes of positions.
    :param lon: Longitudes of positions.
    :param int ieast: 1 for longitudes increasing towards East, -1 for
                      longitudes increasing towards West (default 1).
    :param float azimuth: Local coordinate system constructed with origin at
                          latr,lonr, X axis ('North') in direction of azimuth,
                          and Y axis such that X x Y = Z(down)
                          when going from (lat,lon) to (x,y) (default 0).
    :param boolean wantdeg: If ``True`` return bearings as degrees, not radians.

    :returns: azimuth (+ve clockwise from north) and distance (in km).

    """
    #if len(lat) != len(lon):
    #   raise ArrayMismatch, "Input array sizes do not match"

    xr = 0
    yr = 0

    yn, xe = latLon2XY(xr, yr, lat, lon, ieast, azimuth)
    length = xy2r(yn, xe)
    ### for azimuth calculation use atan2 which returns
    ### angle from -pi to pi. Rules for getting azimuth are:
    ### 1st quadrant (yn > 0 xe > 0):   0    <= angle <=  pi/2
    ###      Rule -1* + pi/2 maps to:  pi/2               0
    ### 2nd quadrant (yn < 0 xe > 0): -pi/2  <= angle <=  0
    ###      Rule -1* + pi/2 maps to:  pi                 pi/2
    ### 3rd quadrant (yn < 0 xe < 0): -pi    <= angle <= -pi/2
    ###      Rule -1* + pi/2 maps to:  3pi/2              pi
    ### 4th quadrant (yn > 0 xe < 0):  pi/2  <= angle <=  pi
    ###      Rule -1* + 5pi/2 maps to: 2pi               3pi/2
    ####################################################################
    angle = np.arctan2(yn, xe) # yes, in that order
    bearing = [theta2bearing(i) for i in angle]

    # If bearing in degrees isexpected on return:
    if wantdeg:
        bearing = np.array([math.degrees(i) for i in bearing], 'f')

    return bearing, length

def bear2LatLon(bearing, distance, oLon, oLat):
    """
    Calculate the longitude and latitude of a new point from an origin
    point given a distance and bearing.

    :param bearing: Direction to new position (degrees, +ve clockwise
                    from north).
    :param distance: Distance to new position (km).
    :param oLon: Initial longitude.
    :param oLat: Initial latitude.

    :returns: new longitude and latitude (in degrees)
    """
    radius = 6367.0 # Earth radius (km)
    oLon = math.radians(oLon)
    oLat = math.radians(oLat)
    bear = math.radians(bearing)

    nLat = math.asin(np.sin(oLat) * np.cos(distance / radius) + \
            np.cos(oLat) * np.sin(distance / radius) * np.cos(bear))
    aa = np.sin(bear) * np.sin(distance / radius) * np.cos(oLat)
    bb = np.cos(distance / radius) - np.sin(oLat) * np.sin(nLat)

    nLon = oLon + np.arctan2(aa, bb)

    return math.degrees(nLon), math.degrees(nLat)

def latLon2XY(xr, yr, lat, lon, ieast=1, azimuth=0):
    """
    Calculate the cartesian distance between consecutive lat,lon
    points. Will bomb at North and South Poles. Assumes geographical
    coordinates and azimuth in decimal degrees, local Cartesian
    coordinates in km.

    :param xr: Reference longitude, normally 0.
    :param yr: Reference latitude, normally 0.
    :param lat: Array of latitudes.
    :param lon: Array of longitudes.
    :param int ieast: 1 if longitude increases toward the East
                     (normal case), -1 if longitude increases
                     toward the West.
    :param int azimuth: local coordinate system constructed with
                        origin at latr,lonr, X axis ('North') in
                        direction of azimuth, and Y axis such that X x
                        Y = Z(down) when going from (lat,lon) to (x,y)
                        scalar or array.

    :returns: Array of northward and eastward distances between
              consecutive points. use :func:`xy2r` to convert to a
              distance between consecutive points.
    """

    #if len(lat) != len(lon):
    #   raise ArrayMismatch, "Input array sizes do not match"

    radius = 6367.0 # Earth radius (km)

    lat = np.radians(lat)
    lon = np.radians(lon)

    # Is azimuth fixed or variable?
    if np.size(azimuth) == 1:
        angle = np.radians(azimuth)*np.ones(lat.size - 1)
    else:
        angle = np.radians(azimuth)

    cosazi = np.cos(angle)
    sinazi = np.sin(angle)

    xntru = xr + radius * (np.diff(lat))
    yetru = yr + ieast * radius * (np.diff(lon)) * np.cos(lat[1:])
    xn = xntru * cosazi + yetru * sinazi
    ye = -xntru * sinazi + yetru * cosazi

    return xn, ye

def distGC(lat, lon):
    """
    Distance based on the great circle navigation between pairs of points.

    :param lat: A pair of latitude values for the two points.
    :param lon: A pair of longitude values for the two points.

    :returns: Distance (in kilometres) between the two points, based on
              great circle navigation.

    Example::

        >>> dist = distGC([-20, -40],[120,190])
        6914.42

    """
    radius = 6367.0 # Earth radius (km)

    lat = np.radians(lat)
    lon = np.radians(lon)

    angular_distance = math.acos(math.sin(lat[0]) * math.sin(lat[1]) + \
                       math.cos(lat[0]) * math.cos(lat[1]) * \
                       math.cos(lon[0] - lon[1]))

    return radius*angular_distance

def gridLatLonDist(cLon, cLat, lonArray, latArray, units=None):
    """
    Generate a grid containing the spherical earth distance
    of the points defined by (lonarray, latarray) from the
    point defined by (clon, clat).
    (lonarray,latarray) and (clon,clat) are in degrees.
    Returns distances in km by default, other units specified by the
    'units' kwarg.

    Based on m_lldist.m by Rich Pawlowicz (rich@ocgy.ubc.ca)
    Modified by Craig Arthur 2006-11-13

    :param float cLon: Longitude of the point to measure the distance from.
    :param float cLat: Latitude of the point to measure the distance from.
    :param lonArray: 1-d array of longitude values that will define the
                     grid over which distances will be calculated.
    :param latArray: 1-d array of latitude values that will define the
                     grid over which distances will be calculated.
    :param str units: Units of distance to be returned (default is kilometre)

    :returns: 2-d array containing the distance of the points defined in
             ``lonArray`` and ``latArray`` from the point
             (``cLon``, ``cLat``).

    Example::

        >>> lonArray = np.arange(90.,100.,0.1)
        >>> latArray = np.arange(-20.,-10.,0.1)
        >>> dist = gridLatLonDist( 105., -15., lonArray, latArray, 'km')

    """

    # #CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
    # cLat_cos = 0.0
    # cLat_sin = 0.0
    # lat = empty(len(latArray), 'd')
    # lon = empty(len(lonArray), 'd')

    # dLon_sin = empty(len(lonArray), 'd')
    # dLat_sin = empty(len(latArray), 'd')
    # lat_cos = empty(len(latArray), 'd')

    # dist = empty([len(latArray), len(lonArray)], 'd')

    # code = """
        # #include <math.h>

        # double radius = 6367.0;
        # double toRads = 0.017453292519943295;

        # double cLon_ = cLon;
        # double cLat_ = cLat;

        # cLon_ = cLon_*toRads;
        # cLat_ = cLat_*toRads;

        # cLat_cos = cos(cLat_);

        # for (int i = 0; i < NlonArray[0]; ++i)
        # {
            # lon(i) = lonArray(i)*toRads;
            # double dLon = (lon(i) - cLon_)/2.0;
            # dLon_sin(i) = sin(dLon);
        # }

        # for (int i = 0; i < NlatArray[0]; ++i)
        # {
            # lat(i) = latArray(i)*toRads;
            # lat_cos(i) = cos(lat(i));

            # double dLat = (lat(i) - cLat_)/2.0;
            # dLat_sin(i) = sin(dLat);
        # }

        # for (int j = 0; j < NlatArray[0]; ++j)
        # {
            # for (int i = 0; i < NlonArray[0]; ++i)
            # {
                 # double a = pow(dLat_sin(j), 2) + \
                            # cLat_cos*lat_cos(j)*pow(dLon_sin(i), 2);
                 # double c = 2.0*atan2(sqrt(fabs(a)), sqrt(1 - a));

                 # dist(j, i) = radius*c;
            # }
        # }
    # """
    # err = weave.inline(code,
                       # ['cLon', 'cLat', 'lonArray', 'latArray', 'lat', 'lon',
                        # 'dLon_sin', 'dLat_sin', 'lat_cos', 'dist', 'cLat_cos'],
                       # type_converters=converters.blitz,
                       # compiler = 'gcc')
    # #CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

    radius = 6367.0

    lat = np.radians(latArray)
    lon = np.radians(lonArray)

    cLon = math.radians(cLon)
    cLat = math.radians(cLat)
    lon_, lat_ = np.meshgrid(lon, lat)

    dLon = lon_ - cLon
    dLat = lat_ - cLat

    a = np.square(np.sin(dLat / 2.0)) + \
        np.cos(cLat) * np.cos(lat_) * np.square(np.sin(dLon / 2.0))
    c = 2.0 * np.arctan2(np.sqrt(np.absolute(a)), np.sqrt(1 - a))
    dist = radius * c

    dist = metutils.convert(dist, "km", units)

    return dist

def gridLatLonBear(cLon, cLat, lonArray, latArray):
    """
    Generate a grid containing the bearing of the points defined by
    (lonArray,latArray) from the point defined by (cLon,cLat).
    (lonArray,latArray) and (cLon,cLat) are in degrees.
    Returns bearing in radians.

    :param float cLon: Longitude of the point to measure the distance from.
    :param float cLat: Latitude of the point to measure the distance from.
    :param lonArray: 1-d array of longitude values that will define the
                     grid over which distances will be calculated.
    :param latArray: 1-d array of latitude values that will define the
                     grid over which distances will be calculated.
    :returns: 2-d array containing the bearing (direction) of the points
              defined in ``lonArray`` and ``latArray`` from the point
              (``cLon``, ``cLat``)

    Example::

        >>> from maputils import gridLatLonBear
        >>> import numpy as np
        >>> lonArray = np.arange(90.,100.,0.1)
        >>> latArray = np.arange(-20.,-10.,0.1)
        >>> gridLatLonBear( 105., -15., lonArray, latArray)
        array([[-1.94475949, -1.94659552, -1.94845671, ..., -2.36416927,
                -2.37344337, -2.38290081],
               [-1.93835542, -1.94015859, -1.94198663, ..., -2.35390045,
                -2.36317282, -2.37263233],
               [-1.93192776, -1.93369762, -1.93549204, ..., -2.34343069,
                -2.35269718, -2.36215458],
                ...,
               [-1.29066433, -1.28850464, -1.28632113, ..., -0.84374983,
                -0.83405688, -0.82416555],
               [-1.28446304, -1.28227062, -1.28005406, ..., -0.83332654,
                -0.82361918, -0.813717  ],
               [-1.27828819, -1.27606348, -1.27381433, ..., -0.82310335,
                -0.81338586, -0.80347714]])

    """

    # #CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
    # lat = empty(len(latArray), 'd')
    # lon = empty(len(lonArray), 'd')

    # dLon_sin = empty(len(lonArray), 'd')
    # dLon_cos = empty(len(lonArray), 'd')
    # lat_sin = empty(len(latArray), 'd')
    # lat_cos = empty(len(latArray), 'd')

    # bearing = empty([len(latArray), len(lonArray)], 'd')

    # code = """
        # #include <math.h>

        # double toRads = 0.017453292519943295;

        # double cLon_ = cLon;
        # double cLat_ = cLat;

        # cLon_ = cLon_*toRads;
        # cLat_ = cLat_*toRads;

        # double cLat_cos = cos(cLat_);
        # double cLat_sin = sin(cLat_);

        # for (int i = 0; i < NlonArray[0]; ++i)
        # {
            # lon(i) = lonArray(i)*toRads;
            # double dLon = lon(i) - cLon_;
            # dLon_sin(i) = sin(dLon);
            # dLon_cos(i) = cos(dLon);
        # }

        # for (int i = 0; i < NlatArray[0]; ++i)
        # {
            # lat(i) = latArray(i)*toRads;
            # lat_sin(i) = sin(lat(i));
            # lat_cos(i) = cos(lat(i));
        # }

        # for (int j = 0; j < NlatArray[0]; ++j)
        # {
            # for (int i = 0; i < NlonArray[0]; ++i)
            # {
                # double alpha = dLon_sin(i)*lat_cos(j);
                # double beta = (cLat_cos*lat_sin(j)) - (cLat_sin*lat_cos(j)*dLon_cos(i));

                # bearing(j, i) = atan2(alpha, beta);
            # }
        # }
    # """
    # err = weave.inline(code,
                       # ['cLon', 'cLat', 'lonArray', 'latArray', 'lat', 'lon',
                        # 'dLon_sin', 'dLon_cos', 'lat_sin', 'lat_cos', 'bearing'],
                       # type_converters=converters.blitz,
                       # compiler = 'gcc')
    # #CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC

    lat = np.radians(latArray)
    lon = np.radians(lonArray)

    cLon = math.radians(cLon)
    cLat = math.radians(cLat)
    lon_, lat_ = np.meshgrid(lon, lat)

    dLon = lon_ - cLon
    #dLat= lat_ - cLat

    alpha = np.sin(dLon) * np.cos(lat_)
    beta = np.cos(cLat) * np.sin(lat_) - \
           np.sin(cLat) * np.cos(lat_) * np.cos(dLon)

    bearing = np.arctan2(alpha, beta)

    return bearing

def bearing2theta(bearing):
    """
    Converts bearing in azimuth coordinate system into theta in
    cartesian coordinate system. Assumes -2*pi <= bearing <= 2*pi

    :param bearing: Bearing to convert (in radians) (+ve clockwise
                    from north).

    :returns: Angle in cartesian coordinate system (+ve anticlockwise
              from east).

    """
    theta = np.pi / 2. - bearing
    theta = np.mod(theta, 2.*np.pi)

    return theta

def theta2bearing(theta):
    """
    Converts a cartesian angle (in radians) to an azimuthal bearing
    (in radians). Assumes -2*pi <= theta <= 2*pi

    :param theta: Angle in cartesian coordinate system (+ve anticlockwise
                  from east).

    :returns: Bearing in azimuth coordinate system (+ve clockwise
                    from north).

    """
    bearing = 2. * np.pi - (theta - np.pi / 2.)
    bearing = np.mod(bearing, 2. * np.pi)

    return bearing

def makeGrid(cLon, cLat, margin=2, resolution=0.01, minLon=None, maxLon=None,
             minLat=None, maxLat=None):
    """
    Generate a grid of the distance and angle of a grid of points
    surrounding a storm centre given the location of the storm. The
    grid margin and grid size can be set in configuration
    files. xMargin, yMargin and gridSize are in degrees.

    :param float cLon: Reference longitude.
    :param float cLat: Reference latitude.
    :param float margin: Distance (in degrees) around the centre to fit the
                         grid.
    :param float resolution: Resolution of the grid (in degrees).
    :param float minLon: Minimum longitude of points to include in the grid.
    :param float maxLon: Maximum longitude of points to include in the grid.
    :param float minLat: Minimum latitude of points to include in the grid.
    :param float maxLat: Maximum latitude of points to include in the grid.

    :returns: 2 2-d arrays containing the distance (km) and bearing (azimuthal)
              of all points in a grid from the ``cLon``, ``cLat``.
    """
    if (type(cLon)==list or type(cLat)==list or
        type(cLon)==np.ndarray or type(cLat)==np.ndarray):
        raise TypeError("Input values must be scalar values")

    gridSize = int(resolution * 1000)

    if minLon:
        minLon_ = int(1000 * (minLon)) - int(1000 * margin)
    else:
        minLon_ = int(1000 * (cLon)) - int(1000 * margin)
    if maxLon:
        maxLon_ = int(1000 * (maxLon)) + int(1000 * margin) + 1
    else:
        maxLon_ = int(1000 * (cLon)) + int(1000 * margin) + 1
    if minLat:
        minLat_ = int(1000 * (minLat)) - int(1000 * margin)
    else:
        minLat_ = int(1000 * (cLat)) - int(1000 * margin)
    if maxLat:
        maxLat_ = int(1000 * (maxLat)) + int(1000 * margin) + 1
    else:
        maxLat_ = int(1000 * (cLat)) + int(1000 * margin) + 1

    xGrid = np.array(np.arange(minLon_, maxLon_, gridSize), dtype=int)
    yGrid = np.array(np.arange(minLat_, maxLat_, gridSize), dtype=int)

    try:
        from ._maputils import beardist
        lonArray = xGrid / 1000.
        latArray = yGrid / 1000.
        R = np.zeros((len(latArray), len(lonArray)), order='F')
        theta = np.zeros((len(latArray), len(lonArray)), order='F')

        beardist(cLon, cLat, lonArray, latArray, theta, R)
        R = np.ascontiguousarray(R)
        theta = np.ascontiguousarray(theta)
    except ImportError:
        R = gridLatLonDist(cLon, cLat, xGrid / 1000., yGrid / 1000.)
        theta = np.pi/2. - gridLatLonBear(cLon, cLat, xGrid / 1000., yGrid / 1000.)
        np.putmask(R, R == 0, 1e-30)

    return R, theta

def makeGridDomain(cLon, cLat, minLon, maxLon, minLat, maxLat,
                   margin=2, resolution=0.01):
    """
    Generate a grid of the distance and angle of a grid of points
    across a complete model domain, given the location of the storm.

    :param float cLon: Reference longitude.
    :param float cLat: Reference latitude.
    :param float minLon: Minimum longitude of points to include in the grid.
    :param float maxLon: Maximum longitude of points to include in the grid.
    :param float minLat: Minimum latitude of points to include in the grid.
    :param float maxLat: Maximum latitude of points to include in the grid.
    :param float margin: Distance (in degrees) around the centre to fit the
                         grid.
    :param float resolution: Resolution of the grid (in degrees).

    :returns: 2 2-d arrays containing the distance (km) and bearing (azimuthal)
              of all points in a grid from the ``cLon``, ``cLat``, spanning the
              complete region.

    """
    if (type(cLon)==list or type(cLat)==list or
        type(cLon)==np.ndarray or type(cLat)==np.ndarray):
        raise TypeError("Input values must be scalar values")
    gridSize = int(resolution * 1000)
    minLon_ = int(1000 * (minLon)) - int(1000 * margin)
    maxLon_ = int(1000 * (maxLon)) + int(1000 * margin) + 1
    minLat_ = int(1000 * (minLat)) - int(1000 * margin)
    maxLat_ = int(1000 * (maxLat)) + int(1000 * margin) + 1

    xGrid = np.array(np.arange(minLon_, maxLon_, gridSize), dtype=int)
    yGrid = np.array(np.arange(minLat_, maxLat_, gridSize), dtype=int)

    R = gridLatLonDist(cLon, cLat, xGrid / 1000., yGrid / 1000.)
    np.putmask(R, R==0, 1e-30)
    theta = np.pi / 2. - gridLatLonBear(cLon, cLat,
                                        xGrid / 1000., yGrid / 1000.)
    return R, theta

def meshLatLon(cLon, cLat, margin=2, resolution=0.01):
    """
    Create a meshgrid of the longitudes and latitudes of a grid.

    :param float cLon: Longitude of centre of grid.
    :param float cLat: Latitude of centre of grid.
    :param float margin: Distance (in degrees) around the centre to
                         build the grid.
    :param float resolution: Resolution of the grid (degrees).

    :returns: Coordinate matrices for the longitude and latitude
              vectors, covering the region within ``margin``
              degrees of (``cLon``, ``cLat``).

    """
    if (type(cLon)==list or type(cLat)==list or
        type(cLon)==np.ndarray or type(cLat)==np.ndarray):
        raise TypeError("Input values must be scalar values")
    gridSize = int(1000 * resolution)

    minLon = int(1000 * (cLon - margin))
    maxLon = int(1000 * (cLon + margin)) + gridSize
    minLat = int(1000 * (cLat - margin))
    maxLat = int(1000 * (cLat + margin)) + gridSize

    xx = np.array(np.arange(minLon, maxLon, gridSize))
    yy = np.array(np.arange(minLat, maxLat, gridSize))

    xGrid, yGrid = np.meshgrid(xx, yy)
    return xGrid / 1000., yGrid / 1000.

def meshLatLonDomain(minLon, maxLon, minLat, maxLat,
                     margin=2, resolution=0.01):
    """
    Create a meshgrid of the lon/lat grid across th full model domain.

    :param float minLon: Minimum longitude of the domain.
    :param float maxLon: Maximum longitude of the domain.
    :param float minLat: Minimum latitude of the domain.
    :param float maxLat: Maximum latitude of the domain.
    :param float margin: Distance (in degrees) around the centre to
                         build the grid.
    :param float resolution: Resolution of the grid (degrees).

    :returns: Coordinate matrices for the longitude and latitude
              vectors, covering the full domain, plus an additional
              margin of ``margin`` degrees.
    """
    gridSize = int(1000 * resolution)

    minLon_ = int(1000 * (minLon - margin))
    maxLon_ = int(1000 * (maxLon + margin)) + gridSize
    minLat_ = int(1000 * (minLat - margin))
    maxLat_ = int(1000 * (maxLat + margin)) + gridSize

    xx = np.array(np.arange(minLon_, maxLon_, gridSize))
    yy = np.array(np.arange(minLat_, maxLat_, gridSize))

    xGrid, yGrid = np.meshgrid(xx, yy)
    return xGrid / 1000., yGrid / 1000.

def dist2GC(cLon1, cLat1, cLon2, cLat2, lonArray, latArray, units="km"):
    """
    Calculate the distance between an array of points and the great
    circle joining two (other) points. All input values are in
    degrees. By default returns distance in km, other units specified
    by the 'units' kwarg.

    Based on a cross-track error formulation from:
    http://williams.best.vwh.net/avform.htm#XTE

    :param float cLon1: Longitude of first point.
    :param float cLat1: Latitude of first point.
    :param float cLon2: Longitude of second point.
    :param float cLat2: Latitude of second point.
    :param lonArray: :class:`numpy.ndarray` of longitudes for which
                     the distance to the line joining the two points
                     will be calculated.
    :param latArray: :class:`numpy.ndarray` of latitudes for which the
                      distance to the line joining the two points will
                      be calculated.

    :returns: 2-d array of distances between the array points and the
              line joining two points.
    :rtype: :class:`numpy.ndarray`
    """

    # Calculate distance and bearing from first point to array of points:
    dist_ = gridLatLonDist(cLon1, cLat1, lonArray, latArray, units="rad")
    bear_ = gridLatLonBear(cLon1, cLat1, lonArray, latArray)

    #bearing of the cyclone:
    cyc_bear_ = latLon2Azi([cLon1, cLon2], [cLat1, cLat2])

    dist2GC_ = np.arcsin(np.sin(dist_) * np.sin(bear_ - cyc_bear_))

    distance = metutils.convert(dist2GC_, "rad", units)
    return distance

def coriolis(lat):
    """
    Calculate the Coriolis factor (f) for a given latitude (degrees).
    If a list is passed, return a list, else return a single value.

    :param lat: Latitude (degrees).
    :type  lat: Array-like.

    :returns: Coriolis factor.

    """
    omega = 2 * np.pi / 24. / 3600.
    f = 2 * omega * np.sin(np.radians(lat))

    return f

def find_index(array, value):
    """
    Find the index of 'array' with a value closest to 'value'

    :param array: array of data values.
    :type array: :class:`numpy.ndarray` or `list`.
    :param value: a value to search `array` for
                 (or find the index of the nearest value to `value`).

    :param int idx: index of `array` that most closely matches
                    `value`
    :raises: ValueError if `value` is a :class:`numpy.ndarray` or
             a list

    Example::

        >>> find_index(np.arange(0., 100., 0.5), 15.25)
        30

    """
    if type(value) == np.ndarray or type(value) == list:
        raise ValueError("Value cannot be an array")

    if (value > array.max()):
        # Value is above the largest value in the array - return the last index:
        return len(array) - 1
    elif (value < array.min()):
        # Value is below minimum value in the array - return the first index:
        return 0
    else:
        # argmin gives us the index corresponding to the minimum value of the array.
        idx = (abs(array - value)).argmin()
        return idx

def find_nearest(array, value):
    """
    Find the closest value in 'array' to 'value'

    :param array: array of data values.
    :type array: :class:`numpy.ndarray`
    :param value: a value to search the array for (or find the index of the
                  nearest value to 'value'
    :type value: int or float

    :returns: array[idx], where idx is the index of array that corresponds
              to the value closest to 'value'.

    :raises ValueError: If `value` is a :class:`numpy.ndarray` or
                        a list.
    :raises IndexError: If the `value` cannot be found in the `array`

    Example::

        >>> n = find_nearest( np.arange(0,100.,0.5), 15.25 )
        15.0

    """
    if type(value) == np.ndarray or type(value) == list:
        raise ValueError("Value cannot be an array")
    idx = find_index(array, value)

    try:
        v = array[idx]
    except IndexError:
        raise
    else:
        return v


guess=""
secretWord="car"
limit_of_guesses=3
guess_numbers=0
IsOut=True

while guess!=secretWord and IsOut:
    if guess_numbers < limit_of_guesses:
        guess = input("Put a guess name-- ")
        guess_numbers += 1
    else:
        IsOut=False;

if IsOut:
 print("You chose right one")
else:
    print("You out of guess limit")


from typing import List

def find(numbers: List[int], number: int) -> int:
    if numbers:
        start, end = 0, len(numbers) - 1
        while start <= end:
            mid = (start + end) // 2
            val = numbers[mid]
            if val > number:
                end = mid - 1
            elif val < number:
                start = mid + 1
            else:
                return mid
    raise ValueError("No result found!")


"""
Problem:
https://www.hackerrank.com/challenges/s10-basic-statistics/problem
"""

from math import ceil
from collections import Counter, OrderedDict

import numpy as np
from scipy import stats

#Using numpy and stat
def calculateMeanMedianModeNpStat(numbers):
    print(np.mean(numbers))
    print(np.median(numbers))
    print(stats.mode(numbers))

def calculateMeanMedianMode(numbers):

    class OrderedCounter(Counter, OrderedDict):
        pass

    mean = sum(numbers) / N

    numbers = sorted(numbers)

    median = numbers[(len(numbers)//2) + 1] if len(numbers) % 2 == 1 else (numbers[len(numbers)//2] + numbers[(len(numbers))//2 - 1]) / 2

    mode = OrderedCounter(numbers).most_common(1)[0][0]

    print(mean)
    print(median)
    print(mode)

N = int(input())

numbers = list(map(int, input().split()))

calculateMeanMedianMode(numbers)


from discord import Interaction
from discord.ext.commands import Context

from common.database.models.anonymous_item import AnonymousItem
from common.database.models.detailed_item import DetailedItem
from common.command_management.command_reconstructor import CommandReconstructor
from common.module.module import Module

class AnonymousItemFactory(Module):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.command_reconstructor: CommandReconstructor = kwargs.get('dependencies', {}).get('CommandReconstructor')
        assert (self.command_reconstructor is not None)

    def create(self, data: Interaction | Context, detailed_item: DetailedItem) -> AnonymousItem:
        return AnonymousItem(
            detailed_item.qualified_command_string,
            detailed_item.command_name,
            self.command_reconstructor.reconstruct_command_string(
                data,
                add_parameter_keys=True,
                anonymize_mentions=True
            ),
            detailed_item.is_app_command,
            detailed_item.created_at,
            detailed_item.is_valid
        )


import math
import os
import sys
import tensorflow as tf
import glob

# slim = tf.contrib.slim
#===================================================  Dataset Utils  ===================================================

def int64_feature(values):
  """Returns a TF-Feature of int64s.

  Args:
    values: A scalar or list of values.

  Returns:
    a TF-Feature.
  """
  if not isinstance(values, (tuple, list)):
    values = [values]
  return tf.train.Feature(int64_list=tf.train.Int64List(value=values))

def bytes_feature(values):
  """Returns a TF-Feature of bytes.

  Args:
    values: A string.

  Returns:
    a TF-Feature.
  """
  return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values]))

def image_to_tfexample(image_data, image_format, height, width, class_serial):
  return tf.train.Example(features=tf.train.Features(feature={
      'image/encoded': bytes_feature(image_data),
      'image/format': bytes_feature(image_format),
      'image/class': int64_feature(class_serial),
      'image/height': int64_feature(height),
      'image/width': int64_feature(width),
  }))

def write_label_file(serial_to_class_ids, dataset_dir,
                     filename='labels.csv'):
  """Writes a file with the list of class ids.

  Args:
    seral_to_class_ids: A map of (integer) serials to class ids.
    dataset_dir: The directory in which the labels file should be written.
    filename: The filename where the class names are written.
  """
  labels_filename = os.path.join(dataset_dir, filename)
  with tf.gfile.Open(labels_filename, 'w') as f:
    for serial in serial_to_class_ids:
      class_id = serial_to_class_ids[serial]
      f.write('%d, %d\n' % (serial, class_id))

#=======================================  Conversion Utils  ===================================================

# Create an image reader object for easy reading of the images
class ImageReader(object):
  """Helper class that provides TensorFlow image coding utilities."""

  def __init__(self):
    # Initializes function that decodes RGB PNG data.
    self._decode_png_data = tf.placeholder(dtype=tf.string)
    self._decode_png = tf.image.decode_png(self._decode_png_data, channels=3)

  def read_image_dims(self, sess, image_data):
    image = self.decode_png(sess, image_data)
    return image.shape[0], image.shape[1]

  def decode_png(self, sess, image_data):
    image = sess.run(self._decode_png,
                     feed_dict={self._decode_png_data: image_data})
    assert len(image.shape) == 3
    assert image.shape[2] == 3
    return image

def _get_filenames_and_classes(dataset_dir, img_ext='png'):
  """Returns a list of filenames and inferred class names.

  Args:
    dataset_dir: A directory containing all images. Image filename itself
    encodes class names.

  Returns:
    A list of image file paths, relative to `dataset_dir` and the list of
    class names.
  """
  photo_filenames = glob.glob(os.path.join(dataset_dir, '*.' + img_ext))
  class_ids = set()
  for f in photo_filenames:
    fname, _ = os.path.splitext(os.path.basename(f))
    class_id = int(fname.split('_')[2])
    class_ids.add(class_id)
    #print "[Debug] file={}, class_id={}".format(f, class_id)

  return photo_filenames, sorted(list(class_ids))

def _get_dataset_filename(dataset_dir, split_name, shard_id, tfrecord_filename, _NUM_SHARDS):
  output_filename = '%s_%s_%04d_of_%04d.tfrecord' % (
      tfrecord_filename, split_name, shard_id, _NUM_SHARDS)
  return os.path.join(dataset_dir, output_filename)

def _convert_dataset(split_name, filenames, class_ids_to_serial, dataset_dir,
                tfrecord_filename, _NUM_SHARDS, simulate=False):
  """Converts the given filenames to a TFRecord dataset.

  Args:
    split_name: The name of the dataset, either 'train' or 'validation'.
    filenames: A list of absolute paths to png images.
    class_ids_to_serial: A dictionary from class ids (int) to serial (int).
    dataset_dir: The directory where the converted datasets are stored.
    simulate: Just do simulation
  """
  assert split_name in ['train', 'validation']

  num_per_shard = int(math.ceil(len(filenames) / float(_NUM_SHARDS)))

  with tf.Graph().as_default():
    image_reader = ImageReader()

    with tf.Session('') as sess:

      for shard_id in range(_NUM_SHARDS):
        output_filename = _get_dataset_filename(
            dataset_dir, split_name, shard_id, tfrecord_filename = tfrecord_filename, _NUM_SHARDS = _NUM_SHARDS)

        if not simulate:
          tfrecord_writer = tf.python_io.TFRecordWriter(output_filename)

        start_ndx = shard_id * num_per_shard
        end_ndx = min((shard_id+1) * num_per_shard, len(filenames))
        for i in range(start_ndx, end_ndx):
          sys.stdout.write('\r>> Converting image %d/%d shard %d' % (
              i+1, len(filenames), shard_id))
          sys.stdout.flush()

          # Read the filename:
          image_data = tf.gfile.FastGFile(filenames[i], 'r').read()
          height, width = image_reader.read_image_dims(sess, image_data)

          fname, _ = os.path.splitext(os.path.basename(filenames[i]))
          class_id = int(fname.split('_')[2])
          class_serial = class_ids_to_serial[class_id]
          example = image_to_tfexample(
              image_data, 'png', height, width, class_serial)
          if not simulate:
            tfrecord_writer.write(example.SerializeToString())

  sys.stdout.write('\n')
  sys.stdout.flush()

def _dataset_exists(dataset_dir, _NUM_SHARDS, output_filename):
  for split_name in ['train', 'validation']:
    for shard_id in range(_NUM_SHARDS):
      tfrecord_filename = _get_dataset_filename(
          dataset_dir, split_name, shard_id, output_filename, _NUM_SHARDS)
      if not tf.gfile.Exists(tfrecord_filename):
        return False
  return True


import datetime
import locale
import sys
import xml.dom.minidom

dom = xml.dom.minidom.parse("items-0.xml")
node = dom.documentElement
items = dom.getElementsByTagName("Item")

f = open("sqlitedata.dat", "w")

for item in items:
    name = item.getElementsByTagName("Name")[0].childNodes[0].data
    categories = item.getElementsByTagName("Category")
    currently = item.getElementsByTagName("Currently")[0].childNodes[0].data
    firstBid = item.getElementsByTagName("First_Bid")[0].childNodes[0].data
    numberOfBids = item.getElementsByTagName("Number_of_Bids")[0].childNodes[0].data
    bids = item.getElementsByTagName("Bids")
    location = item.getElementsByTagName("Location")[0].childNodes[0].data
    country = item.getElementsByTagName("Country")[0].childNodes[0].data
    started = item.getElementsByTagName("Started")[0].childNodes[0].data
    ends = item.getElementsByTagName("Ends")[0].childNodes[0].data
    seller = item.getElementsByTagName("Seller")[0]
    sellerID = seller.attributes["UserID"].value
    sellerRating = seller.attributes["Rating"].value
    description = item.getElementsByTagName("Description")[0]
    if len(description.childNodes) > 0:
        des = description.childNodes[0].data

    f.write("Name: " + name + "\n")
    for category in categories:
        cat = category.firstChild.data
        f.write("Category: " + cat + "\n")
    f.write("Description: " + des + "\n")

    f.write("Currently: " + currently + "\n")
    f.write("First Bid: " + firstBid + "\n")
    f.write("Number of Bids: " + numberOfBids + "\n")
    f.write("Location: " + location + "\n")
    f.write("Country: " + country + "\n")
    f.write("Started: " + started + "\n")
    f.write("Ends: " + ends + "\n")
    f.write("Seller ID: " + sellerID + " Seller Rating: " + sellerRating + "\n")

    for bidTag in bids:
        bid = bidTag.getElementsByTagName("Bid")
        for attri in bid:
            f.write("******BID INFORMATION********\n")
            bidList = attri.getElementsByTagName("Bidder")[0]
            location = attri.getElementsByTagName("Location")
            country = attri.getElementsByTagName("Country")
            bidder = bidList.attributes['UserID'].value
            rating = bidList.attributes["Rating"].value
            time = attri.getElementsByTagName("Time")[0].childNodes[0].data
            amount = attri.getElementsByTagName("Amount")[0].childNodes[0].data
            f.write("Bidder: " + bidder + " Rating: " + rating + "\n")
            if len(location) > 0:
                f.write("Location: " + location[0].childNodes[0].data + "\n")
            if len(country) > 0:
                f.write("Country: " + country[0].childNodes[0].data + "\n")
            f.write("Time: " + time + "\n")
            f.write("Amount: " + amount + "\n")
            f.write("*****************************\n")

    f.write("\n")

f.close()


# Classe repsonsável pela implementação do Bubble Sort
#

# Py Array Sort / sort / Bubblesort
# @author MRX
# Version : 1.0.0

class Bubblesort:

    def sort(self, array):

        tamanho = len(array) - 1
        ordenado = False

        while not ordenado:
            ordenado = True

            for i in range(tamanho):
                if array[i] > array[i + 1]:
                    array[i], array[i + 1] = array[i + 1], array[i]
                    ordenado = False

        return array


def financialCrisis(roadRegister):
    def gen():
        for k in range(len(roadRegister)):
            front = roadRegister[:k]
            back = roadRegister[k + 1:]
            all_rows = front + back
            for p, r in enumerate(all_rows):
                front = r[:k]
                back = r[k + 1:]
                all_rows[p] = front + back
            yield all_rows

    return list(gen())


#!/bin/env python3
from secrets import a, b, FLAG
from collections import namedtuple
from Crypto.Util.number import inverse, bytes_to_long
import hashlib
import random

Point = namedtuple("Point", "x y")
O = 'INFINITY'

def is_on_curve(P):
    if P == O:
        return True
    else:
        return (P.y**2 - (P.x**3 + a*P.x + b)) % p == 0 and 0 <= P.x < p and 0 <= P.y < p

def point_inverse(P):
    if P == O:
        return P
    return Point(P.x, -P.y % p)

def point_addition(P, Q):
    if P == O:
        return Q
    elif Q == O:
        return P
    elif Q == point_inverse(P):
        return O
    else:
        if P == Q:
            s = (3*P.x**2 + a)*inverse(2*P.y, p) % p
        else:
            s = (Q.y - P.y) * inverse((Q.x - P.x), p) % p
    Rx = (s**2 - P.x - Q.x) % p
    Ry = (s*(P.x - Rx) - P.y) % p
    R = Point(Rx, Ry)
    assert is_on_curve(R)
    return R

def point_multiply(P, d):
    bits = bin(d)[2:]
    Q = O
    for bit in bits:
        Q = point_addition(Q, Q)
        if bit == '1':
            Q = point_addition(Q, P)
    assert is_on_curve(Q)
    return Q

p = 9631668579539701602760432524602953084395033948174466686285759025897298205383
gx = 5664314881801362353989790109530444623032842167510027140490832957430741393367
gy = 3735011281298930501441332016708219762942193860515094934964869027614672869355
G = Point(gx, gy)
assert is_on_curve(G)

#Alice
dA = random.randint(1, p-2)
A = point_multiply(G, dA)
print('A =', A)

#Bob
dB = random.randint(1, p-2)
B = point_multiply(G, dB)
print('B =', B)

#Encryption
k = point_multiply(B, dA).x
k = hashlib.sha512(str(k).encode('ascii')).digest()
enc = bytes(ci ^ ki for ci, ki in zip(FLAG.ljust(len(k), b'\0'), k))
print('enc =', enc.hex())


import os
import logging
from ..core.poll import Poll
from ..core.rabbitmq.queue import RabbitQueue
from ..core.rabbitmq.exchange import TopicExchange
from ..core.rabbitmq.binding import Binding, ConsumerBinding

log = logging.getLogger(__name__)

tenant = os.environ.get("tenant", "EGamer")
chain = os.environ.get("chain", "eth")

status_check_binding = ConsumerBinding(
    RabbitQueue("tenant_chain_action_q"),
    TopicExchange("tenant.chain.action.chain_task"),
)

status_check_result_binding = Binding(
    RabbitQueue("tenant_chain_status_q"),
    TopicExchange("tenant.chain.commodity.action.tx"),
)

# @status_check_binding.listen_on("%s.%s.txcheck" % (tenant, chain))
@status_check_binding.listen_on("*.*.*")
def check_transaction_status(channel, *args, **kwargs):
    log.info("check status request:")
    log.info(channel)
    log.info(args)
    log.info(kwargs)

class TransactionStatusPoll(Poll):
    def __init__(self):
        super().__init__(status_check_binding, status_check_result_binding)
        self.set_poll_interval(5)

    def poll(self):
        log.info("Transaction status polling alive!")


import requests
from bs4 import BeautifulSoup
import speech_recognition as sr

ready = False
while not ready:
    re = sr.Recognizer()
    with sr.Microphone() as source:
        print("Say song lyrics: ")
        audio = re.listen(source)
        try:
            lyrics = re.recognize_google(audio)
            ready = True
        except Exception:
            print("Google could not understand what you said. Try again.")

print("The lyrics you said: " + lyrics + "\n")

url = "https://www.lyrics.com/subserp.php"
PARAMS = {"st": lyrics}
r = requests.get(url, PARAMS)
print("Website visited: " + r.url + "\n")

soup = BeautifulSoup(r.text, "html.parser")
song_names = soup.find_all("p", class_="lyric-meta-title")
song_artists = soup.find_all(
    "p", class_=["lyric-meta-album-artist", "lyric-meta-artists"]
)

names = []
artists = []

for name in song_names:
    names.append(name.text)

for artist in song_artists:
    artists.append(artist.text)

print("The top 3 songs associated with those lyrics as suggested by lyrics.com are: ")
for i in range(3):
    print(f"{i + 1}.) {names[i]} by {artists[i]}")


#Desenvolva uma lógica que leia o peso e a altura de uma pessoa, calcule seu imc e mostre seu status, de acordo com a tabela abaixo:
#abaixo de 18.5: Abaixo do peso | 18.5 a 25: Peso ideal | 25 a 30: Sobrepeso | 30 a 40: Obesidade | +40: Obesidade Morbida

peso = float(input('Seu peso (Kg): '))
altura = float(input('Sua altura (M): '))
if altura.is_integer():
    altura = altura / 100
imc = peso / (altura**2)

if imc <= 18.5:
    status = '\033[1;31mAbaixo do peso\033[m'
elif imc < 25:
    status = '\033[1;32mPeso ideal\033[m'
elif imc < 30:
    status = '\033[1;33mSobrepeso\033[m'
elif imc < 40:
    status = '\033[1;31mObesidade\033[m'
else:
    status = '\033[1;31mObesidade Mórbida\033[m'

print(f'\033[1mSeu IMC: {imc:.1f}\033[m\n'
      f'\033[1mStatus:\033[m {status}')


def solution(s):
    s = s.lower()
    cnt_y = 0
    cnt_p =0
    for i in s:
        if i == "y":
            cnt_y +=1
        if i == "p":
            cnt_p +=1

    return True if cnt_y==cnt_p or (cnt_y ==0 and cnt_p ==0) else False

Programmers/알고리즘/Level1/문자열 내 p와 y의 개수/강문영.py


from statistics import mean
from textwrap import dedent

import matplotlib.pyplot as plt

from blackjack.display_utils import money_format, pct_format, zero_division_pct

def slice_label(percent, all_vals):
    """
    Create a pie chart slice label of the form `x% (absolute count)` (e.g. --> 45.3% (153) ).
    Note that this function was ripped from the matplotlib documentation on the subject.
    """
    absolute = int(percent/100.0*sum(all_vals))
    return "{:.1f}%\n({:d})".format(percent, absolute)

class SingleGameAnalyzer:
    """Class for running basic analytics on tracked metrics for a single game."""

    def __init__(self,
                 wins=0,
                 losses=0,
                 pushes=0,
                 insurance_wins=0,
                 insurance_losses=0,
                 gambler_blackjacks=0,
                 dealer_blackjacks=0,
                 bankroll_progression=None
                ):
        self.wins = wins
        self.losses = losses
        self.pushes = pushes
        self.insurance_wins = insurance_wins
        self.insurance_losses = insurance_losses
        self.gambler_blackjacks = gambler_blackjacks
        self.dealer_blackjacks = dealer_blackjacks
        self.bankroll_progression = bankroll_progression or []

    def print_summary(self):
        """Print a simple summary of analyzed results."""
        # --- Hand Outcomes ---
        total_hands = sum([self.wins, self.losses, self.pushes, self.insurance_wins])  # Note that insurance losses are not a final outcome of a hand!
        hand_win_pct = zero_division_pct(self.wins, total_hands)
        hand_loss_pct = zero_division_pct(self.losses, total_hands)
        hand_push_pct = zero_division_pct(self.pushes, total_hands)
        hand_insurance_win_pct = zero_division_pct(self.insurance_wins, total_hands)

        # --- Blackjacks ---
        total_blackjacks = self.gambler_blackjacks + self.dealer_blackjacks
        bj_gambler_pct = zero_division_pct(self.gambler_blackjacks, total_blackjacks)
        bj_dealer_pct = zero_division_pct(self.dealer_blackjacks, total_blackjacks)

        # --- Insurance ---
        total_insurance = self.insurance_wins + self.insurance_losses
        ins_win_pct = zero_division_pct(self.insurance_wins, total_insurance)
        ins_loss_pct = zero_division_pct(self.insurance_losses, total_insurance)

        # --- Bankroll ---
        winnings_gross = self.bankroll_progression[-1] - self.bankroll_progression[0]
        winnings_pct = zero_division_pct(winnings_gross, self.bankroll_progression[0])

        # Return the formatted summary string
        print(dedent(f"""\
            --- Hand Outcomes ---

            Total Hands: {total_hands}

            Wins: {self.wins} ({pct_format(hand_win_pct)})
            Losses: {self.losses} ({pct_format(hand_loss_pct)})
            Pushes: {self.pushes} ({pct_format(hand_push_pct)})
            Insurance Wins: {self.insurance_wins} ({pct_format(hand_insurance_win_pct)})

            --- Blackjacks ---

            Total Blackjacks: {total_blackjacks}

            Player Blackjacks: {self.gambler_blackjacks} ({pct_format(bj_gambler_pct)})
            Dealer Blackjacks: {self.dealer_blackjacks} ({pct_format(bj_dealer_pct)})

            --- Insurance ---

            Total Bets: {total_insurance}

            Wins: {self.insurance_wins} ({pct_format(ins_win_pct)})
            Losses: {self.insurance_losses} ({pct_format(ins_loss_pct)})

            --- Bankroll ---

            Winnings: {money_format(winnings_gross)} ({pct_format(winnings_pct)})

            Max Bankroll: {money_format(max(self.bankroll_progression))}
            Min Bankroll: {money_format(min(self.bankroll_progression))}
            Avg Bankroll: {money_format(mean(self.bankroll_progression))}
            """)
        )

    def create_plots(self):
        """Create charts summarizing the tracked metric data."""
        # Create a figure to hold the plots (called "axes")
        fig, (ax1, ax2) = plt.subplots(2, 1)  # 2 rows 1 column of axes (i.e. stacked plots)

        # Axes 1: Bankroll vs. Turn Number (line chart)
        ax1.plot(self.bankroll_progression)
        ax1.set_xlabel('Turn Number')
        ax1.set_ylabel('Bankroll ($)')
        ax1.set_title('Bankroll vs. Turn Number')

        # Axes 2: Hand Outcome Breakdown (pie chart)
        data = []
        labels = []
        for metric, label in [
            (self.wins, 'Wins'), (self.losses, 'Losses'), (self.pushes, 'Pushes'), (self.insurance_wins, 'Insurance Wins')
        ]:
            if metric > 0:
                data.append(metric)
                labels.append(label)

        wedges, _, _ = ax2.pie(data, autopct=lambda pct: slice_label(pct, data), textprops=dict(color="w"))
        ax2.legend(wedges, labels, title="Outcomes")
        ax2.set_title('Hand Outcomes')
        ax2.axis('equal')

        # Avoid plot label overlap
        plt.tight_layout()
        plt.show()


from time import sleep
from random import randint

from telegram import Update
from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters
import logging

from finder import AdFinder

# Enable logging
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=logging.INFO)
logging.getLogger("httpx").setLevel(logging.WARNING)
logger = logging.getLogger(__name__)

# Your API TOKEN
API_TOKEN = "Your API TOKEN"

async def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Send a message when the command /start is issued."""

    await update.message.reply_text("لینک مورد نظر خود را وارد کنید: ")

async def crawl(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    """Echo the user message."""
    user_id = update.effective_user.id
    url = update.message.text
    finder = AdFinder(url)
    while True:
        try:
            ads = finder.run()
            for ad in ads:
                message = f'{ad.get("title")} \n\n\n {ad.get("url")}'
                await update.message.reply_photo(photo=ad["image"], caption=message)
        except Exception as err:
            print(err)

        sleep(randint(30, 60))

def main() -> None:
    """Start the bot."""

    application = Application.builder().token(API_TOKEN).build()

    application.add_handler(CommandHandler("start", start))
    application.add_handler(CommandHandler("stop", start))
    application.add_handler(MessageHandler(filters.TEXT & filters.Regex(r'^https://divar\.ir/.*$'), crawl))

    # Run the bot until the user presses Ctrl-C
    application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == "__main__":
    main()


# -- Path setup --------------------------------------------------------------

import sphinx_rtd_theme

# -- Project information -----------------------------------------------------

project = 'solnp'
copyright = '2020, Krister S. Jakobsson'
master_doc = 'index'
title = 'Python/C++ SOLNP'
subtitle = 'Thesis'
author = 'Krister S. Jakobsson'
institute = ''
department = ''
source_suffix = '.rst'

# -- General configuration ---------------------------------------------------

# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
html_last_updated_fmt = '%Y-%m-%d'

# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
html_use_smartypants = True

# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
    'sphinx.ext.mathjax',
    'sphinx.ext.viewcode',
    'sphinx.ext.autodoc',
    'sphinx.ext.napoleon',
    'sphinx.ext.imgconverter',
    'sphinx.ext.todo',
    'sphinx.ext.ifconfig',
    'sphinx.ext.githubpages',
    'sphinx_rtd_theme',
]

todo_include_todos = True
napoleon_google_docstring = False
napoleon_include_special_with_doc = False

# We do it like this to support multiple sphinx version without having warning.
# Our buildbot consider warning as error.
try:
    from sphinx.ext import imgmath
    extensions.append('sphinx.ext.imgmath')
except ImportError:
    try:
        from sphinx.ext import pngmath
        extensions.append('sphinx.ext.pngmath')
    except ImportError:
        print("Not able to find sphinx module for outputting math formulas in html")

mathjax_config = {
    'extensions': ['tex2jax.js'],
    'jax': ['input/TeX', 'output/HTML-CSS'],
}

latex_packaes = [
    "amsmath",
    "mathtools",
    "amsfonts",
    "amssymb",
    "dsfont"
]

default_role = 'math'
pngmath_divpng_args = ['-gamma 1.5','-D 110']
#pngmath_divpng_args = ['-gamma', '1.5', '-D', '110', '-bg', 'Transparent']
imgmath_latex_preamble =  "\n".join([("\\usepackage{%s}" % package) for package in latex_packaes]) +\
                          '\\def\\Z{\\mathbb{Z}}\n'+\
                          '\\def\\R{\\mathbb{R}}\n'+\
                          '\\def\\bX{\\mathbf{X}}\n'+\
                          '\\def\\X{\\mathbf{X}}\n'+\
                          '\\def\\By{\\mathbf{y}}\n'+\
                          '\\def\\Bbeta{\\boldsymbol{\\beta}}\n'+\
                          '\\def\\U{\\mathbf{U}}\n'+\
                          '\\def\\V{\\mathbf{V}}\n'+\
                          '\\def\\V1{\\mathds{1}}\n'+\
                          '\\def\\hU{\\mathbf{\hat{U}}}\n'+\
                          '\\def\\hS{\\mathbf{\hat{\Sigma}}}\n'+\
                          '\\def\\hV{\\mathbf{\hat{V}}}\n'+\
                          '\\def\\E{\\mathbf{E}}\n'+\
                          '\\def\\F{\\mathbf{F}}\n'+\
                          '\\def\\x{\\mathbf{x}}\n'+\
                          '\\def\\h{\\mathbf{h}}\n'+\
                          '\\def\\v{\\mathbf{v}}\n'+\
                          '\\def\\nv{\\mathbf{v^{{\\bf -}}}}\n'+\
                          '\\def\\nh{\\mathbf{h^{{\\bf -}}}}\n'+\
                          '\\def\\s{\\mathbf{s}}\n'+\
                          '\\def\\b{\\mathbf{b}}\n'+\
                          '\\def\\c{\\mathbf{c}}\n'+\
                          '\\def\\W{\\mathbf{W}}\n'+\
                          '\\def\\C{\\mathbf{C}}\n'+\
                          '\\def\\P{\\mathbf{P}}\n'+\
                          '\\def\\T{{\\bf \\mathcal T}}\n'+\
                          '\\def\\B{{\\bf \\mathcal B}}\n'

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']

# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
exclude_dirs = ['images', 'scripts', 'sandbox']

# -- Options for HTML output -------------------------------------------------

# The theme to use for HTML and HTML Help pages.  See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']

# -- Options for LaTeX output ---------------------------------------------

latex_engine = 'xelatex'
latex_show_urls = 'footnote'
latex_additional_files = []
latex_elements = {
    'papersize': 'a4paper',
    'pointsize': '11pt',
    'figure_align': 'htbp',
    'preamble': '',
}

# Latex Titlepage
latex_logo = None
mystyle = 'title'
latex_elements['preamble'] = "\n".join([("\\usepackage{%s}" % package) for package in latex_packaes]) +\
                            '\\def\\Z{\\mathbb{Z}}\n'+\
                            '\\def\\R{\\mathbb{R}}\n'+\
                            '\\def\\bX{\\mathbf{X}}\n'+\
                            '\\def\\X{\\mathbf{X}}\n'+\
                            '\\def\\By{\\mathbf{y}}\n'+\
                            '\\def\\Bbeta{\\boldsymbol{\\beta}}\n'+\
                            '\\def\\bU{\\mathbf{U}}\n'+\
                            '\\def\\bV{\\mathbf{V}}\n'+\
                            '\\def\\V1{\\mathds{1}}\n'+\
                            '\\def\\hU{\\mathbf{\hat{U}}}\n'+\
                            '\\def\\hS{\\mathbf{\hat{\Sigma}}}\n'+\
                            '\\def\\hV{\\mathbf{\hat{V}}}\n'+\
                            '\\def\\E{\\mathbf{E}}\n'+\
                            '\\def\\F{\\mathbf{F}}\n'+\
                            '\\def\\x{\\mathbf{x}}\n'+\
                            '\\def\\h{\\mathbf{h}}\n'+\
                            '\\def\\v{\\mathbf{v}}\n'+\
                            '\\def\\nv{\\mathbf{v^{{\\bf -}}}}\n'+\
                            '\\def\\nh{\\mathbf{h^{{\\bf -}}}}\n'+\
                            '\\def\\s{\\mathbf{s}}\n'+\
                            '\\def\\b{\\mathbf{b}}\n'+\
                            '\\def\\c{\\mathbf{c}}\n'+\
                            '\\def\\W{\\mathbf{W}}\n'+\
                            '\\def\\C{\\mathbf{C}}\n'+\
                            '\\def\\P{\\mathbf{P}}\n'+\
                            '\\def\\T{{\\bf \\mathcal T}}\n'+\
                            '\\def\\B{{\\bf \\mathcal B}}\n'

latex_additional_files += [mystyle + '.sty']

# ('source', 'target', 'title', 'author', 'documentclass')

latex_documents = [
    (master_doc, 'thesis.tex', title, author, 'report'),
]


from keychain.ui.widgets.lib import dragSpinBox, checkBox, lineEdit, comboBox, fileLine, label

MAPPING = {
    "int" : dragSpinBox.IntDragSpinBox,
    "double" : dragSpinBox.DoubleDragSpinBox,
    "bool" : checkBox.CheckBox,
    "str" : lineEdit.LineEdit,
    "list" : comboBox.ComboBox,

    "label" : label.Label,
    "file" : fileLine.FileLine,
    "folder" : fileLine.FolderLine,
}


# 원순열 전체를 다룰때는 같은 배열 2개를 이어붙이자

def solution(elements):
    answer = set()
    arr = elements + elements
    length = len(elements)

    for i in range(1, length + 1) :
        seed = sum(arr[: i])
        answer.add(seed)

        for j in range(i, length + i - 1):
            seed = seed -arr[j - i] + arr[j]
            answer.add(seed)

    return len(answer)

Algorithm/Programmers/Python/Level 2/연속 부분 수열 합의 개수.py

연속 부분 수열 합의 개수.py


import pytest
from cite_seq_count import io

@pytest.fixture
def data():
    from collections import OrderedDict
    from scipy import sparse
    test_matrix = sparse.dok_matrix((4,2))
    test_matrix[1,1] = 1
    pytest.sparse_matrix = test_matrix
    pytest.top_cells = set(['ACTGTTTTATTGGCCT','TTCATAAGGTAGGGAT'])
    pytest.ordered_tags_map = OrderedDict({
        'test3-CGTCGTAGCTGATCGTAGCTGAC':0,
        'test2-CGTACGTAGCCTAGC':1,
        'test1-CGTAGCTCG': 3,
        'unmapped': 4
        })
    pytest.data_type = 'umi'
    pytest.outfolder = 'tests/test_data/'

def test_write_to_files(data, tmpdir):
    import gzip
    import scipy
    io.write_to_files(pytest.sparse_matrix,
        pytest.top_cells,
        pytest.ordered_tags_map,
        pytest.data_type,
        tmpdir)
    file = tmpdir.join('umi_count/matrix.mtx.gz')
    with gzip.open(file, 'rb') as mtx_file:
        assert isinstance(scipy.io.mmread(mtx_file) ,scipy.sparse.coo.coo_matrix)


import json
from .enums import DataTables, GameModes
from .lookups import data_tables, heroes

class OverwatchStatisticGenerator:
    """
    This class is for generating overwatch statistics.

    Attributes:
        overwatch_user (OverwatchUser): The user whose performance statistics are desired.
        game_mode (int): The gamemode for the desired stats.
    """

    def __init__(self, overwatch_user, mode = GameModes.QP):
        """
        Constructor for the OverwatchStatisticGenerator.
        Generates stats for quick play by default.

        Parameters:
            overwatch_user (OverwatchUser): The current overwatch user.
            mode (GameModes)(optional): Enum for the game mode desired.
        """
        self.overwatch_user = overwatch_user
        self.game_mode = 0 if mode == GameModes.QP else 1

    def get_hero_statistics(self, hero) -> dict:
        """
        Generates all statistics for a particular hero.

        Parameters:
            hero (Heroes): Enum for the hero desired.
        """
        hero_stats = {}
        hero_stats['Hero'] = hero.name
        hero_address = heroes[hero]
        css_selector = f'div[data-category-id="{hero_address}"]'
        hero_game_mode_tables = self.overwatch_user.response.html.find(css_selector)

        if len(hero_game_mode_tables) > self.game_mode:
            hero_data_tables = hero_game_mode_tables[self.game_mode]
            hero_data_cards = hero_data_tables.find('.card-stat-block')
            for table in DataTables:
                hero_stats[table.name] = self.__get_table_specific_stats(table, hero_data_cards)

        return hero_stats

    def __get_table_specific_stats(self, table, hero_data_cards) -> dict:
        """
        Gets specific table stats.

        Parameters:
            table (DataTables): Enum for the table desired.
            hero_data_cards (list): Stat block that holds all cards for the particular hero.
        """
        table_stats = {}
        table_data = []
        table_name = data_tables[table]
        for card in hero_data_cards:
            if card.text.startswith(table_name):
                table_data = card.text.split("\n")[1:]
                break

        return self.__parse_table_data(table_data)

    def __parse_table_data(self, table_data) -> dict:
        """
        Parses the table stat list into a dictionary.

        Parameters:
            table_data (list): List of table stats to be parsed.
        """
        table_stats = {}
        for i in range(0, len(table_data), 2):
            table_stats[table_data[i]] = table_data[i+1]

        return table_stats


from datetime import datetime
from datetime import timedelta
import urllib.request as url
import re
from atmotools import *

time = datetime.strptime("20181129_18","%Y%m%d_%H")
procWindData(time, time + timedelta(hours=200),db="gfs_pred_0deg5",dry_run=False,overwrite=True)
exit()
index = str(url.urlopen("http://www.ftp.ncep.noaa.gov/data/nccf/com/gfs/prod/").read()).split("\\n")
times = []
for row in index:
	timestr = re.findall('(?<=href\=\"gfs\.).*(?=/\")',row)
	if timestr:
		times.append(timestr[0])
list.sort(times,key=int)
for t in times[1:]:
	time = datetime.strptime(t,"%Y%m%d%H")
	procWindData(time, time + timedelta(hours=200),db="gfs_pred_0deg5",dry_run=False,overwrite=True)


import copy

class Board(object):

    """
    Final position of the board.
    """
    final = [
        [1, 2, 3],
        [4, 5, 6],
        [7, 8, 0]
    ]

    def __init__(self, state, parent):
        # Heuristics parameters
        self.m_dist = -1
        self.m_tile_count = -1

        # Node parameters
        self._parent = parent
        self._hash = None
        self._cost = 0
        self._depth = 0
        self._state = state
        self.children = []
        self.board_size = len(self.state)

        # Get empty board position
        self.empty_row = -1
        self.empty_col = -1
        for row in range(self.board_size):
            for col in range(self.board_size):
                if self.state[row][col] == 0:
                    self.empty_row = row
                    self.empty_col = col

        self.valid_positions = []

    def __eq__(self, other):
        """
        Overload the == operator. Compare whether one board is equal to
        another board or not.

        :param other: The board to be compared with.
        :return: Whether the 2 boards are equal nor not.
        """
        return self.state == other.state

    def __lt__(self, other):
        """
        Check if one board is less than another board. The cost of the board needs to be considered.

        :param other: The board to be compared with.
        :return: Whether one board is less than another one.
        """

        # Need to compare the costs. If the cost and the boards are the same, the depth needs to be compared.
        if (self.cost == other.cost):
            return self.depth < other.depth
        return self.cost < other.cost

    def __hash__(self):
        """
        Compute a hash value of the board. This is needed because a set can't hash iterable objects and
        list is an iterable object.

        :return: A hash value of the board.
        """
        if self._hash is None:
            k = []
            # Convert each row into a tuple and then create a tuple of tuples where each tuple is a row.
            # Return the has. This conversion is required because the hash function can't work with lists.
            for i in self.state:
                k.append(tuple(i))
            self._hash = hash(tuple(k))
        return self._hash

    def print_board(self):
        """
        Print the board.

        :return: None
        """
        for row in self.state:
            print(row)

    def print_children(self):
        """
        Print the children.

        :return: None
        """

        for child in self.children:
            child.print_board()
            print("\n")

    def get_surrounding_valid_positions(self):
        """
        Get surrounding positions for the position passed. Collect the valid positions for a board.
        Considering that (i, j) is position of the missing tile on the board, the only valid positions would be
        (i - 1, j), (i + 1, j), (i, j - 1) and (i, j + 1). If the boundaries are kept in check, it can be observed that
        all the valid positions are either in the missing tile row or in the missing tile column. The for loop bellow
        collects all the positions that either are in the missing tile row or in the missing tile column.

        :return: A list of valid positions.
        """

        # row + 2 & col + 2 because range will then return values up to row + 1
        for i in range(self.empty_row - 1, self.empty_row + 2):
            if i < 0 or i >= self.board_size:
                continue
            for j in range(self.empty_col - 1, self.empty_col + 2):
                if j < 0 or j >= self.board_size:
                    continue
                is_empty_row = self.empty_row == i
                is_empty_col = self.empty_col == j
                if is_empty_row ^ is_empty_col == 1:
                    self.valid_positions.append((i, j))

        return self.valid_positions

    def generate_children(self, visited):
        """
        Generate the children for the current puzzle.

        :return: the list of children.
        """
        if len(self.children) != 0:
            return self.children

        # Get the valid positions where the missing tile could be
        self.get_surrounding_valid_positions()

        # Swap the blank space with the valid positions previously obtained.
        for position in self.valid_positions:
            b = copy.deepcopy(self._state)
            row, col = position
            b[self.empty_row][self.empty_col] = b[row][col]
            b[row][col] = 0

            # if self.parent and self.parent.state == b:
            #     continue

            # Check if a board has already been visited
            child = Board(b, self)
            child.depth = 1 + self.depth
            found = False
            if visited is not None:
                found = child in visited

            # Only add to the set of children if Node was not
            # visited earlier.
            if not found:
                self.children.append(child)

        return self.children

    def goal_test(self, state):
        """
        Check if the current board is the final solved state of the Board.

        :return: Boolean indicating whether Board is the final state or not.
        """
        return self._state == Board.final

    def misplaced_tile(self):
        """
        Return the number of misplaced tiles from the final state of the Board.

        :return: The number of tiles that are misplaced.
        """
        if self.m_tile_count != -1:
            return self.m_tile_count

        # Iterate over the final board and the current board and check which tiles are misplaced.
        self.m_tile_count = 0
        for row in range(self.board_size):
            for col in range(self.board_size):

                # Increment count only if Board position is not an empty position
                if (self._state[row][col] != 0) \
                        and (self._state[row][col] != Board.final[row][col]):
                    self.m_tile_count = self.m_tile_count + 1

        return self.m_tile_count

    def manhattan_distance(self):
        """
        Return the Manhattan distance of the board from the final solved state.

        :return: The Manhattan distance.
        """
        if self.m_dist != -1:
            return self.m_dist

        # For each of the misplaced tiles, just need to take the absolute difference between the
        # rows and the columns and add them up.
        self.m_dist = 0
        for row in range(self.board_size):
            for col in range(self.board_size):
                r = -1
                c = -1
                k = self._state[row][col]
                if k == 0:
                    continue
                if k % self.board_size == 0:
                    r = (k / self.board_size) - 1
                    c = self.board_size - 1
                else:
                    r = int(k / self.board_size)
                    c = (k % self.board_size) - 1

                self.m_dist = self.m_dist + abs(r - row) + abs(c - col)
        return self.m_dist

    # Properties of this class
    @property
    def depth(self):
        return self._depth

    @depth.setter
    def depth(self, value):
        self._depth = value

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, value):
        self._state = value

    @property
    def cost(self):
        return self._cost

    @cost.setter
    def cost(self, value):
        self._cost = value

    @property
    def parent(self):
        return self._parent

    @parent.setter
    def parent(self, value):
        self._parent = value

    @staticmethod
    def print_board_from_initial_state(board):
        """
        Print the board states from the beginning to the end.

        :param board: Board to print.
        :return: None
        """
        if board is None:
            return

        # Print the board states higher up in the Tree first
        Board.print_board_from_initial_state(board.parent)
        board.print_board()

    @staticmethod
    def get_depth(board):
        """
        Get the cost of a solved state recursively by adding 1 to the cost
        until the root node is reached.

        :param board: Board for which cost is required.
        :return: 1 + the cost of the parent node.
        """
        if board is None:
            return 0

        return 1 + Board.get_depth(board.parent)

    @staticmethod
    def get_board_for_size(size):
        """
        Create a solved board based on the size provided. Ex - if size = 5, return a solved 24-Puzzle.

        :param size: No. of elements in one row.
        :return: A solved N-Puzzle.
        """
        for i in size:
            for j in size:
                Board.final[i][j] = (i * size) + j + 1


def f(g5,g3,other):
    if not other:
        if abs(sum(g5)-sum(g3))==0:
            return True
        return 0

    if f(g5+[other[0]], g3,other[1:]) or f(g5 , g3+[other[0]],other[1:] ):
        return True
    return False
    # if arr==[]:
    #     if abs(sum(g5)-sum(g3))==0:
    #         return 1
    #     return 0
    # for i in range(len(arr)):
    #     if arr[i]%5==0:
    #         return f(arr[:i]+arr[i+1:],g5+[arr[i]],g3)
    #     elif arr[i]%3==0:
    #         return f(arr[:i]+arr[i+1:],g5,g3+[arr[i]])
    #     else:
    #         if f(arr[:i]+arr[i+1:], g5+[arr[i]], g3) or f(arr[:i] + arr[i + 1:], g5 , g3+[arr[i]]):
    #             return True
    # return False
'''
4
1 5 -5 1
~
13
3 0 1 3 -2 -1 4 -2 -1 5 0 -2 -2
'''
while True:
    try:
        n=int(input())
        arr=list(map(int,input().split(' ')[:n]))
        g5=[]
        g3=[]
        other=[]
        for v in arr:
            if v%5==0:
                g5.append(v)
            elif v%3==0:
                g3.append(v)
            else:
                other.append(v)
        print('true') if f(g5,g3,other) else print('false')
    except:
        break


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

'''
Created on 03/02/2016

@author: david
'''

from copy import deepcopy
from math import pi as PI, sin, radians, sqrt, asin, degrees
from operator import add
import time

from emulation.propeller import Propeller
from emulation.state import State

class EmulatedDrone(object):
    '''
    Emulates a physical drone
    '''

    #TODO: Create config
    REALISTIC_FLIGHT = False #Realistic or ideal flight emulation mode
    HANGED_MODE = True #Emulates the drone hanged by ropes. It doesn't move, but speeds and accelerations changes.
    X_CONFIGURATON = True # Indicates whether the drone is configured as X or +
    PROPELLER_THRUST_RATE = 0.0075 # 0.75kg/propeller @100% (total x4 propellers: 3.0kg max. thrust)
    PROPELLER_COUNTER_ROTATION_RATE = 1000.0
    WEIGHT = 1.6 # kg
    MAX_CRASH_SPEED = -1000.0 #m/s
    ARM_LENGTH = 0.23 #m

    HORIZONTAL_FRICTION_CONSTANT = 0.1
    VERTICAL_FRICTION_CONSTANT = 0.4
    #end config

    R1 = sqrt(2.0)/2.0 # constant used for angle rotation in X-configuration mode

    _instance = None

    @staticmethod
    def getInstance():

        if EmulatedDrone._instance == None:
            EmulatedDrone._instance = EmulatedDrone()

        return EmulatedDrone._instance

    def __init__(self):

        self._realisticFlight = EmulatedDrone.REALISTIC_FLIGHT

        self._state = State()
        if EmulatedDrone.X_CONFIGURATON:
            self._state._angles = [0.0, 0.0, -45.0]

        if EmulatedDrone.HANGED_MODE:
            self._state._coords = [0.0, 0.0, 1.0]

        self._weight = EmulatedDrone.WEIGHT
        self._armLength = EmulatedDrone.ARM_LENGTH
        self._arcSpeedToAngleSpeed = 180.0/PI*self._armLength

        # Propellers and motor are configured as follows:
        #
        #               (4) ^ (1)
        #                  \ /
        #                   X
        #                  / \
        #               (3)   (2)
        #
        if self._realisticFlight:

            self._propellers = [Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 0.98, 1.01 * self._weight/4.0, Propeller.ROTATION_CCW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE),
                                Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 0.97, 0.97 * self._weight/4.0, Propeller.ROTATION_CW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE),
                                Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 0.96, 0.99 * self._weight/4.0, Propeller.ROTATION_CCW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE),
                                Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 0.99, 1.03 * self._weight/4.0, Propeller.ROTATION_CW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE)]
        else:

            self._propellers = [Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 1.0, self._weight/4.0, Propeller.ROTATION_CCW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE),
                                Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 1.0, self._weight/4.0, Propeller.ROTATION_CW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE),
                                Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 1.0, self._weight/4.0, Propeller.ROTATION_CCW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE),
                                Propeller(self, EmulatedDrone.PROPELLER_THRUST_RATE, 1.0, self._weight/4.0, Propeller.ROTATION_CW, EmulatedDrone.PROPELLER_COUNTER_ROTATION_RATE)]

        self._propellersCount = len(self._propellers)

        self._propellersUpdatedCount = 0

    def getPropeller(self, index):

        return self._propellers[index]

    def _updateStatus(self):

        if self._state._time and not self._state._crashed:

            currentTime = time.time()
            dt = currentTime - self._state._time
            #Detect pid stopped
            if dt > 0.1:
                dt = 0.0
            dt2 = dt/2.0
            self._state._time = currentTime

            #Accelerations

            previousAngleSpeedZ = self._state._angleSpeeds[2]
            self._state._angleSpeeds[2] = 0.0

            forces = [0.0]*3
            for propeller in self._propellers:

                propellerForces = propeller.getThrust()
                self._state._angleSpeeds[2] += propeller.getTorque()
                forces = map(add, forces, propellerForces)

            forces = [force for force in forces]
            forces[0] -= self._state._speeds[0] * EmulatedDrone.HORIZONTAL_FRICTION_CONSTANT
            forces[1] -= self._state._speeds[1] * EmulatedDrone.HORIZONTAL_FRICTION_CONSTANT
            forces[2] -= self._state._speeds[2] * EmulatedDrone.VERTICAL_FRICTION_CONSTANT

            previousAccels = deepcopy(self._state._accels)
            self._state._accels = [force / self._weight for force in forces]

            #Speed & position
            if EmulatedDrone.HANGED_MODE:

                for index in range(3):
                    self._state._speeds[index] += (self._state._accels[index] + previousAccels[index]) * dt2

            else:
                for index in range(3):
                    previousSpeed = self._state._speeds[index]
                    self._state._speeds[index] += (self._state._accels[index] + previousAccels[index]) * dt2
                    self._state._coords[index] += (self._state._speeds[index] + previousSpeed) * dt2

            #The drone can not fly underground
            if self._state._coords[2] <= 0.0 and self._state._speeds[2] <= 0.0:

                self._state._crashed = self._state._speeds[2] < EmulatedDrone.MAX_CRASH_SPEED

                self._state._coords[2] = 0.0
                self._state._accels = [0.0]*3
                self._state._speeds = [0.0]*3
                self._state._angles = [0.0, 0.0, self._state._angles[2]]
                self._state._angleSpeeds = [0.0]*3

                '''
                elif self._state._coords[2] >= 0.5 and self._state._speeds[2] > 0.0:

                    self._state._coords[2] = 0.5
                    self._state._accels = [0.0]*3
                    self._state._speeds = [0.0]*3
                '''
            else:

                #Calculate drone's current yaw (self._state._angles[2])
                #Positive angles are CCW for axis Z
                self._state._angles[2] += (self._state._angleSpeeds[2] + previousAngleSpeedZ) * dt2
                self._state._angles[2] = self._normalizeAngle(self._state._angles[2])

                #Calculate drone's angle-speeds
                accelAxisX = self._propellers[3].getOrtogonalAccel() - self._propellers[1].getOrtogonalAccel()
                previousAngleSpeedX = self._state._angleSpeeds[0]
                self._state._angleSpeeds[0] += accelAxisX * dt * self._arcSpeedToAngleSpeed

                accelAxisY = self._propellers[2].getOrtogonalAccel() - self._propellers[0].getOrtogonalAccel()
                previousAngleSpeedY = self._state._angleSpeeds[1]
                self._state._angleSpeeds[1] += accelAxisY * dt * self._arcSpeedToAngleSpeed

                #Calculate drone's angles (heading was already calculated)
                self._state._angles[0] += (self._state._angleSpeeds[0] + previousAngleSpeedX) * dt2
                self._state._angles[0] = self._normalizeAngle(self._state._angles[0])
                self._state._angles[1] += (self._state._angleSpeeds[1] + previousAngleSpeedY) * dt2
                self._state._angles[1] = self._normalizeAngle(self._state._angles[1])

            #Update propeller angles
            for propeller in self._propellers:
                propeller.setAngles(self._state._angles)

            #if dt < 1.0:
            #    print self._state

    def _normalizeAngle(self, angle):

        if angle < -180.0:
            angle +=  360.0
        elif angle > 180.0:
            angle -= 360.0

        return angle

    def getState(self):

        currentState = deepcopy(self._state)

        if EmulatedDrone.X_CONFIGURATON:
            #Rotate angles +45º
            droneAngleX = radians(currentState._angles[0])
            droneAngleY = radians(currentState._angles[1])

            sinX = sin(droneAngleX)
            sinY = sin(droneAngleY)

            hx = (sinX + sinY)/2.0
            hy = (sinY - sinX)/2.0

            worldAngleX = degrees(asin(hx/EmulatedDrone.R1))
            worldAngleY = degrees(asin(hy/EmulatedDrone.R1))
            worldAngleZ = currentState._angles[2] + 45.0

            currentState._angles = [worldAngleX, worldAngleY, worldAngleZ]

        return currentState

    def initStateTime(self):

        self._state._time = time.time()

    def onPropellerUpdated(self):

        self._propellersUpdatedCount += 1
        if self._propellersUpdatedCount == self._propellersCount:

            self._updateStatus()
            self._propellersUpdatedCount = 0

        elif self._propellersUpdatedCount > self._propellersCount:

            raise Exception("Error: Any propellers updated unsuccesfully.")