from typing import Optional, overload, TYPE_CHECKING, Dict, Union

from docarray.array.base import BaseDocumentArray
from docarray.array.mixins import AllMixins

if TYPE_CHECKING:
    from docarray.typing import DocumentArraySourceType
    from docarray.array.memory import DocumentArrayInMemory
    from docarray.array.sqlite import DocumentArraySqlite
    from docarray.array.annlite import DocumentArrayAnnlite
    from docarray.array.weaviate import DocumentArrayWeaviate
    from docarray.array.elastic import DocumentArrayElastic
    from docarray.array.redis import DocumentArrayRedis
    from docarray.array.storage.sqlite import SqliteConfig
    from docarray.array.storage.annlite import AnnliteConfig
    from docarray.array.storage.weaviate import WeaviateConfig
    from docarray.array.storage.elastic import ElasticConfig
    from docarray.array.storage.redis import RedisConfig

class DocumentArray(AllMixins, BaseDocumentArray):
    """
    DocumentArray is a list-like container of :class:`~docarray.Document` objects.

    A DocumentArray can be used to store, embed, and retrieve :class:`~docarray.Document` objects.

    .. code-block:: python

        from docarray import Document, DocumentArray

        da = DocumentArray(
            [Document(text='The cake is a lie'), Document(text='Do a barrel roll!')]
        )
        da.apply(Document.embed_feature_hashing)

        query = Document(text='Can i have some cake?').embed_feature_hashing()
        query.match(da, metric='jaccard', use_scipy=True)

        print(query.matches[:, ('text', 'scores__jaccard__value')])

    .. code-block:: bash

        [['The cake is a lie', 'Do a barrel roll!'], [0.9, 1.0]]

    A DocumentArray can also :ref:`embed its contents using a neural network <embed-via-model>`,
    process them using an :ref:`external Flow or Executor <da-post>`, and persist Documents in a :ref:`Document Store <doc-store>` for
    fast vector search:

    .. code-block:: python

        from docarray import Document, DocumentArray
        import numpy as np

        n_dim = 3
        metric = 'Euclidean'

        # initialize a DocumentArray with ANNLiter Document Store
        da = DocumentArray(
            storage='annlite',
            config={'n_dim': n_dim, 'columns': [('price', 'float')], 'metric': metric},
        )
        # add Documents to the DocumentArray
        with da:
            da.extend(
                [
                    Document(id=f'r{i}', embedding=i * np.ones(n_dim), tags={'price': i})
                    for i in range(10)
                ]
            )
        # perform vector search
        np_query = np.ones(n_dim) * 8
        results = da.find(np_query)

    .. seealso::
        For further details, see our :ref:`user guide <documentarray>`.
    """

    @overload
    def __new__(
        cls,
        _docs: Optional['DocumentArraySourceType'] = None,
        copy: bool = False,
        subindex_configs: Optional[Dict[str, 'None']] = None,
    ) -> 'DocumentArrayInMemory':
        """Create an in-memory DocumentArray object."""
        ...

    @overload
    def __new__(
        cls,
        _docs: Optional['DocumentArraySourceType'] = None,
        storage: str = 'sqlite',
        config: Optional[Union['SqliteConfig', Dict]] = None,
        subindex_configs: Optional[Dict[str, Dict]] = None,
    ) -> 'DocumentArraySqlite':
        """Create a SQLite-powered DocumentArray object."""
        ...

    @overload
    def __new__(
        cls,
        _docs: Optional['DocumentArraySourceType'] = None,
        storage: str = 'weaviate',
        config: Optional[Union['WeaviateConfig', Dict]] = None,
        subindex_configs: Optional[Dict[str, Dict]] = None,
    ) -> 'DocumentArrayWeaviate':
        """Create a Weaviate-powered DocumentArray object."""
        ...

    @overload
    def __new__(
        cls,
        _docs: Optional['DocumentArraySourceType'] = None,
        storage: str = 'annlite',
        config: Optional[Union['AnnliteConfig', Dict]] = None,
        subindex_configs: Optional[Dict[str, Dict]] = None,
    ) -> 'DocumentArrayAnnlite':
        """Create a AnnLite-powered DocumentArray object."""
        ...

    @overload
    def __new__(
        cls,
        _docs: Optional['DocumentArraySourceType'] = None,
        storage: str = 'elasticsearch',
        config: Optional[Union['ElasticConfig', Dict]] = None,
        subindex_configs: Optional[Dict[str, Dict]] = None,
    ) -> 'DocumentArrayElastic':
        """Create a Elastic-powered DocumentArray object."""
        ...

    @overload
    def __new__(
        cls,
        _docs: Optional['DocumentArraySourceType'] = None,
        storage: str = 'redis',
        config: Optional[Union['RedisConfig', Dict]] = None,
    ) -> 'DocumentArrayRedis':
        """Create a Redis-powered DocumentArray object."""
        ...

    def __enter__(self):
        return self

    def __exit__(self, *args, **kwargs):
        """
        Ensures that offset2ids are stored in the db after
        operations in the DocumentArray are performed.
        """
        self._save_offset2ids()

    def __new__(cls, *args, storage: str = 'memory', **kwargs):
        if cls is DocumentArray:
            if storage == 'memory':
                from docarray.array.memory import DocumentArrayInMemory

                instance = super().__new__(DocumentArrayInMemory)
            elif storage == 'sqlite':
                from docarray.array.sqlite import DocumentArraySqlite

                instance = super().__new__(DocumentArraySqlite)
            elif storage == 'annlite':
                from docarray.array.annlite import DocumentArrayAnnlite

                instance = super().__new__(DocumentArrayAnnlite)
            elif storage == 'weaviate':
                from docarray.array.weaviate import DocumentArrayWeaviate

                instance = super().__new__(DocumentArrayWeaviate)
            elif storage == 'qdrant':
                from docarray.array.qdrant import DocumentArrayQdrant

                instance = super().__new__(DocumentArrayQdrant)
            elif storage == 'elasticsearch':
                from docarray.array.elastic import DocumentArrayElastic

                instance = super().__new__(DocumentArrayElastic)
            elif storage == 'redis':
                from .redis import DocumentArrayRedis

                instance = super().__new__(DocumentArrayRedis)

            else:
                raise ValueError(f'storage=`{storage}` is not supported.')
        else:
            instance = super().__new__(cls)
        return instance


from sys import stdin
n =int(stdin.readline())
for _ in range(n):
    stack = []
    PS = stdin.readline().rstrip()
    for ps in PS:
        if ps == '(':
            stack.append(ps)
        else:
            if not stack:
                print('NO')
                break
            else:
                stack.pop()
    else:
        if stack:
            print('NO')
        else:
            print('YES')


import numpy as np
from matplotlib import pyplot as plt

def draw_2D(f, points=None, scale=100, rate=100):
    """
    Drawing chart of a 2D function 'f'.

    Furthermore, drawing gradient descent work result in case points is not None

    :param f: a 2D function to draw
    :param points: optional. gradient descent work result
    :param scale: chart axis scale to draw
    :param rate: count of x-axis points to build f chart.
    :return: Nothing
    """
    xs = np.linspace(-scale, scale, rate)
    ys = np.array(list(map(lambda x: f([x]), xs)))

    if points is not None:
        plt.plot(points[:, 0], points[:, 1], 'r.')
    plt.plot(xs, ys)

    plt.show()

def draw_3D(f, points=None, scale=100, rate=100):
    """
    Drawing chart of a 3D function 'f'.

    Furthermore, drawing gradient descent work result in case points is not None

    :param f: a 3D function to draw
    :param points: optional. gradient descent work result
    :param scale: chart axis scale to draw
    :param rate: count of x-axis and y-axis points to build f chart.
    :return: Nothing
    """
    t = np.linspace(-scale, scale, rate)
    X, Y = np.meshgrid(t, t)
    ax = plt.figure().add_subplot(projection='3d')
    ax.plot_surface(X, Y, f([X, Y]))

    if points is not None:
        XS = np.array([])
        YS = np.array([])
        ZS = points[:, 1]

        for point in points[:, 0]:
            XS = np.append(XS, point[0])
            YS = np.append(YS, point[1])

        ax_points = plt.figure().add_subplot(projection='3d')
        ax_points.scatter(XS, YS, ZS, c='r')

        ax_levels = plt.figure().add_subplot()
        ax_levels.contour(X, Y, f([X, Y]), levels=sorted(
            [f([p[0], p[1]]) for p in points[:, 0]] + list(np.linspace(-1, 1, 100))))
        ax_levels.plot(XS, YS, 'r.')

    plt.show()


# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
from http.client import HTTPSConnection

# https://finance.naver.com/item/sise_day.nhn?code=005930&page=2

cCode = '005930'    # 삼성전자

h = {'User-agent' : 'mozilla/5.0'}
d = []

con = HTTPSConnection("finance.naver.com")
for page in range(1, 11):
    con.request("GET", "/item/sise_day.nhn?code=%s&page=%s" % (cCode, page), headers = h)
    rb = con.getresponse().read()
    # print(rb)
    ssMarketData = BeautifulSoup(rb, "html.parser", from_encoding = "euc-kr")
    # print(ssMarketData)
    ssMarketDatas = ssMarketData.select("td span")
    # print(ssMarketDatas)
    # 종가    전일비    시가    고가    저가    거래량
    for m in ssMarketDatas:
        # print(m.text.strip())
        d.append(m.text.strip())

print(d)


import unittest

class Compressor(object):
    """
    Wrapper for simple lossless compression operations
    Examples:
        1. Compression
            a. ``abbccc`` becomes ``a1b2c3``
            b. ``aaaaaaaaaaaaaaa`` becomes  `a12`
        2. Decompression, does the opposite of compression
            a. ````
    """

    @classmethod
    def compress(cls, original: str) -> str:
        compressed = ''

        last_character = ''
        count = 0

        # for index in range(len(original) - 1):
        #     if character == last_character:
        #         count += 1
        #     elif last_character != '':

        return compressed

    @classmethod
    def recursive_compression(cls, original: str) -> str:
        return Compressor.recursive_compression_helper(original, 0, 1, '')

    @classmethod
    def recursive_compression_helper(cls, original, index, count, answer):
        if index == len(original) - 1:
            answer += original[index] + str(count)

        elif original[index] == original[index + 1]:
            answer = Compressor.recursive_compression_helper(original, index + 1, count + 1, answer)

        else:
            answer += original[index] + str(count)
            return Compressor.recursive_compression_helper(original, index + 1, 1, answer)

        return answer

    @classmethod
    def recursive_decompression(cls, compressed: str) -> str:
        return Compressor.recursive_decompression_helper(compressed, 0, '', 0, '')

    @classmethod
    def recursive_decompression_helper(cls, compressed: str, count, last_character, index, answer) -> str:
        if index == len(compressed) - 1:
            answer += int(count) * last_character

        elif compressed[index].isdigit():
            count += compressed[index]
            return Compressor.recursive_decompression_helper(compressed, count, last_character, index + 1, answer)

        else:
            answer += int(count) * last_character
            last_character = compressed[index]
            answer += Compressor.recursive_decompression_helper(compressed, '0', last_character, index + 1, answer)

        return answer

if __name__ == '__main__':
    # print(Compressor.recursive_compression('aaaaaaaaaabbbccll'))
    print(Compressor.recursive_decompression('a10c2'))


# 01-monty-hall

import random
choice = 0 # or None
gift = None
opened = None
win = 0
trial = counter= 10000

while counter > 0:
    counter -= 1
    choise = 1
    gift = random.randrange(1, 4)
    if gift == 2:
        opened = 3
    elif gift == 3:
        opened = 2
    else:
        opened = random.randrange(2, 4)

    if opened == 2:
        choice = 3
    else:
        choice = 2

    if choice == gift:
        win +=1

result = win/trial * 100
out = 'Change door and win {}%'.format(result)
print(out)


import numpy as np
import matplotlib.pyplot as plt
import pydrr as pd #pd: DRR

#DATAPATH:
#https://github.com/chenyk1990/reproducible_research/blob/master/odrr5d/matfun/yc_synth5d.mat

#load data
import scipy
from scipy import io
datas=scipy.io.loadmat("yc_synth5d.mat")
d=datas['data5d'];
d=d/d.max();

#add noise
[n1,n2,n3,n4,n5]=d.shape;
np.random.seed(201415)
n=0.1*np.random.randn(n1,n2,n3,n4,n5);
dn=d+n;
print(np.std(dn))

## decimate traces
ratio=0.3;
mask=pd.genmask(dn.reshape(n1,n2*n3*n4*n5,order='F'),ratio,'c',201415);
mask=mask.reshape(n1,n2,n3,n4,n5,order='F');
d0=dn*mask;
print(np.std(d0))

## Recon
flow=5;fhigh=100;dt=0.004;N=4;NN=3;Niter=10;mode=1;a=np.linspace(1,0,10);verb=1;eps=0.00000000001;
d1=pd.drr5drecon(d0,mask,flow,fhigh,dt,N,100,Niter,eps,mode,a,verb);
d2=pd.drr5drecon(d0,mask,flow,fhigh,dt,N,NN,Niter,eps,mode,a,verb);
noi1=d-d1;
noi2=d-d2;

## compare SNR
snr1=pd.snr(d[:,:,:,5,5],d1[:,:,:,5,5],2);
snr2=pd.snr(d[:,:,:,5,5],d2[:,:,:,5,5],2);
print('SNR of RR is %g'%snr1);
print('SNR of DRR is %g'%snr2);

## compare with matlab
import scipy
from scipy import io
datas = {"d0":d0,"dc":d,"mask":mask,"dn": dn, "d1": d1, "noi1": noi1, "d2":d2, "noi2":noi2}
scipy.io.savemat("datas5d.mat", datas)

## plotting
fig = plt.figure(figsize=(8, 8))
ax=fig.add_subplot(3, 2, 1)
plt.imshow(dn[:,:,:,5,5].transpose(0,2,1).reshape(n1,n2*n3),cmap='jet',clim=(-0.05,0.05),aspect='auto');ax.set_xticks([]);ax.set_yticks([]);
plt.title('Noisy data');
ax=fig.add_subplot(3, 2, 2)
plt.imshow(d0[:,:,:,5,5].transpose(0,2,1).reshape(n1,n2*n3),cmap='jet',clim=(-0.05,0.05),aspect='auto');ax.set_xticks([]);ax.set_yticks([]);
plt.title('Incomplete data');
ax=fig.add_subplot(3, 2, 3)
plt.imshow(d1[:,:,:,5,5].reshape(n1,n2*n3,order='F'),cmap='jet',clim=(-0.05,0.05),aspect='auto');ax.set_xticks([]);ax.set_yticks([]);
plt.title('Reconstructed (RR, SNR=%.4g dB)'%snr1);
ax=fig.add_subplot(3, 2, 4)
plt.imshow(noi1[:,:,:,5,5].transpose(0,2,1).reshape(n1,n2*n3),cmap='jet',clim=(-0.05,0.05),aspect='auto');ax.set_xticks([]);ax.set_yticks([]);
plt.title('Error (RR)');
ax=fig.add_subplot(3, 2, 5)
plt.imshow(d2[:,:,:,5,5].reshape(n1,n2*n3,order='F'),cmap='jet',clim=(-0.05,0.05),aspect='auto');ax.set_xticks([]);ax.set_yticks([]);
plt.title('Reconstructed (DRR, SNR=%.4g dB)'%snr2);
ax=fig.add_subplot(3, 2, 6)
plt.imshow(noi2[:,:,:,5,5].transpose(0,2,1).reshape(n1,n2*n3),cmap='jet',clim=(-0.05,0.05),aspect='auto');ax.set_xticks([]);ax.set_yticks([]);
plt.title('Error (DRR)');
plt.savefig('test_pydrr_drr5drecon.png',format='png',dpi=300);
plt.show()


import cv2 as cv
import mediapipe as mp

def process_img(img, face_detection):
    img_rgb = cv.cvtColor(img, cv.COLOR_BGR2RGB)
    out = face_detection.process(img_rgb)
    if out.detections is not None:
        for detection in out.detections:
            location_data = detection.location_data
            bbox = location_data.relative_bounding_box
            x1, y1, w, h = bbox.xmin, bbox.ymin, bbox.width, bbox.height
            x1 = int(x1 * W) - 30
            y1 = int(y1 * H)
            w = int(w * W)
            h = int(h * H)
            # cv.rectangle(img, (x1, y1), (x1+w, y1+h), (0,255,0), 10)
            # # Blur the face
            img[y1:y1 + h, x1:x1 + w] = cv.blur(img[y1:y1 + h, x1:x1 + w], (30, 30))

    return img

cap = cv.VideoCapture(0)
W, H = 720, 480
cap.set(3, W)
cap.set(4, H)

while 1:
    # # Read Image
    ret, img = cap.read()

    # # Detect faces
    mp_face_detection = mp.solutions.face_detection

    with mp_face_detection.FaceDetection(min_detection_confidence=0.5, model_selection=0) as face_detection:
        img = process_img(img=img, face_detection=face_detection)

    cv.imshow('Image', img)
    cv.waitKey(25)


import cherrypy
from cherrypy.test import helper

class SimpleCPTest(helper.CPWebCase):
	def setup_server():
		class Root(object):
			@cherrypy.expose
			def echo(self, message):
				return message

		cherrypy.tree.mount(Root())
	setup_server = staticmethod(setup_server)

	def test_message_should_be_retuned_as_is(self):
		self.getPage("/echo?message=Hello%20World")
		self.assertStatus('200 OK')
		self.assertHeader('Content-Type', 'text/html;charset=utf-8')
		self.assertBody('Hello World')

	def test_non_utf8_message_will_fail(self):
		self.getPage("/echo?message=A+bient%F4t",
					headers=[
						('Accept-Charset', 'ISO-8859-1,utf-8'),
						('Content-Type', 'text/html;charset=ISO-8859-1')
					]
		)
		self.assertStatus('404 Not Found')


from prodo.project import Project
import prodo.actions as actions
import json
import argparse

def main():
    parser = argparse.ArgumentParser(
        description="Project development software")
    parser.add_argument('--version', action='version', version='%(prog)s 0.0')
    parser.add_argument('--list', action='store_true',
                        help="Lists all past and active sprints")
    parser.add_argument('--sprint', nargs='?', type=int, default=1,
                        help="Select sprint to focus on (default \'Current\')")
    subparsers = parser.add_subparsers(
        help="Different actions commands", dest='command')
    add = subparsers.add_parser('add')
    add.add_argument('name', nargs='?', help="Task name to add")
    add.add_argument('description', nargs='?', help="Task description")
    add.add_argument('--tasks', nargs='*', help="Sub tasks to complete")
    add.add_argument('--tags', nargs='*', help="Tags to categorize task")
    add.add_argument('--dev', nargs='*', help="Name of assigned developer")
    mod = subparsers.add_parser('modify')
    mod.add_argument('id', type=int, help="Id identifier of task in sprint")
    mod.add_argument('name', nargs='?', help="Task name")
    mod.add_argument('description', nargs='?', help="Task description")
    mod.add_argument('--tasks', nargs='*', help="Sub tasks to complete")
    mod.add_argument('--tags', nargs='*', help="Tags to categorize task")
    mod.add_argument('--dev', nargs='*', help="Name of assigned developer")
    dlt = subparsers.add_parser('delete')
    dlt.add_argument('id', type=int, help="Id of task in sprint to delete")
    move = subparsers.add_parser('move')
    move.add_argument('id', type=int, help="Id identifier of task in sprint")
    move.add_argument('column', nargs='?',
                      help="Destination column to place task")
    new = subparsers.add_parser('new')
    new.add_argument('object', type=str, choices=[
                     "column", "sprint"], help="Object to create new of")
    new.add_argument('name', nargs='?', help="Name of new object")
    lst = subparsers.add_parser('list')
    start = subparsers.add_parser('start')
    args = parser.parse_args()
    print(args)
    proj = Project(json.load(open('prodo.json')))
    actions.preform_action(proj, args)
    json.dump(proj.write(), open('prodo.json', 'w'))

if __name__ == "__main__":
    main()


from pylab import *

import getpass
users={"candi": "C:\\Users\\candi\\Documents\\GitHub\\Lab3.2\\",
"silvanamorreale":"C:\\Users\\silvanamorreale\\Documents\\GitHub\\Lab3.2\\" ,
"Studenti": "C:\\Users\\Studenti\\Desktop\\Lab3\\",
"User":"C:\\Users\\User\\Documents\\GitHub\\Lab3.2\\"
}
try:
    user=getpass.getuser()
    path=users[user]
    print("buongiorno ", user, "!!!")
except:
    raise Error("unknown user, please specify it and the path in the file Esercitazione*.py")

sys.path = sys.path + [path]
dir= path + "Esercitazione11\\"

from BuzzLightyear import *
from uncertainties import *
import uncertainties
###########################################################################

from Oscillografo import *

AB = OscilloscopeData(dir+"data\\AB.csv")
andAO = OscilloscopeData(dir+"data\\andAO.csv")
orAO = OscilloscopeData(dir+"data\\orAO.csv")
xorAO = OscilloscopeData(dir+"data\\xorAO.csv")

figure(1)
fig,ax = subplots(1)

plot(AB.T1, AB.CH1, ",--", label="input1")
plot(AB.T2, AB.CH2, ",--", label="input2")
plot(andAO.T2, andAO.CH2, ",-", label="AND")

ax.set_yticklabels([])
ax.set_xticklabels([])
legend(loc=6)
grid()
savefig(dir + "grafici\\ANDard.pdf")

figure(2)
fig,ax = subplots(1)
grid()
plot(AB.T1, AB.CH1, ",--", label="input1")
plot(AB.T2, AB.CH2, ",--", label="input2")
plot(orAO.T2, orAO.CH2, ",-", label="OR")

ax.set_yticklabels([])
ax.set_xticklabels([])
legend(loc=6)
grid()
savefig(dir + "grafici\\ORard.pdf")

figure(3)
fig,ax = subplots(1)

plot(AB.T1, AB.CH1, ",--", label="input1")
plot(AB.T2, AB.CH2, ",--", label="input2")
plot(xorAO.T2, xorAO.CH2, ",-", label="XOR")

ax.set_yticklabels([])
ax.set_xticklabels([])
legend(loc=6)
grid()
savefig(dir + "grafici\\XORard.pdf")

figure(4)
fig,ax = subplots(1)

plot(AB.T1, AB.CH1, ",:", label="input1")
plot(AB.T2, AB.CH2, ",:", label="input2")
plot(xorAO.T2, xorAO.CH2, ",--", label="SUM")
plot(andAO.T2, andAO.CH2, ",-", label="CARRY")

ax.set_yticklabels([])
ax.set_xticklabels([])
legend(loc=6)

savefig(dir + "grafici\\ADDERard.pdf")

# show()
close('all')

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

file = "astabileRes"
data = load_data(dir,file)
data_err = [mme(data[0], 'ohm'), mme(data[1], 'time', 'oscil')]
# data_err = [mme(data[0], 'ohm'), sqrt(((mme(data[1], 'time', 'oscil'))**2)+(3*data[1]/100)**2)]
tab=["$R_2$ [$\Omega$]","Period [s]"]

latex_table(dir, file, data, data_err, tab)

par, cov = fit_linear(data[0], data[1], dx=data_err[0], dy=data_err[1])
m, q = correlated_values(par, cov)

line = lambda x, m, q: m*x + q

x = linspace(min(data[0])*0.9, max(data[0])*1.05, 1000)
y = line(x, m.nominal_value, q.nominal_value)

chi2 = sum(((data[1] - line(data[0], m.nominal_value, q.nominal_value))/data_err[1])**2)
print(chi2)
print(cov[0,1]/(sqrt(cov[0,0]*cov[1,1])))
errorbar(data[0], data[1], xerr=data_err[0], yerr=data_err[1], fmt=',')
plot(x, y)

xlim(min(data[0])*0.88, max(data[0])*1.06)
ylim(min(data[1])*0.88, max(data[1])*1.06)
xlabel(tab[0], fontsize = 24)
ylabel(tab[1], fontsize = 24)
ticklabel_format(style='sci', axis='both', scilimits=(0,0))
grid()
savefig(dir + "./grafici/FITastabile.pdf")

########################################################################### parte astabile-stabile in serie...
#preambolo

C3 = ufloat(10.38e-9,mme(10.38e-9, "farad"))
R3 = ufloat(990, mme(990, "ohm"))

freq=1/(C3*R3)
print("frequanza di taglio=", freq)

#grafici...
O1 = OscilloscopeData(dir+"data\\4OutM.csv")
O2 = OscilloscopeData(dir+"data\\410030.csv")

figure(123)

plot(O1.T1, O1.CH1)
plot(O1.T2, O1.CH2)
grid()
figure(1234)

plot(O2.T1, O2.CH1)
plot(O2.T2, O2.CH2)
grid()

#analisi tempi...

myprint_dict={}

def printufloat(X):
    x=X.n
    y=X.s
    return str(x)+" \\pm "+str(y)

myprint_dict[uncertainties.ufloat]=printufloat
myprint_dict[uncertainties.core.AffineScalarFunc]=printufloat
myprint_dict[uncertainties.core.Variable]=printufloat

def printArray(x):
    s="array(["
    for i in x:
        s+=myprint(i)+","
    return s+"])"

myprint_dict[np.array]=printArray

def myprint(x):
    print(type(x), x, "<-----------")
    if type(x) in myprint_dict:
        print(type(x))
        return myprint_dict[type(x)](x)
    return str(x)

def my_latex_table(directory, file_, data, tab, verbose=True):
    """
        Parameters
        ----------

        Returns
        -------

    """
    with open(directory+"tabelle/tab_"+file_+".txt", "w") as text_file:
       # print(data)
        text_file.write("\\begin{tabular}{c")
        for z in range (1,len(tab)):
            text_file.write("|c")
        text_file.write("} \n")
        text_file.write("%s" % tab[0])
        for z in range (1,len(tab)):
            text_file.write(" & %s" % tab[z])
        text_file.write("\\\\\n\hline\n")
        for i in range (len(data[0])):
            text_file.write("%s" % myprint(data[0][i]))
            for j in range (1,len(tab)):
                print(i, j)
                print(data[j][i])
                text_file.write(" & %s" % myprint(data[j][i]))
            text_file.write("\\\\\n")
        text_file.write("\\end{tabular}")
        text_file.close()

file="bothRes.txt"
data=np.loadtxt(dir+"\\data\\bothRes.txt")
R1=data[:,0]
dR1=mme(R1, "ohm")
R2=data[:,1]
dR2=mme(R2, "ohm")
T1=data[:,2]*1e-6
dT1=np.ones(T1.shape)*1e-6
T2=data[:,3]*1e-6
dT2=np.ones(T2.shape)*1e-6
#approccio fit multipli...

from itertools import cycle
cycol = cycle('bgrcmk')

print("Fit per righe...")

figure(2)
# pylab.title("$R_1$ vs $T_{duty}$")
pylab.xlabel("$R_1$ [ohm]")
pylab.ylabel("$T_{duty}$ [sec]")
grid()

se={}
for i,j in zip(R2, dR2):
    if(not (i in se)):
        se[i]=j

results=[]
cond=[]
legs=[]
lines=[]

for i in se:
    mask=R2==i
    r1=R1[mask]
    dr1=dR1[mask]
    t1=T1[mask]
    dt1=dT1[mask]
    t2=T2[mask]
    dt2=dT2[mask]
    print(i)
    print(r1)
    par, cov = fit_linear(r1, t2, dx=dr1, dy=dt2)
    m, q = correlated_values(par, cov)
    chisq = sum((t2-line(r1, *par))**2/(par[0]**2*dr1**2+dt2**2))
    cond.append(ufloat(i, se[i]))
    results.append([par, cov, m, q, chisq])
    print("m={} , q={}".format(m, q))
    print("chiq={} su {} dof".format(chisq, len(r1)))
    domain=np.linspace(np.min(r1), np.max(r1))
    color=next(cycol)
    iline,=pylab.plot(domain, line(domain, *par), color=color, label="$R_2={}$".format(i))
    lines.append(iline)
    pylab.errorbar(r1, t2, dt2, dr1, ".", color=color)
    #pylab.plot(domain, line(domain, *par), color=color)
    legs.append("$R_2={}$".format(i))
    print("==============")

pylab.legend(legs, handles=lines)
pylab.savefig(dir + "./grafici/FitsRighe.pdf")

results=np.array(results)
ms=results[:,2]
qs=results[:,3]
chisqs=results[:,4]
nomi=["$R_2$", "$T/R$", "$T_0$", "$\\chi^2$"]
f=uncertainties.unumpy.nominal_values
ff=uncertainties.unumpy.std_devs
my_latex_table(dir, "fit per righe.txt", [cond, ms, qs, chisqs], nomi)

mnvs=uncertainties.unumpy.nominal_values(ms)
mstds=uncertainties.unumpy.std_devs(ms)
mfin, varmfin=fit_const_yerr(mnvs, mstds)

qnvs=uncertainties.unumpy.nominal_values(qs)
qstds=uncertainties.unumpy.std_devs(qs)
qfin, varqfin=fit_const_yerr(qnvs, qstds)

chifin1=sum((mfin-mnvs)**2/mstds**2)
chifin2=sum((qfin-qnvs)**2/qstds**2)

figure(3)
# pylab.title("$R_2$ vs m, $R_2$ vs q")
pylab.xlabel("$R_2$ [Ohm]")
pylab.subplot(311)
pylab.plot(list(se.keys()),(mfin-mnvs)/mstds, 'b.')
pylab.subplot(312)
pylab.plot(list(se.keys()), (qfin-qnvs)/qstds, 'b.')
pylab.savefig(dir + "./grafici/FitRighe.pdf",bbox_inches='tight')

mfin=uncertainties.ufloat(mfin, varmfin**0.5)
qfin=uncertainties.ufloat(qfin, varqfin**0.5)

print("------>>>>   m={} , q={}, chisq1={},  chisq2={}, dof={}".format(mfin, qfin, chifin1, chifin2, len(mnvs)))
print("c'è qualche problema...")

print("=======================")
print("=======================")

print("Fit per colonne...")

figure(4)
# pylab.title("$R_2$ vs $T_{duty}$")
pylab.xlabel("$R_2$ [ohm]")
pylab.ylabel("$Periodo$ [sec]")
grid()
results=[]
cond=[]
legs=[]
lines=[]

se={}
for i,j in zip(R1, dR1):
    if(not (i in se)):
        se[i]=j

for i in se:
    mask=R1==i
    r2=R2[mask]
    if(len(r2)>2):
        dr2=dR2[mask]
        t1=T1[mask]
        dt1=dT1[mask]
        t2=T2[mask]
        dt2=dT2[mask]
        print(i)
        print(r2)
        par, cov = fit_linear(r2, t1, dx=dr2, dy=dt1)
        m, q = correlated_values(par, cov)
        chisq = sum((t1-line(r2, *par))**2/(par[0]**2*dr2**2+dt1**2))
        cond.append(ufloat(i, se[i]))
        results.append([par, cov, m, q, chisq])
        print("m={} , q={}".format(m, q))
        print("chiq={} su {} dof".format(chisq, len(r2)))
        domain=np.linspace(np.min(r2), np.max(r2))
        color=next(cycol)
        iline,=pylab.plot(domain, line(domain, *par), label="$R_1={}$".format(i), color=color)
        lines.append(iline)
        pylab.errorbar(r2, t1, dt1, dr2, ".", color=color)
        legs.append("$R_1={}$".format(i))
        print("==============")

pylab.legend(legs, handles=lines)
pylab.savefig(dir + "./grafici/FitsColonne.pdf")

results=np.array(results)
ms=results[:,2]
qs=results[:,3]
chisqs=results[:,4]
nomi=["$R_1$", "$T/R$", "$T_0$", "$\\chi^2$"]
f=uncertainties.unumpy.nominal_values
ff=uncertainties.unumpy.std_devs
my_latex_table(dir, "fit per colonne.txt", [cond, ms, qs, chisqs], nomi)

mnvs=uncertainties.unumpy.nominal_values(ms)
mstds=uncertainties.unumpy.std_devs(ms)
mfin, varmfin=fit_const_yerr(mnvs, mstds)

qnvs=uncertainties.unumpy.nominal_values(qs)
qstds=uncertainties.unumpy.std_devs(qs)
qfin, varqfin=fit_const_yerr(qnvs, qstds)

chifin1=sum((mfin-mnvs)**2/mstds**2)
chifin2=sum((qfin-qnvs)**2/qstds**2)

figure(5)
# pylab.title("$R_1$ vs m, $R_1$ vs q")
pylab.xlabel("$R_1$ [Ohm]")
pylab.subplot(511)
pylab.plot(f(np.array(cond)),(mfin-mnvs)/mstds, 'b.')
pylab.subplot(512)
pylab.plot(f(np.array(cond)), (qfin-qnvs)/qstds, 'b.')
pylab.savefig(dir + "./grafici/FitColonne.pdf",bbox_inches='tight')

mfin=uncertainties.ufloat(mfin, varmfin**0.5)
qfin=uncertainties.ufloat(qfin, varqfin**0.5)

print("------>>>>   m={} , q={}, chisq1={},  chisq2={}, dof={}".format(mfin, qfin, chifin1, chifin2, len(mnvs)))
print("E' effettivamente lineare e non dipende da nulla...")

#last

R_2=ufloat(47.6+387, mme(47.6+387, "volt"))
R_1=ufloat(386, mme(386, "volt"))

print(R1, R2)

T__1=ufloat(100, 2.5)
T__2=ufloat(30, 2.5)
print(T__2/T__1)
#un approccio bidimensionale non ha troppo senso....


#!/usr/bin/env python3

import fileinput
from math import atan2, sqrt, pi, inf
from collections import namedtuple, defaultdict, OrderedDict

Point = namedtuple('Point', field_names=['x', 'y'])

def parse_asteroids(string):
    return [
        Point(x, y)
        for y, line in enumerate(string.split('\n'))
        for x, char in enumerate(line)
        if char == '#'
    ]

def max_visibility(asteroids):
    return max(
        {
            station: {
                atan2(station.y - asteroid.y, station.x - asteroid.x)
                for asteroid in asteroids
                if asteroid != station
            } for station in asteroids
        }.items(),
        key=lambda item: len(item[1])
    )

def euclidean_distance(a, b):
    return sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2)

def asteroids_by_angle(asteroids, station):
    lines_of_sight = defaultdict(list)
    for asteroid in asteroids:
        if asteroid == station:
            continue
        angle = atan2(station.y - asteroid.y, station.x - asteroid.x)
        lines_of_sight[angle].append(asteroid)
    return lines_of_sight

def reorder(lines_of_sight, station):
    lines_of_sight = {
        (angle * 180 / pi + 270) % 360: sorted(
            asteroids,
            key=lambda asteroid: euclidean_distance(station, asteroid),
            reverse=True
        ) for angle, asteroids in lines_of_sight.items()
    }
    return OrderedDict(sorted(lines_of_sight.items()))

def vaporized_asteroids(lines_of_sight, n=inf):
    vaporized = []
    while len(vaporized) < n and all(lines_of_sight.values()):
        for angle in lines_of_sight.keys():
            if not lines_of_sight[angle]:
                continue
            vaporized.append(lines_of_sight[angle].pop())
    return vaporized

def test_task1():
    assert True
    print('tests for task 1: ok')

def solve_task1():
    string = ''.join(fileinput.input())
    asteroids = parse_asteroids(string)
    maximum = max_visibility(asteroids)
    print(f'answer to task 1: {len(maximum[1])}')

def test_task2():
    assert True
    print('tests for task 2: ok')

def solve_task2():
    string = ''.join(fileinput.input())
    asteroids = parse_asteroids(string)
    station = max_visibility(asteroids)[0]
    lines_of_sight = asteroids_by_angle(asteroids, station)
    lines_of_sight = reorder(lines_of_sight, station)
    asteroid = vaporized_asteroids(lines_of_sight, n=200)[199]
    print(f'answer to task 2: {asteroid.x * 100 + asteroid.y}')

def main():
    test_task1()
    solve_task1()
    test_task2()
    solve_task2()

if __name__ == '__main__':
    main()


import os
import torch
from ..plugin import Plugin

class Checkpoint(Plugin):
    name = 'checkpoint'

    def __init__(self, save_path, target_metrics, mode):
        self.save_path = save_path
        self.target_metrics = target_metrics
        self.best = None

        if mode == 'min':
            self.compare = lambda x, y: x < y
        elif mode == 'max':
            self.compare = lambda x, y: x > y
        else:
            raise ValueError('mode should be min or max')

    def __call__(self, trainer):
        checkpoint = trainer.state_dict()

        checkpoint_path = os.path.join(
            self.save_path, 'latest_checkpoint.pth.tar')
        torch.save(checkpoint, checkpoint_path)

        score = trainer.history[self.target_metrics][-1]
        if self.best is None or self.compare(score, self.best):
            checkpoint_path = os.path.join(
                self.save_path, 'best_checkpoint.pth.tar')
            torch.save(checkpoint, checkpoint_path)
            self.best = score


"""base

Revision ID: 5705a9291e9a
Revises: None
Create Date: 2014-06-14 16:38:45.704819

"""

# revision identifiers, used by Alembic.
revision = '5705a9291e9a'
down_revision = None

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('users',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('password', sa.String(), nullable=True),
    sa.Column('admin', sa.Boolean(), nullable=True),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('name')
    )
    op.create_table('dcaccount',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('username', sa.String(), nullable=True),
    sa.Column('password', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('hapiaccount',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('app_key', sa.String(), nullable=True),
    sa.Column('client_id', sa.String(), nullable=True),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('syncstate',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('endpoint', sa.String(), nullable=True),
    sa.Column('hapiaccount_id', sa.Integer(), nullable=True),
    sa.Column('last_sync_time', sa.DateTime(), nullable=True),
    sa.ForeignKeyConstraint(['hapiaccount_id'], ['hapiaccount.id'], ),
    sa.PrimaryKeyConstraint('id')
    )
    op.create_table('cwearapplication',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('name', sa.String(), nullable=True),
    sa.Column('owner', sa.Integer(), nullable=False),
    sa.Column('dcaccount', sa.Integer(), nullable=True),
    sa.Column('hapiaccount', sa.Integer(), nullable=True),
    sa.Column('last_sync_time', sa.DateTime(), nullable=True),
    sa.Column('sync_freq_secs', sa.Integer(), nullable=True),
    sa.ForeignKeyConstraint(['dcaccount'], ['dcaccount.id'], ),
    sa.ForeignKeyConstraint(['hapiaccount'], ['hapiaccount.id'], ),
    sa.ForeignKeyConstraint(['owner'], ['users.id'], ),
    sa.PrimaryKeyConstraint('id'),
    sa.UniqueConstraint('name')
    )
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('cwearapplication')
    op.drop_table('syncstate')
    op.drop_table('hapiaccount')
    op.drop_table('dcaccount')
    op.drop_table('users')
    ### end Alembic commands ###


from .. import session, engine
from sqlalchemy import Column, Integer, String, Enum
# from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

import enum

class Role(enum.Enum):
    Admin = 'Admin'
    Editor = 'Editor'
    Viewer = 'Viewer'

class StaffStatus(enum.Enum):
    left = 'left'
    pending = 'pending'
    active = 'active'

class TimeStatus(enum.Enum):
    old = 'old'
    new = 'new'

class Employee(Base):
    __tablename__ = 'employee'

    id = Column(Integer, primary_key=True)
    name = Column(String)
    staff_status = Column(Enum(StaffStatus))
    role = Column(Enum(Role),nullable=True)
    time_spent_status = Column(Enum(TimeStatus))
    # designation = relationship(Designation, backref="designation")

    def __repr__(self):
        return f'{self.name}'

    def save(self):
        session.add(self)
        session.commit()

    def to_json(self):
        json_obj = {}
        for column in self.__table__.columns:
            json_obj[column.name] = str(getattr(self, column.name))
        return json_obj

# Base.metadata.create_all(engine) #edit here
Employee.__table__.create(engine, checkfirst=True)


import logging
import json

from flask import request, jsonify

from codeitsuisse import app

logger = logging.getLogger(__name__)

@app.route('/asteroid', methods=['POST'])
def evaluate_asteroid():
    data = request.get_json()
    logging.info("data sent for evaluation {}".format(data))
    inputValue = data.get("test_cases")
    result = []
    for inputs in inputValue:
      result.append(solve(inputs))
    logging.info("My result :{}".format(result))
    return json.dumps(result)

def solve(input_data):
  counts = {}
  groupStarts = {}

  def getMultiplier(count):
    if count <= 6:
      return 1
    elif 10 > count >= 7:
      return 1.5
    else:
      return 2

  groups = []

  currentCount = 1
  prevChar = input_data[0]
  currentGroupStart = 0

  for i in range(1, len(input_data)):
    if prevChar == input_data[i]:
      currentCount+=1
    else:
      counts[len(groups)] = currentCount
      groupStarts[len(groups)] = currentGroupStart
      groups.append(prevChar)
      prevChar = input_data[i]
      currentCount = 1
      currentGroupStart = i

  counts[len(groups)] = currentCount
  groupStarts[len(groups)] = currentGroupStart
  groups.append(prevChar)

  # print(groupStarts)

  ans = [1, 0]
  trav = 0
  groupStart = 0
  groupMiddle = 0

  while trav < len(groups):

    groupStart = groupStarts[trav]
    groupMiddle = groupStart + counts[trav]//2

    # print(f'Current Group: {trav}')
    # print(f'Current Group Start: {groupStart}')
    # print(f'Current Group Middle: {groupMiddle}')

    hit = counts[trav] * getMultiplier(counts[trav])
    leftPointer = trav-1
    rightPointer = trav+1

    while leftPointer >= 0 and rightPointer <= len(groups)-1 and groups[leftPointer] == groups[rightPointer]:
      # print(f'   Left Pointer: {leftPointer}')
      # print(f'   Right Pointer: {rightPointer}')
      numberOfAsteroids = counts[leftPointer]+counts[rightPointer]
      hit += (numberOfAsteroids) * getMultiplier(numberOfAsteroids)
      leftPointer-=1
      rightPointer+=1

    if hit > ans[0]:
      ans[0] = hit
      ans[1] = groupMiddle
      # print(f"Updated Answer to {ans}")

    # print("=================")
    trav+=1

  return {
    "input" : input_data,
    "score" : ans[0],
    "origin" : ans[1]
  }


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from numpy import nan_to_num, subtract, add, divide, multiply
from osgeo import gdal, gdalconst
from gdal import GetDriverByName
from highcharts import Highchart

chart = Highchart()

def ndvi(in_nir_band, in_colour_band, in_rows, in_cols, in_geotransform, out_tiff, data_type=gdal.GDT_Float32):

    #Leia as faixas de entrada como matrizes numpy.
    np_nir    = in_nir_band.ReadAsArray(0, 0, in_cols, in_rows)
    np_colour = in_colour_band.ReadAsArray(0, 0, in_cols, in_rows)

    # Converta os arrays np em ponto flutuante de 32 bits para garantir que a divisao ocorra corretamente.
    np_nir_as32    = np_nir.astype(np.float32)
    np_colour_as32 = np_colour.astype(np.float32)

    #Tratando divisao por zero
    np.seterr(divide='ignore', invalid='ignore')

    # Calculando a formula NDVI  = (nir + red) / ( nir + red)
    numerator   = subtract(np_nir_as32, np_colour_as32)
    denominator = add(np_nir_as32, np_colour_as32)
    result     = divide(numerator, denominator)

    # Remove todas as areas fora do limite
    result[result == -0] = -99

    #capturando valores minimo e maximo com numpy
    np.nanmin(result), np.nanmax(result)

    #classe que noramliza a escala de cores
    class MidpointNormalize(colors.Normalize):

        def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
            self.midpoint = midpoint
            colors.Normalize.__init__(self,vmin,vmax,clip)

        def __call__(self, value, clip=None):
            x, y = [self.vmin, self.midpoint, self.vmax],[0,0.5,1]
            return np.ma.masked_array(np.interp(value,x,y), np.isnan(value))

    # definindo valores minimo e maximo para construcao do grafico (NDVI vai do -1 a 1)
    min = -1 #np.nanmin(result);
    max = 1  #np.nanmax(result);
    mid = 0.25

    #criando imagem .png, demonstrando grafico escala falsa cor
    fig  = plt.figure(figsize=(15,10))
    ax   = fig.add_subplot(111)
    cmap = plt.cm.RdYlGn
    cax  = ax.imshow(result,cmap=cmap, clim=(min,max), norm=MidpointNormalize(midpoint=mid,vmin=min,vmax=max))
    ax.axis('off'),
    ax.set_title('Escala NDVI', fontsize=18,fontweight='bold')
    cbar = fig.colorbar(cax, orientation='horizontal', shrink=0.50)
    fig.savefig('ndvi-escala.png', dpi=200,bbox_inches='tight', pad_inches=0.7)
    #mostra a imagem
    plt.show()

    #criando imagem com o histograma
    fig2 = plt.figure(figsize=(15,10))
    ax   = fig2.add_subplot(111)

    plt.title("Histograma NDVI", fontsize=18,fontweight='bold')
    plt.xlabel("Escala NDVI", fontsize=12)
    plt.ylabel("# pixels", fontsize=12)
    x = result[~np.isnan(result)]

    numBins = 20
    count   = len(x)
    lista   = [-1];
    i       = 0

    while(i <= count):

        lista.append(round(x[i],2)) # append or extend
        i  = i + 100

    lista = sorted(lista)
    data  = np.array(lista)
    data  = set(data)
    data  = sorted(data)

    print(data)

    ax.hist(lista,numBins,color='#43A047',alpha=0.8)

    fig2.savefig('ndvi-histograma.png', dpi=200,bbox_inches='tight',pad_inches=0.7)
    #mostra a imagem
    plt.show()

    #Motando grafico Highcharts
    options = {
    'title': {
    'text': 'Calculo NDVI'
    },
    'subtitle': {
    'text': 'resultado das imagens processadas'
    },
    'xAxis': {
    'categories': ['-1','-0.75','-0.50','-0.25','0','0.25','0.50','0.75','1'],
    },
    'yAxis': {
    'title': {
    'text': 'Pixels'
    }
    },
    }

    chart.set_dict_options(options)

    #convertendo o array num para lista
    #data = data.tolist()
    #print(data)

    chart.add_data_set(data,series_type='areaspline', name='NDVI Series')
    chart.set_options('chart', {'resetZoomButton': {'relativeTo': 'plot', 'position': {'x': 0,'y': -30}}})
    chart.set_options('xAxis', {'events': {'afterBreaks': 'function(e){return}'} ,'tickInterval': 0.25})
    chart.set_options('tooltip', {'formatter': 'default_tooltip'})
    chart.save_file('grafico');

    #Inicializando o driver geotiff.
    geotiff = GetDriverByName('GTiff')

    # If the desired output is an int16, map the domain [-1,1] to [0,255], create an int16 geotiff with one band and
    # write the contents of the int16 NDVI calculation to it.  Otherwise, create a float32 geotiff with one band and
    # write the contents of the float32 NDVI calculation to it.
    if data_type == gdal.GDT_UInt16:
        ndvi_int8 = multiply((result + 1), (2**7 - 1))
        output = geotiff.Create(out_tiff, in_cols, in_rows, 1, gdal.GDT_Byte)
        output_band = output.GetRasterBand(1)
        output_band.SetNoDataValue(-99)
        output_band.WriteArray(ndvi_int8)
    elif data_type == gdal.GDT_Float32:
        output = geotiff.Create(out_tiff, in_cols, in_rows, 1, gdal.GDT_Float32)
        output_band = output.GetRasterBand(1)
        output_band.SetNoDataValue(-99)
        output_band.WriteArray(result)
    else:
        raise ValueError('Tipo de dados de saida invalidos. Os tipos validos sao gdal.UInt16 ou gdal.Float32.')

    # Set the geographic transformation as the input.
    output.SetGeoTransform(in_geotransform)

    return None


import itertools
import numpy as np
import deeppy as dp
from test_layers import check_grad

batch_sizes = [1, 4, 5, 10]
n_ins = [1, 2, 7, 8, 18]
activations = ['leaky_relu', 'parametric_relu', 'relu', 'sigmoid', 'softplus',
               'tanh']

def test_activation():
    confs = itertools.product(batch_sizes, n_ins, activations)
    for batch_size, n_in, activation in confs:
        print('Activation: batch_size=%i, n_in=%i, method=%s'
              % (batch_size, n_in, str(activation)))
        x_shape = (batch_size, n_in)
        x = np.random.normal(size=x_shape).astype(dp.float_)
        layer = dp.Activation.from_any(activation)
        layer.setup(x_shape)
        assert layer.y_shape(x_shape) == x_shape
        if dp.float_ != np.float_:
            rtol = 1e-02
        else:
            rtol = None
        check_grad(layer, x, rtol=rtol)


def permutations():
    global running
    global characters
    global bitmask
    if len(running) == len(characters):
        a = (''.join(running))
        print(''.join(running))
        j.write(a + '\n')
    else:
        for i in xrange(len(characters)):
            if characters[i] not in running:
            #if ((bitmask>>i)&1) == 0:
                #bitmask |= 1 << i
                running.append(characters[i])
                permutations()
                running.pop()

x = []
f = open('testx.txt','r')
for _ in f:
    x.append(_.replace('\n', ''))

j = open('test.txt','w')

for _ in x:
    raw = _ #raw_input()
    characters = list(raw)
    running = []
    bitmask = 0
    permutations()


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

import random
import string
from words import words

#print(words)
## jogo da forca -- guessing the word through the letters
def get_valid_word(words):
    word = random.choice(words) # choose some random word from the list
    while "-" in word or ' ' in word:
        word = random.choice(words)

    return word.upper()

def hangman():
    word = get_valid_word(words)
    word_letters = set(word) # letters in the word
    alphabet = set(string.ascii_uppercase)
    used_letters = set() # what the user has guessed

    lives = 5

    #guetting the user input
    while len(word_letters) > 0 and lives > 0:

        #letters used
        print(f'You have', lives, 'and you have used these letters: ', ' '.join(used_letters))

        #what the current word is
        word_list = [letter if letter in used_letters else "-" for letter in word]
        print('Current word: ', ' '.join(word_list))

        user_letter = input('Guess a letter: '.upper())
        if user_letter in alphabet-used_letters:
            used_letters.add(user_letter)
            if user_letter in word_letters:
                word_letters.remove(user_letter)
                print('')
            else:
                lives = lives - 1 # takes one life if wrong
                print('Letter is not in the word.')

        elif user_letter in used_letters:
            print('\nYou have already used that character. Please try again.')

        else:
            print('\nThat is a invalid character. Please try again ')

    # when len(word_letters) == 0 or when lives == '0'
    if lives == 0:
        print('Sorry, your lives are over. The word was', word)
    else:
        print('You guessed the word', word, '!!!')

hangman()


import logging
import os
import time
import datetime

import boto3
import pystache
import yaml
import simplejson
from botocore.exceptions import NoCredentialsError, ClientError

from cfnstack.CFNStack import CFNStack

"""
StackGlue glues cloudformation stacks together and provides ability to create/destroy stacks based on dependency defined in YAML file
StackGlue class has methods to read YAML file where cloudformation stacks are listed with dependencies
and sort the cloudformation stacks based on dependencies and action methods to create, update and delete
cloudformation stacks listed in YAML file
"""

class StackGlue(object):
    def __init__(self, yamlfile, profile):
        self.logger = logging.getLogger(__name__)

        if profile and not profile.isspace():
            config_profile = profile
        else:
            config_profile = 'default'

        yamlconfig = open(yamlfile, 'r')
        render_yaml = pystache.render(yamlconfig.read(), dict(os.environ))
        self.stackDict = yaml.safe_load(render_yaml)

        # There will be only one global stack name
        toplevel_stack_count = len(self.stackDict.keys())
        if toplevel_stack_count != 1:
            error_message = ("Need one and only global stack name at the top level, found %s")
            self.logger.critical(error_message % toplevel_stack_count)
            exit(1)

        self.name = list(self.stackDict.keys())[0]

        if 'region' in self.stackDict[self.name]:
            self.region = self.stackDict[self.name]['region']
        else:
            self.logger.critical("No region mentioned in the stack. Please specify region")
            exit(1)

        # Verifying account id of key and stack account id

        # if 'account_id' in self.stackDict[self.name]:
        #     iam = boto3.resource('iam')
        #     current_user_arn = iam.CurrentUser().arn
        #     account_id = current_user_arn.split(':')[4]
        #
        #     if account_id != str(self.stackDict[self.name]['account_id']):
        #         self.logger.critical(
        #             'Account ID of the stack does not match the account ID of the aws credentials used.')
        #         exit(1)

        # Get the environment
        if 'environment' in self.stackDict[self.name]:
            self.environment = self.stackDict[self.name]['environment'].lower()
        else:
            # Assign default as DEV
            self.environment = 'dev'

        # Get and verify SNS topic
        self.sns_topic_arn = self.stackDict[self.name].get('sns-topic-arn', [])
        if isinstance(self.sns_topic_arn, str):
            self.sns_topic_arn = [self.sns_topic_arn]
        for topic in self.sns_topic_arn:
            if topic.split(':')[3] != self.region:
                self.logger.critical('SNS Topic %s is not in the %s region' % (topic, self.region))
                exit(1)

        self.global_tags = self.stackDict[self.name].get('tags', {})
        # print(self.global_tags['project'])

        # Array for holding CFNStack objects
        self.stack_objs = []

        self.cf_stacks = list(self.stackDict[self.name]['stacks'].keys())

        # Get all existing cloudformation stack details
        try:
            self.aws_session = boto3.Session(profile_name=config_profile)
            self.cfn_conn = self.aws_session.resource("cloudformation")
            self.cfn_all_stacks = self.cfn_conn.stacks.all()
        except NoCredentialsError as exception:
            self.logger.critical("No Credentials found for connecting to cloudformation: %s" % exception)
            exit(1)

        for stack_name in self.cf_stacks:
            one_stack = self.stackDict[self.name]['stacks'][stack_name]
            if type(one_stack) is dict:
                if one_stack.get('disable', False):
                    self.logger.warning("Stack %s is disabled by configuration, skipping..." % stack_name)
                    continue

            local_sns_arn = one_stack.get('sns-topic-arn', self.sns_topic_arn)
            if isinstance(local_sns_arn, str):
                local_sns_arn = [local_sns_arn]

            for topic in local_sns_arn:
                if topic.split(':')[3] != self.region:
                    self.logger.critical(
                        "SNS topic '%s' for Stack '%s' is not in the '%s' region " % (topic, stack_name, self.region))
                    exit(1)

            local_tags = one_stack.get('tags', {})

            self.merged_tags = self.global_tags.copy()
            self.merged_tags.update(local_tags.items())

            # Add static application tag
            self.merged_tags['Environment'] = self.environment.upper()

            if 'cf_template' in one_stack:
                self.stack_objs.append(
                    CFNStack(
                        stack_glue_name=self.name,
                        aws_session = self.aws_session,
                        name=stack_name,
                        environment=self.environment,
                        params=one_stack.get('params'),
                        template_name=one_stack['cf_template'],
                        region=self.region,
                        sns_topic_arn=local_sns_arn,
                        depends_on=one_stack.get('depends'),
                        tags=self.merged_tags
                    )
                )

    # Sort Cloudformation stacks by dependencies listed in YAML file
    def sort_cf_stacks_by_deps(self):
        """
        Sort the array of stack_objs so they are in dependency order
        """
        sorted_stacks = []
        dep_graph = {}
        no_deps = []

        # Add all stacks without dependencies in no_deps
        for stack in self.stack_objs:
            if stack.depends_on is None:
                no_deps.append(stack)
            else:
                dep_graph[stack.name] = stack.depends_on[:]

        while len(no_deps) > 0:
            stack = no_deps.pop()
            sorted_stacks.append(stack)
            for node in list(dep_graph):
                for deps in dep_graph[node]:
                    if stack.cfn_stack_name == deps:
                        dep_graph[node].remove(stack.cfn_stack_name)
                        if len(dep_graph[node]) < 1:
                            for stack_obj in self.stack_objs:
                                if stack_obj.name == node:
                                    no_deps.append(stack_obj)
                            del dep_graph[node]
        if len(dep_graph) > 0:
            self.logger.critical(
                "could not resolve dependency order. Either circular dependency or dependency on stack not in yaml file")
            exit(1)
        else:
            self.stack_objs = sorted_stacks
            return True

    # Apply - Create stacks if does not exists in AWS cloudformation and update the stack with updated template if stack already exists in cloudformation
    def apply(self, stack_name=None):
        for stack in self.stack_objs:
            if stack_name and stack.name != stack_name:
                continue
            self.logger.info("Determining whether stack needs to be created or updated")

            if not stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.info("Stack %s does not exists in CloudFormation. Stack %s is going to be created" % (
                stack.name, stack.name))
                self.create(stack.name)
            else:
                self.logger.info(
                    "Stack %s exists in CloudFormation. Checking wheter there is any change in the cloudformation template or parameters" % stack.name)
                self.update(stack.name)

    # Create cloudformation stack and this function is called from apply.
    def create(self, stack_name=None):
        """
        Create all stacks in the yaml file based on dependency order.
        Any stack already exists skip the stack creation
        """

        for stack in self.stack_objs:
            if stack_name and stack.name != stack_name:
                continue
            self.logger.info("Starting checks for creation of stack %s" % stack.name)

            if stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.critical("Stack %s already exists in cloudformation, skipping..." % stack.name)
            else:
                if stack.dependencies_met(self.cfn_all_stacks) is False:
                    self.logger.critical("Dependencies for stack %s is not met and exiting..." % stack.name)
                    exit(1)
                if not stack.populate_params(self.cfn_all_stacks):
                    self.logger.critical("Could not determine correct parameters for stack %s" % stack.name)
                    exit(1)

                stack.read_template()
                self.logger.info("Creating: %s, and its parameters : %s" % (stack.cfn_stack_name, stack.params))
                try:
                    self.cfn_conn.create_stack(
                        StackName=stack.cfn_stack_name,
                        TemplateBody=stack.template_body,
                        Parameters=stack.params,
                        Capabilities=['CAPABILITY_IAM'],
                        NotificationARNs=stack.sns_topic_arn,
                        OnFailure='DELETE',
                        Tags=stack.tags
                    )
                except Exception as exception:
                    self.logger.critical("Creating stack %s failed. Error: %s" % (stack.cfn_stack_name, exception))
                    exit(1)

                create_result = self.watch_events(stack.cfn_stack_name, "CREATE_IN_PROGRESS")
                if create_result != "CREATE_COMPLETE":
                    self.logger.critical("Stack did not create correctly, status is now %s" % create_result)
                    exit(1)

                self.logger.info("Finished creating stack: %s" % stack.cfn_stack_name)
                self.cfn_all_stacks = self.cfn_conn.stacks.all()

    # Update cloudfromation stack if already exists in AWS cloudformation
    def update(self, stack_name=None):
        for stack in self.stack_objs:
            if stack_name and stack.name != stack_name:
                continue
            self.logger.info("Starting checks for update of stack %s" % stack.name)

            if not stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.critical(
                    "Stack %s does not exists in cloudformation, can't update non-existing stack, skipping..." % stack.name)
            else:
                if stack.dependencies_met(self.cfn_all_stacks) is False:
                    self.logger.critical("Dependencies for stack %s is not met and exiting..." % stack.name)
                    exit(1)
                if not stack.populate_params(self.cfn_all_stacks):
                    self.logger.critical("Could not determine correct parameters for stack %s" % stack.name)
                    exit(1)

                stack.read_template()

                template_up_to_date = stack.template_uptodate(self.cfn_all_stacks)
                params_up_to_date = stack.params_uptodate(self.cfn_all_stacks)

                self.logger.info("Stack is up to date: %s" % (template_up_to_date and params_up_to_date))

                if template_up_to_date and params_up_to_date:
                    self.logger.info("Stack '%s' is already up to date with cloudformation. Skipping..." % stack.name)
                else:
                    self.logger.info("Template or parameter for stack %s has changed." % stack.name)
                    self.logger.info("Starting update of stack %s with parameters: %s" % (stack.name, stack.params))

                    # Validate template step can be added here

                    try:
                        self.cfn_conn.Stack(stack.cfn_stack_name).update(
                            TemplateBody=stack.template_body,
                            Parameters=stack.params,
                            Capabilities=['CAPABILITY_IAM'],
                            NotificationARNs=stack.sns_topic_arn
                        )
                    except ClientError as exception:
                        if (str(exception.response['Error']['Message']) == "No updates are to be performed."):
                            self.logger.error(
                                "CloudFormation has no updates to perform on resources of stack %s. Continue with next stack if exists..." % stack.name)
                            continue
                        else:
                            self.logger.critical(
                                "Updating stack %s failed. Error: %s" % (stack.cfn_stack_name, exception))
                            exit(1)

                    update_result = self.watch_events(
                        stack.cfn_stack_name, [
                            "UPDATE_IN_PROGRESS",
                            "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"])
                    if update_result != "UPDATE_COMPLETE":
                        self.logger.critical(
                            "Stack didn't update correctly, status is now %s"
                            % update_result)
                        exit(1)

                    self.logger.info(
                        "Finished updating stack: %s" % stack.cfn_stack_name)

            # avoid getting rate limited
            time.sleep(2)

    #List CF change sets created in a stack
    def listcs(self,stack_name=None):
        for stack in self.stack_objs:
            self.logger.info(stack)
            if stack_name and stack.name != stack_name:
                continue
            self.logger.info("Starting to retrieve changesets for %s" % stack.name)

            if not stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.critical(
                    "Stack %s does not exists in cloudformation, can't list change sets from non-existing stack, skipping..." % stack.name)
            else:
                if stack.dependencies_met(self.cfn_all_stacks) is False:
                    self.logger.critical("Dependencies for stack %s is not met and exiting..." % stack.name)
                    exit(1)
                if not stack.populate_params(self.cfn_all_stacks):
                    self.logger.critical("Could not determine correct parameters for stack %s" % stack.name)
                    exit(1)

            cf_client = self.cfn_conn.meta.client;

            try:
                stackcs = cf_client.list_change_sets(StackName=stack.cfn_stack_name)
            except  Exception as exception:
                self.logger.critical("Can't list change sets for stack %s. Error: %s" % (stack.cfn_stack_name, exception))
                exit(1)

            enco = lambda obj: (
                obj.isoformat()
                if isinstance(obj, datetime.datetime)
                    or isinstance(obj, datetime.date)
                else None
            )

            for csval in stackcs['Summaries']:
                self.logger.info("\nHere is the description of change set \"%s\" for stack \"%s\", created on %s"
                                     % (csval['ChangeSetName'],csval['StackName'],csval['CreationTime']))
                self.logger.info("\n"+simplejson.dumps(csval,sort_keys=False,indent=4,default=enco))
                self.logger.info("\n-----------------------------------------------------------------------------\n")
                try:
                    stackcs = cf_client.describe_change_set(ChangeSetName=csval['ChangeSetName'],StackName=csval['StackName'])
                except  Exception as exception:
                    self.logger.critical(
                            "Can't describe change sets for stack %s. Error: %s" % (stack.cfn_stack_name, exception))
                    exit(1)
                self.logger.info("\nDetails of changes in the change set \"%s\" for stack \"%s\"" % (csval['ChangeSetName'],csval['StackName']) )
                self.logger.info("\n"+simplejson.dumps(stackcs, sort_keys=False, indent=4, default=enco))
                self.logger.info("\n********************************************************************\n")

    #Apply or execute changeset to a stack
    def applycs(self, stack_name=None, changesetname=None):
        for stack in self.stack_objs:
            if stack_name and stack.name != stack_name:
                continue
            self.logger.info("Starting to retrieve changesets for %s" % stack.name)

        if not stack.exists_in_cfn(self.cfn_all_stacks):
            self.logger.critical(
                "Stack %s does not exists in cloudformation, can't apply change sets on non-existing stack, skipping..." % stack.name)
        else:
            if stack.dependencies_met(self.cfn_all_stacks) is False:
                self.logger.critical("Dependencies for stack %s is not met and exiting..." % stack.name)
                exit(1)
            if not stack.populate_params(self.cfn_all_stacks):
                self.logger.critical("Could not determine correct parameters for stack %s" % stack.name)
                exit(1)

        cf_client = self.cfn_conn.meta.client;

        try:
            stackcs = cf_client.list_change_sets(StackName=stack.cfn_stack_name)
        except  Exception as exception:
            self.logger.critical("Can't list change sets for stack %s. Error: %s" % (stack.cfn_stack_name, exception))
            exit(1)

        if len(stackcs['Summaries'])==0:
            self.logger.info("No changesets are available to apply. Exiting with error")
            exit(1)

        cs_exists = 0
        for csval in stackcs['Summaries']:
            if stack.name == stack.name:
                if csval['ChangeSetName'] == changesetname:
                    self.logger.critical("Change set \"%s\" is available in stack \"%s\"" % (csval['ChangeSetName'],csval['StackName']))
                    cs_exists = 1

        if cs_exists == 0:
            self.logger.critical("Can't find change set called \"%s\"" % changesetname)
            exit(1)
        else:
            try:
                cf_client.execute_change_set(ChangeSetName=changesetname, StackName=stack.cfn_stack_name)
            except  Exception as exception:
                self.logger.critical(
                        "Can't execute change sets for stack %s. Error: %s" % (stack.cfn_stack_name, exception))
                exit(1)

        update_result = self.watch_events(
                stack.cfn_stack_name, [
                        "UPDATE_IN_PROGRESS",
                        "UPDATE_COMPLETE_CLEANUP_IN_PROGRESS"])
        if update_result != "UPDATE_COMPLETE":
                self.logger.critical(
                        "Stack didn't update correctly, status is now %s"
                        % update_result)
                exit(1)

        self.logger.info(
                    "Finished updating stack %s using change set: %s" % (stack.cfn_stack_name,changesetname))

    #Create change set for a CF stack
    def createcs(self, stack_name=None, changesetname=None):
        for stack in self.stack_objs:
            if stack_name and stack.name != stack_name:
                continue

            if not stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.critical(
                    "Stack %s does not exists in cloudformation, can't create change sets on non-existing stack, skipping..." % stack.name)
            else:
                if stack.dependencies_met(self.cfn_all_stacks) is False:
                    self.logger.critical("Dependencies for stack %s is not met and exiting..." % stack.name)
                    exit(1)
                if not stack.populate_params(self.cfn_all_stacks):
                    self.logger.critical("Could not determine correct parameters for stack %s" % stack.name)
                    exit(1)

            cf_client = self.cfn_conn.meta.client;

            current_time = datetime.datetime.now().isoformat()
            description_txt = "Change Set "+changesetname+" is created for "+stack.cfn_stack_name+" at "+current_time

            stack.read_template()
            self.logger.info("Creating Changeset: %s for stack: %s, and its parameters : %s" % (changesetname,stack.cfn_stack_name, stack.params))

            try:
                cf_client.create_change_set(
                    StackName=stack.cfn_stack_name,
                    TemplateBody=stack.template_body,
                    Parameters=stack.params,
                    Capabilities=['CAPABILITY_IAM'],
                    NotificationARNs=stack.sns_topic_arn,
                    Tags=stack.tags,
                    ChangeSetName = changesetname,
                    Description = description_txt
                )
            except Exception as exception:
                self.logger.critical(
                    "Can't create change sets for stack %s. Error: %s" % (stack.cfn_stack_name, exception))
                exit(1)

            self.logger.info("Changeset %s for stack %s is successfully created" % (changesetname, stack.cfn_stack_name))

    #Delete change set from a CF stack
    def deletecs(self, stack_name=None, changesetname=None):
        for stack in self.stack_objs:
            if stack_name and stack.name != stack_name:
                continue

            if not stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.critical(
                    "Stack %s does not exists in cloudformation, can't delete change sets on non-existing stack, skipping..." % stack.name)
            else:
                if stack.dependencies_met(self.cfn_all_stacks) is False:
                    self.logger.critical("Dependencies for stack %s is not met and exiting..." % stack.name)
                    exit(1)
                if not stack.populate_params(self.cfn_all_stacks):
                    self.logger.critical("Could not determine correct parameters for stack %s" % stack.name)
                    exit(1)

            cf_client = self.cfn_conn.meta.client;

            self.logger.info("Delete Changeset: %s for stack: %s, and its parameters : %s" % (
            changesetname, stack.cfn_stack_name, stack.params))

            try:
                cf_client.delete_change_set(
                    StackName=stack.cfn_stack_name,
                    ChangeSetName=changesetname
                )
            except Exception as exception:
                self.logger.critical(
                    "Can't delete change sets for stack %s. Error: %s" % (stack.cfn_stack_name, exception))
                exit(1)

            self.logger.info(
                "Changeset %s for stack %s is successfully deleted" % (changesetname, stack.cfn_stack_name))

    #Delete cloudformation stack
    def delete(self, stack_name=None):
        """
        Delete all the stacks from cloudformation.
        Delete the stack in reverse dependency order
        """
        for stack in reversed(self.stack_objs):
            if stack_name and stack.name != stack_name:
                continue
            self.logger.info("Starting checks for creation of stack %s" % stack.name)

            if not stack.exists_in_cfn(self.cfn_all_stacks):
                self.logger.critical("Stack %s does not exist in cloudformation, skipping..." % stack.name)
            else:
                self.logger.info("Starting to delete stacks %s" % stack.name)
                try:
                    self.cfn_conn.Stack(stack.cfn_stack_name).delete()
                except  Exception as exception:
                    self.logger.critical("Deleting stack %s failed. Error: %s" % (stack.cfn_stack_name, exception))
                    exit(1)

                delete_result = self.watch_events(stack.cfn_stack_name, "DELETE_IN_PROGRESS")

                if (delete_result != "DELETE_COMPLETE" and delete_result != "STACK_GONE"):
                    self.logger.critical("Stack didn't get deleted correctly, Status is now %s", delete_result)
                    exit(1)

                self.logger.info("Finished deleting Stack: %s", stack.cfn_stack_name)
                self.cfn_all_stacks = self.cfn_conn.stacks.all()

    # Watch cloudformation events for all action
    def watch_events(self, stack_name, while_status):
        """
        Stay and watch cloudformation events till 'while_status'
        """
        cfstack_obj = self.cfn_conn.Stack(stack_name)
        first_events = []

        try:
            cfstack_obj.reload()
            events = self.cfn_conn.Stack(stack_name).events.all()
        except ClientError as exception:
            if (str(exception.response['Error']['Message']) == "Stack with id %s does not exist" % (stack_name)):
                return "STACK_GONE"

        for evt in first_events:
            first_events.append(evt)

        self.logger.info("All events for the stack - %s :", self.name)

        try:
            for evt in reversed(first_events):
                self.logger.info("%s %s %s %s %s %s" % (
                    evt.timestamp.isoformat(),
                    evt.resource_status,
                    evt.resource_type,
                    evt.logical_resource_id,
                    evt.physical_resource_id,
                    evt.resource_status_reason,
                ))
        except ClientError as exception:
            self.logger.critical("Error reading events list : " + str(exception))

        status = str(cfstack_obj.stack_status)

        while status in while_status:
            self.logger.info("Fetching new events for the stack - %s :", self.name)
            new_events = []
            event_to_log = []
            try:
                cfstack_obj.reload()
                events = self.cfn_conn.Stack(stack_name).events.all()
            except ClientError as exception:
                if (str(exception.response['Error']['Message']) == "Stack with id %s does not exist" % (stack_name)):
                    return "STACK_GONE"

            for evt in events:
                new_events.append(evt)

            event_to_log = [evt for evt in new_events if evt not in first_events]

            try:
                for evt in reversed(event_to_log):
                    self.logger.info("%s %s %s %s %s %s" % (
                        evt.timestamp.isoformat(),
                        evt.resource_status,
                        evt.resource_type,
                        evt.logical_resource_id,
                        evt.physical_resource_id,
                        evt.resource_status_reason,
                    ))
            except ClientError as exception:
                self.logger.critical("Error reading events list : " + str(exception))

            try:
                status = str(cfstack_obj.stack_status)
            except ClientError as exception:
                if (str(exception.response['Error']['Message']) == "Stack with id %s does not exist" % (stack_name)):
                    return "STACK_GONE"

            first_events = new_events

            self.logger.info("Waiting 5 Sec to fetch log for the stack - %s :", self.name)

            time.sleep(5)

        return status


from django.urls import path
from . import views

app_name = 'educator'

urlpatterns = [
    path('', views.edMain, name='edmain'),
    path('edtaskwatch', views.edTaskWatch, name='edtaskwatch'),
    path('edassigntask', views.edAssignTask, name='edassigntask'),
    path('edassigntask_grpsel', views.edAssignTask, name='edassigntask_grpsel'),
    path('edassigntask_taskgrpsel', views.edAssignTask, name='edassigntask_taskgrpsel'),
    path('edassigntask_studsel', views.edAssignTask, name='edassigntask_studsel'),
    path('topics', views.edTaskGroups, name='topics'),
    path('topics/new', views.edTaskNew, name='new_topic'),
    path('templates', views.edTaskTemplates, name='topic_templates'),
    path('eddefinetask', views.edDefineTask, name='eddefinetask'),
    path('edworkontask', views.editTemplate, name='edworkontask'),
    path('edgeneratetask', views.edGenerateTask, name='edgeneratetask'),
    path('edpregeneratedtask', views.edPreGeneratedTask, name='edpregeneratedtask'),
    path('edstatistics', views.edStatistics, name='edstatistics'),
    path('edstats/students', views.edStatsStudents, name='stats_students'),
    path('edstats/student', views.edStatsStudent, name='stats_student'),
    path('edstats/student/detailed', views.edStatsStudentDetailed, name='stats_student_detailed'),
    path('edprofile', views.edProfile, name='edprofile'),
    path('edsupport', views.edSupport, name='edsupport'),
    path('edchangepassword', views.edChangePassword, name='edchangepassword'),
    path('edchp', views.edchp, name='edchp'),
    path('edsendmail', views.edsendmail, name='edsendmail'),
    path('edcreategroup', views.edcreategroup, name='edcreategroup'),
    path('toLogin', views.toLogin, name='toLogin'),
]


import setuptools
from cati.frontend import Version

f = open('README.md', 'r')
long_description = f.read()
f.close()

setuptools.setup(
    name="cati",
    version=Version.version,
    author="parsa shahmaleki",
    author_email="parsampsh@gmail.com",
    description="The Cati Unix Package manager",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/parsampsh/gameoflife",
    packages=setuptools.find_packages(),
    scripts=['etc/bin/cati'],
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: Unix",
    ],
    python_requires='>=3.6',
    install_requires=[
        'packaging >= 20.4',
        'requests >= 2.25.0',
        'wget >= 3.2',
    ],
)


__author__ = 'vden'

import random
import pytest
import allure

list_table = []
count_table = 0

class Sql_ddlHelper():

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

    @allure.step('create table {0}')
    def create_table(self, tablename=None, column_names_and_type=None):

        if self.db.initdb.check_tablename(tablename=tablename):
            print(("table '%s' already created") % tablename)
        else:
            print(("table '%s' not created") % tablename)

            conn = self.db.conn.db_write()

            sql_char = ("""
                  create table {tablename_t}
                    (
                       id         serial not null
                                  constraint {tablename_t}_pkey
                                  primary key,""").format(tablename_t=tablename)

            for column_name_and_type in column_names_and_type:
                sql_char +=("""
                        {column_name_c} ,""").format(column_name_c=column_name_and_type)

            sql_char+=("""
                        test_start_timestamp timestamp
                     );

                    create unique index {tablename_t}_id_uindex
                       on {tablename_t} (id);

                    create index {tablename_t}_test_start_timestamp_index
                        on {tablename_t} (test_start_timestamp desc);

                    commit ;
                       """).format(tablename_t=tablename)

            print('sql_char=', sql_char)

            cursor = self.db.cur_e.cursor_execute(conn=conn, sql_char=sql_char)

            if cursor is not None:
                cursor.close()
            if conn is not None:
                conn.close()


import sys
import re
from time import time
from os.path import isfile
from parameters import *
from collections import defaultdict

def normalize(x):
    # x = re.sub("[\uAC00-\uD7A3]+", "\uAC00", x) £ convert Hangeul to 가
    # x = re.sub("[\u3040-\u30FF]+", "\u3042", x) # convert Hiragana and Katakana to あ
    # x = re.sub("[\u4E00-\u9FFF]+", "\u6F22", x) # convert CJK unified ideographs to 漢
    x = re.sub("\s+", " ", x)
    x = re.sub("^ | $", "", x)
    x = x.lower()
    return x

def tokenize(x):
    if UNIT == "char":
        return list(re.sub(" ", "", x))
    if UNIT == "word":
        return x.split(" ")

def save_data(filename, data):
    fo = open(filename, "w")
    for seq in data:
        fo.write(" ".join(seq) + "\n")
    fo.close()

def load_tkn_to_idx(filename):
    print("loading %s" % filename)
    tkn_to_idx = {}
    fo = open(filename)
    for line in fo:
        line = line[:-1]
        tkn_to_idx[line] = len(tkn_to_idx)
    fo.close()
    return tkn_to_idx

def load_idx_to_tkn(filename):
    print("loading %s" % filename)
    idx_to_tkn = []
    fo = open(filename)
    for line in fo:
        line = line[:-1]
        idx_to_tkn.append(line)
    fo.close()
    return idx_to_tkn

def save_tkn_to_idx(filename, tkn_to_idx):
    fo = open(filename, "w")
    for tkn, _ in sorted(tkn_to_idx.items(), key = lambda x: x[1]):
        fo.write("%s\n" % tkn)
    fo.close()

def load_checkpoint(filename, model = None):
    print("loading %s" % filename)
    checkpoint = torch.load(filename)
    if model:
        model.load_state_dict(checkpoint["state_dict"])
    epoch = checkpoint["epoch"]
    loss = checkpoint["loss"]
    print("saved model: epoch = %d, loss = %f" % (checkpoint["epoch"], checkpoint["loss"]))
    return epoch

def save_checkpoint(filename, model, epoch, loss, time):
    print("epoch = %d, loss = %f, time = %f" % (epoch, loss, time))
    if filename and model:
        print("saving %s" % filename)
        checkpoint = {}
        checkpoint["state_dict"] = model.state_dict()
        checkpoint["epoch"] = epoch
        checkpoint["loss"] = loss
        torch.save(checkpoint, filename + ".epoch%d" % epoch)
        print("saved model at epoch %d" % epoch)

def maskset(x):
    mask = x.eq(PAD_IDX)
    return (mask, x.size(1) - mask.sum(1)) # set of mask and lengths

def idx_to_tkn(tkn_to_idx):
    return [x for x, _ in sorted(tkn_to_idx.items(), key = lambda x: x[1])]

def f1(p, r):
    return 2 * p * r / (p + r) if p + r else 0


from typing import Callable, Dict, Tuple
import flax
import jax
import jax.numpy as jnp
from brax import envs

@flax.struct.dataclass
class EnvState:
  """Contains training state for the learner."""
  core: envs.State
  total_metrics: Dict[str, jnp.ndarray]
  total_episodes: jnp.ndarray

Action = jnp.ndarray
StepFn = Callable[[EnvState, Action], EnvState]

def wrap(core_env: envs.Env, rng: jnp.ndarray) -> Tuple[EnvState, StepFn]:
  """Returns a wrapped state and step function for training."""
  rng = jax.random.split(rng, core_env.batch_size)

  first_core = core_env.reset(rng)
  first_core.metrics['reward'] = first_core.reward
  first_total_metrics = jax.tree_map(jnp.sum, first_core.metrics)
  first_total_episodes = jnp.zeros(())

  first_state = EnvState(
      core=first_core,
      total_metrics=first_total_metrics,
      total_episodes=first_total_episodes)

  def step(state: EnvState, action: Action) -> EnvState:
    core = core_env.step(state.core, action)
    core.metrics['reward'] = core.reward
    def test_done(a, b):
      if a is first_core.done or a is first_core.metrics or a is first_core.reward:
        return b
      test_shape = [a.shape[0],] + [1 for _ in range(len(a.shape) - 1)]
      return jnp.where(jnp.reshape(core.done, test_shape), a, b)
    core = jax.tree_multimap(test_done, first_state.core, core)
    total_metrics = jax.tree_multimap(lambda a, b: a + jnp.sum(b),
                                      state.total_metrics, core.metrics)
    total_episodes = state.total_episodes + jnp.sum(core.done)
    return EnvState(
        core=core,
        total_metrics=total_metrics,
        total_episodes=total_episodes)

  return first_state, jax.jit(step)


NOPYTHON = False  # If ture the Numba decorated function will run entirely
                  # without the involvement of the Python interpreter.
                  # Alternatively the compilation will be done in object mode.

PARALLEL = False   # If True Numba functions are parallelized.

NUM_THREADS = 2   # Set number of threads for Numba Functions


"""
Multiplex network structure
"""
from graph import Graph

# from dateutil import parser
# parser.parse(date_a)
# parser.parse(date_b)
# diff = (date_b - date_a).days

class Multiplex(object):
    """
    Multiplex class
    """
    def __init__(self, *args, **kwargs):
        """
        Arguments
        ----------
        list of graphs to be loaded

        Keyword Arguments
        -----------------
        """
        self.graphs_list = []
        for g_i in args:
            if isinstance(g_i, Graph):
                self.graphs_list.append(g_i)

    # We use three directed graphs
    # Graph A (directed) connects works and their respective publication dates
    # Graph B (undirected) connects authors to their respective works
    # Graph C (directed) connects works and their cited works
    # But in reality we want virtual graphs that uses these graphs
    # as information base
    # VirtualGraph A:
    # -> Connects authors that worked together (coauthorship)
    # -> get_neighbors: given a vertex, go to Graph B, find author, select
    # list of works, for each work, go on Graph A and select its date, then go
    # to each work and list the authors and return the authors
    # VirtualGraph B:
    # -> Connects authors that cited others (citation)
    # -> get_neighbors: given a vertex, select list of works, then for each
    # go in graph C, select list of works, then get back on graph B to find
    # its authors


from bs4 import BeautifulSoup
from bs4 import element
import requests
import asyncio
import time
import aiohttp

count = 0
async def query(link):
	'''функция для обработки запроса.
		Принимает url и возвращает объект BeautifulSoup
		для дальнейшей обработки'''
	headers = {
			'User-Agent':'Mozilla/5.0 (X11; Linux x86_64; rv:12.0) \
				Gecko/20100101 Firefox/12.0'}
	async with aiohttp.ClientSession() as session:
		async with session.get(link) as response:
			response = await response.read()
	soup = BeautifulSoup(response.decode('utf-8'), 'html.parser')
	return soup

def link_to_new_page(base_url, next_page_obj):
	'''функция для определения наличия дополнительных страниц.
		Принимает объект Node, в котором ищется ссылка на
		следующую страницу с объявлениеми.
		Возвращает None или ссылку на страницу.'''
	if next_page_obj:
		print(1)
		if next_page_obj.name == 'a':
			new_page = base_url + next_page_obj.get('href')
		else:
			if next_page_obj.a:
				new_page = base_url + next_page_obj.a.get('href')
			else:
				new_page = None
	else:
		new_page = None
	return new_page

def text_formatting(tag):
	'''функция для форматирования текста.
		На вход получаем объект Node, из которого извлекается текст.
		Возвращает строку, соотв. тексту Node'''
	text = ''
	for i in tag.children:
		if isinstance(i, element.NavigableString):
			text += i + ' '
		else:
			child = i.children
			if child:
				for j in child:
					if isinstance(j, element.NavigableString):
						text += j + ' '
					else:
						if j.name in ['b', 'i', 'span']:
							text += j.get_text() + ' '
						else:
							text += j.get_text() + '
'
				text += '
'
			else:
				text += i.get_text() + '
'

	return text

async def rabota_ua():
	'''фукнция для извлечения данных из https://rabota.ua'''
	base_url = 'https://rabota.ua'
	new_page = base_url +\
	"/jobsearch/vacancy_list?keyWords=python&scheduleId=3&parentId=1"
	out = ''
	global count
	while new_page:
		#заходим на страницу с объявлениями
		soup = await query(new_page)
		divs = soup.findAll('div', attrs={'class':'fd-f1'})
		#проверяем существует ли следующая страница
		next_page = soup.find('dd', attrs={'class':'nextbtn'})
		new_page = link_to_new_page(base_url, next_page)
		for div in divs:
			if div.h3:
				#обрабатываем каждое объявление
				title = div.h3.string.strip() + '\n'
				a = div.h3.a.get('href').strip()
				href = base_url + a
				out += '
{1} -\
						{2}
'.format(href, base_url, title)
				#заходим на страницу объявления
				soup = await query(href)
				div = soup.find('div',
				attrs={'class':'f-vacancy-description-inner-content'})

				text = text_formatting(div)
				out += '
{}
'.format(text)
				count += 1
	return out

async def work_ua():
	'''фукнция для извлечения данных из https://www.work.ua'''
	base_url = 'https://www.work.ua'
	new_page = base_url +\
	"/jobs-python/?advs=1&sel_zan=76"
	out = ''
	global count
	while new_page:
		#заходим на страницу с объявлениями
		soup = await query(new_page)
		divs = soup.findAll('div', attrs={
								'class':'card card-hover card-visited\
								 wordwrap job-link card-logotype'})
		divs += soup.findAll('div', attrs={
								'class':'card card-hover card-visited\
									 wordwrap job-link'})
		ul = soup.find('ul', attrs={'class':"pagination hidden-xs"})
		#проверяем существует ли следующая страница
		if ul:
			next_page = ul.findAll('li')[-1]
			new_page = link_to_new_page(base_url, next_page)
		else:
			new_page = None
		for d in divs:
			#обрабатываем каждое объявление
			title = d.find('h2').a.string.strip()
			a = d.find('h2').a.get('href')
			href = base_url + a
			out += '
{1} - \
					{2}
'.format(href, base_url, title)
			#заходим на страницу объявления
			soup = await query(href)
			div = soup.find('div', attrs={'class':"overflow wordwrap"})
			text = text_formatting(div)
			out += '
{}\n
'.format(text)
			count += 1

	return out

async def hh_ua():
	'''фукнция для извлечения данных из https://hh.ua'''
	base_url = 'https://hh.ua'
	new_page = base_url +\
	"/search/vacancy?order_by=publication_time&schedule=remote&\
	enable_snippets=true&area=5&text=Python&clusters=true&\
	search_period=7&currency_code=UAH&experience=between1And3&\
	from=cluster_experience"
	out = ''
	global count
	while new_page:
		#заходим на страницу с объявлениями
		soup = await query(new_page)
		divs = soup.findAll('div',
					attrs={'class':'vacancy-serp-item__info'})
		#проверяем существует ли следующая страница
		next_page = soup.find('a', attrs={
									'class':"bloko-button \
										HH-Pager-Controls-Next \
										HH-Pager-Control"})
		new_page = link_to_new_page(base_url, next_page)
		for d in divs:
			t = d.find('div',
					attrs={'class':'vacancy-serp-item__title'})
			if t:
				#обрабатываем каждое объявление
				title = t.a.string.strip()
				href = t.a.get('href')
				out += '
{1} - \
						{2}
'.format(href, base_url, title)
				#заходим на страницу объявления
				soup = await query(href)
				description = soup.find('div',
								attrs={'class':"g-user-content"})
				if not description:
					description = soup.find('div',
						attrs={'class':'vacancy-branded-user-content'})
				requirements = soup.find('div',
						attrs={'class':"bloko-gap bloko-gap_bottom"})
				text = text_formatting(description)
				out += '
{0}\n{1}
'.format(
										requirements.get_text(), text)
				count += 1
	return out

async def main(loop):
	'''функция для обработки 3 сайтов и составления результирующей
	html-страницы'''
	#обрабатываем сайты
	completed, pending = await asyncio.wait([work_ua(),
											rabota_ua(),
											hh_ua()])
	#создаем результирующую html-страницу
	html = '<title>Вакансии</title><meta charset="utf-8">\
	<link rel="stylesheet" type="text/css" href="vacancy.css"\
	'
	html += '
\
				Найдено объявлений: {}
'.format(count)
	#наполняем страницу содержимым
	for item in completed:
		html += item.result()
	html += ''
	#записываем полученную страницу в файл
	with open('vacancy.html', 'w') as f:
		f.write(html)

if __name__ == '__main__':
	t = time.time()
	loop = asyncio.get_event_loop()
	loop.run_until_complete(main(loop))
	loop.close()
	print(time.time()-t)
	print('Всего объявлений:', count)