#! /usr/bin/env python
import os
import numpy as np
from PythonPhot import getpsf, aper
from astropy.io import fits as pyfits
from .__main__ import getxycenter

def getcamera(imfile):
    """ Determine the camera name (e.g. ACS-WFC or WFC3-IR)
    from the header of the given image.  The input imfile
    may be a string giving a fits filename, a pyfits hdu object,
    or a pyfits header.
    :param imfile:
    :return:
    """
    import hstphot
    hdr = hstphot.getheader(imfile)
    instrument, detector = '', ''
    if 'CAMERA' in hdr:
        instrument = hdr['CAMERA']
        detector = ''
    elif 'INSTRUME' in hdr:
        instrument = hdr['INSTRUME']
    if 'DETECTOR' in hdr:
        detector = hdr['DETECTOR']
    camera = '-'.join([instrument, detector]).rstrip('-')
    return camera

def mkpsfmodel_stdstar(psfimdir="./", psfrad=0.3, fitrad=0.15,
                       starname='g191b2b',
                       pixscale=0.03,
                       bandlist=['f435w', 'f606w', 'f814w'],
                       verbose=True):
    """ Construct a set of psf models from drizzled HST images of a
    standard star, with the star in the center of the image.

    :param psfimdir: psf image directory (where the input std star images are
       and also where the output psf model images will be put)
    :param psfrad: the scalar radius, in arcsec, of the circular area within
                which the PSF will be defined.  This should be slightly larger
                than the radius of the brightest star that one will be
                interested in.
    :param fitrad: the scalar radius, in arcsec, of the circular area used in
               the least-square star fits.  Stetson suggest that fitrad should
               approximately equal to the FWHM, slightly less for crowded
               fields.  (fitrad must be smaller than psfrad.)

    :return : None
    """
    # radius of aperture and sky annulus for first-pass aperture photometry,
    # used to scale the psf
    aparcsec = 2.5
    skyradarcsec = np.array([2.5, 3.5])

    for band in bandlist:

        # convert user-supplied radii from arcsec to pixels
        appix = aparcsec / pixscale
        skyradpix = skyradarcsec / pixscale
        psfradpix = psfrad / pixscale
        fitradpix = fitrad / pixscale

        inputfile = os.path.join(
            psfimdir, '%s.e00/%s_%s_e00_reg_drz_sci.fits' % (
                starname, starname, band))
        outputfile = os.path.join(
            psfimdir, '%s_%s_%2imas_psf_model.fits' % (
                starname, band, int(pixscale * 1000)))

        hdulist = pyfits.open(inputfile)
        hdr = hdulist[0].header
        imdat = hdulist[0].data
        if 'FILTER1' in hdr:
            if 'CLEAR' in hdr['FILTER1']:
                filtname = hdr['FILTER2']
            else:
                filtname = hdr['FILTER1']
        else:
            filtname = hdr['FILTER']
        camera = getcamera(hdr)

        # Define the conversion factor from the values in this image
        # to photons : photons per ADU.
        if 'BUNIT' not in hdr:
            if camera == 'WFC3-IR' and 'EXPTIME' in hdr:
                phpadu = hdr['EXPTIME']
            else:
                phpadu = 1
        elif hdr['BUNIT'].lower() in ['cps', 'electrons/s']:
            phpadu = hdr['EXPTIME']
        elif hdr['BUNIT'].lower() in ['counts', 'electrons']:
            phpadu = 1
        assert (phpadu is not None), \
            "Can't determine units from the image header."

        rdnoise = 0
        if 'READNSEA' in hdr:
            rdnoise = np.mean([hdr[key] for key in hdr.keys()
                               if key.startswith('READNSE')])

        xmid = np.array([hdr['NAXIS1'] / 2.]) - 1
        ymid = np.array([hdr['NAXIS2'] / 2.]) - 1
        xpos, ypos = getxycenter(
            inputfile, xmid, ymid, ext=0, radec=False,
            fitsconvention=False, verbose=True)
        if verbose:
            print("PSF recentering : (%.2f,%.2f) ==> (%.2f,%.2f)" % (
                xmid, ymid, xpos, ypos))
        xpos = np.array([xpos])
        ypos = np.array([ypos])

        idpsf = np.arange(len(xpos))
        image = pyfits.getdata(inputfile)

        # run aper to get mags and sky values for specified coords
        mag, magerr, flux, fluxerr, sky, skyerr, badflag, outstr = \
            aper.aper(image, xpos, ypos, phpadu=phpadu, apr=appix,
                      zeropoint=25,
                      skyrad=skyradpix, badpix=[-12000, 60000], exact=True)

        # use the star at those coords to generate a PSF model
        gauss, psf, psfmag = getpsf.getpsf(image, xpos, ypos, mag,
                                           np.asfarray([sky]), rdnoise,
                                           phpadu,
                                           idpsf, psfradpix, fitradpix,
                                           outputfile, zeropoint=25,
                                           debug=False)
        if verbose:
            print("PSF image written to %s" % outputfile)
    return

def bin_image_data(arr, binfactor):
    # bin an array by reshaping it into a higher-order array and taking
    # the sum over the new dimension
    old_shape = arr.shape
    new_shape = np.array(old_shape) / binfactor
    shape = (new_shape[0], arr.shape[0] // new_shape[0],
             new_shape[1], arr.shape[1] // new_shape[1])
    return arr.reshape(shape).sum(-1).sum(1)

def mkpsfmodel(psfimage, xpsf=None, ypsf=None,
               psfrad=0.6, fitrad=0.3, pixscale=0.03, binning=None,
               phpadu=1, rdnoise=0, mag=25, zeropoint=25, sky=0,
               verbose=True):
    """ Construct a psf model from a star in a drizzled image.

    :param psfimage: filename of the .fits file with the star at the center in
               image array 0.
    :param psfrad: the scalar radius, in arcsec, of the circular area within
                which the PSF will be defined.  This should be slightly larger
                than the radius of the brightest star that one will be
                interested in measuring photometry for.
    :param fitrad: the scalar radius, in arcsec, of the circular area used in
               the least-square star fits.  Stetson suggest that fitrad should
               approximately equal to the FWHM, slightly less for crowded
               fields.  (fitrad must be smaller than psfrad.)
    :param pixscale: the pixel scale of the input image [arcseconds per pixel]
    :param phpadu:  the "gain" of the input image in photons per ADU  [?]
    :param rdnoise: the readnoise of the input image, in ADU [?]
    :param mag: the magnitude of the star in the input image
    :param zeropoint: the zero point of the input image (magnitude that
             produces a flux of 1 [ADU per second?]
    :param sky: the sky brightness of the input image, in ADU per second [?]
    :return : None
    """
    # TODO : currently the units in the __doc__ text are guesses. Need to
    # review the code  in the PythonPhot source and check
    import hstphot

    # convert user-supplied radii from arcsec to pixels
    psfradpix = psfrad / pixscale
    fitradpix = fitrad / pixscale

    outputfile = psfimage.replace('.fits', '_model.fits')
    hdulist = pyfits.open(psfimage)
    hdr = hdulist[0].header
    imdat = hdulist[0].data

    if xpsf is None or ypsf is None:
        # Assume star is in the center of the image:
        xmid = np.array([hdr['NAXIS1'] / 2.]) - 1
        ymid = np.array([hdr['NAXIS2'] / 2.]) - 1
        xpsf, ypsf = xmid, ymid

    xpos, ypos = getxycenter(
        psfimage, xpsf, ypsf, ext=0, radec=False,
        fitsconvention=False, verbose=True)
    if verbose:
        print("PSF recentering : (%.2f,%.2f) ==> (%.2f,%.2f)" % (
            xpsf, ypsf, xpos, ypos))
    xpos = np.array([xpos])
    ypos = np.array([ypos])
    mag = np.array([mag])
    idpsf = np.arange(len(xpos))

    if binning is not None:
        assert isinstance(binning, int)
        assert not (imdat.shape[0] % binning)
        assert not (imdat.shape[1] % binning)
        imdat = bin_image_data(imdat, binning)
        xpos /= binning
        ypos /= binning
        psfradpix /= binning
        fitradpix /= binning
        print("Binning input image %i x %i" % (binning, binning))

    # use the star at those coords to generate a PSF model
    gauss, psf, psfmag = getpsf.getpsf(
        imdat, xpos, ypos, mag,  np.asfarray([sky]), rdnoise,
        phpadu, idpsf, psfradpix, fitradpix,  outputfile, zeropoint=zeropoint,
        debug=False)
    if verbose:
        print("PSF image written to %s" % outputfile)
    return outputfile, gauss, psf, psfmag

def main():
    import argparse

    parser = argparse.ArgumentParser(
        description="Make a PythonPhot psf model from the a single-star image")

    # Required positional argument
    parser.add_argument('inputimage',
                        help='FITS file with a single star at the center.')

    # optional keyword arguments
    parser.add_argument('--pixscale', type=float,
                        default=0.03,
                        help="arcseconds per pixel.")

    argv = parser.parse_args()

    mkpsfmodel(argv.inputimage, pixscale=argv.pixscale)

if __name__ == '__main__':
    main()


#!/usr/bin/env python3
import requests
from bs4 import BeautifulSoup
import json
from slugify import slugify

# https://github.com/un33k/python-slugify

URLS = [
    "https://www.swm.de/baeder/schwimmen-sauna/auslastung"
]

def main():
    orgs = []
    for url in URLS:
        orgs += crawl_url(url)

    orgs.sort(key=lambda x: x["display_name"])

    with open("organizations.json", "w") as file:
        json.dump(orgs, file, indent=2)

def crawl_url(url):
    orgs = []
    req = requests.get(url)
    soup = BeautifulSoup(req.content, 'html.parser')
    for ticos_el in soup.select("multiple-ticos-bar-counter"):
        ids = json.loads(ticos_el["organizations"])
        displays = json.loads(ticos_el["displays"])
        orgs += [dict(id=id, name=slugify(name), display_name=name) for (id, name) in zip(ids, displays)]
    return orgs

if __name__ == "__main__":
    main()


import mmw
import typing

class TextField(mmw.Drawable):
    """A Textfield (WIP)"""
    def __repr__(self) -> str:
        if self.useRelativePos:
            return 'mmw.TextField(type=mmw.{}, name={}) at ({}/{}, {}/{})'.\
                format(self._type, repr(self.name), self.xRel, self.x,
                       self.yRel, self.y)
        else:
            return 'mmw.TextField(type=mmw.{}, name={}) at ({}, {})'.format(
                self._type, repr(self.name), self.x, self.y)

    def __init__(self, type=mmw.consts.TF_ONELINE, name=''):
        super().__init__(name)
        self.text = ['']
        self._type = None
        self.field_type = type

    @property
    def field_type(self) -> str:
        return self._type

    @field_type.setter
    def field_type(self, value):
        if value in mmw.consts.TF_TYPES:
            self._type = value
        else:
            raise ValueError(repr(value)+' is not part of mmw.consts.TF_TYPES '
                             'and cannot be used as a type. '
                             'See mmw.consts.TF_TYPES')

    def draw(self) -> typing.List[str]:
        output = ''
        if self.name != '':
            output += self.name+' '
        if self.field_type == mmw.consts.TF_ONELINE:
            if self.forcedWidth <= 0:  # Brak ustawionej wielkosci
                if self.autoResize:  # Automagiczna wielkosc
                    output += self.style['TextLeftBorder']
                    if isinstance(self.text, list):
                        output += self.text[0]
                    elif isinstance(self.text, str):
                        output += self.text
                    else:
                        output += repr(self.text)
                    output += self.style['TextRightBorder']
                    self.width = len(output)
                else:
                    raise mmw.errors.InvalidStateError('self.forcedWidth '
                                                       'is <= 0 '
                                                       'but self.autoResize '
                                                       'is not set.')
            else:
                if self.autoResize:
                    raise mmw.errors.InvalidStateError('self.autoResize '
                                                       'is set and '
                                                       'self.forcedWidth '
                                                       'is set.')
                else:
                    text = ''
                    if isinstance(self.text, list):
                        text = self.text[0][:self.forcedWidth-2]
                    elif isinstance(self.text, str):
                        text = self.text[:self.forcedWidth-2]
                    else:
                        text = repr(self.text)[:self.forcedWidth-2]
                    output += self.style['TextLeftBorder']
                    output += text
                    output += self.style['TextEmpty']\
                        * (self.forcedWidth - len(text) - 2)
                    output += self.style['TextRightBorder']
        return output.split('\n')


"""
image quality assessment (IQA) of the quantized images and the original image in l* channel of L*a*b* color space
----- method: SSIM
----- version 1.0 (skimage library)
----- http://scikit-image.org/docs/dev/auto_examples/transform/plot_ssim.html
"""
"""
Inspired by the PSNR computation, we can we can only compute SSIM for the L* channel of images.
Since luminance plane consists of significant information
in the image the evaluation score obtained is closer to human vision judgement.
"""

import csv
from skimage.measure import compare_ssim

# import the original and quantized image arrays in L*a*b* color space
from quantization_sky_float64 import testimg_list,rescale_ori

# ---- extract L* channel of the original image
L_ori = rescale_ori[:,:,0]

# ---- compare MSSIM
score_list = []
for i in testimg_list:
    L_test = i[:,:,0]
    score = compare_ssim(L_ori, L_test, multichannel=False)
    score_list.append(score)
print(score_list)

# ---- save ssim score to csv file
csvfile = "sky_ssim_in_L_lab.csv"
with open(csvfile, "w") as output:
    writer = csv.writer(output, lineterminator='\n')
    for val in score_list:
        writer.writerow([val])


import numpy as np

class Perceptron(object):
    """ Implementation of Rosenblatt's Perceptron """
    def __init__(self, seed:int=0, epochs:int=50, learning_rate:float=0.01):
        """ Initialization of Perceptron Parameters """
        self.seed = seed
        self.epochs = epochs
        self.learning_rate = learning_rate
        self.w = None

    def fit(self, X:np.array, y:np.array):
        """ Return the trained perceptron.

        Learning the perceptron using the Delta rule

        Keyword arguments:\n
            X : object features\n
            y : the correct class label
        """
        X = self.__make_bias(X).astype(np.float32)

        rnd = np.random.RandomState(self.seed)
        self.w = rnd.random(size=X.shape[1]).astype(np.float32)  # initializing the initial weights

        for _ in range(self.epochs):
            for x, y_train in zip(X, y):
                error = y_train - self.__activate(x, self.w)
                for j in range(3):
                    self.w[j] = self.w[j] + self.learning_rate * error * x[j]  # Delta rule

        return self

    def predict(self, x):
        """ Return label predicted by the model
        Prediction function

        Keyword arguments:\n
            x : input features
        """
        x = self.__make_bias(x)
        return self.__activate(x, self.w)

    def __make_bias(self, X):
        """ Adding an bias """
        bias = np.ones((np.array(X).shape[0], 1))
        return np.concatenate((np.array(X), bias), axis=1)

    def __activate(self, x, w) -> int:
        """ Activation function """
        if len(x.shape) > 1:
            res = list()
            for x_ in x:
                if (x_ @ w.T) >= 0:
                    res.append(1)
                else:
                    res.append(0)
            return np.array(res).astype(np.float32)

        if (x @ w.T) >= 0: return np.array(1).astype(np.float32)
        else: return np.array(0).astype(np.float32)


class Node:
    def __init__(self,val=0,left=None,right=None):
        self.val=val
        self.left=left
        self.right=right
def mid(node):
    slow=node
    fast=node.right
    while fast!=None and fast.next!=None:
        slow=slow.right
        fast=fast.right.right
    return slow
root=None
def creation_bst(head):
    if head==None:
        return
    m = mid(head)
    if m.left!=None:
        m.left.right=None
        m.left=None
    head2=m.right
    if m.right!=None:
        m.right.left = None
        m.right = None

    if m!=head:
        m.left=creation_bst(head)
    m.right=creation_bst(head2)
    return m

def dll_2_bst(head):
    root=creation_bst(head)
    return root

41 Convert Sorted Doubly Linked List To Binary Search Tree.py


# -*- coding: utf-8 -*-
import info

class subinfo(info.infoclass):
    def setTargets( self ):
        self.svnTargets['gitHEAD'] = "[git]http://git.cgsecurity.org/testdisk.git"
        self.patchToApply['gitHEAD'] = ('testdisk-cmake.diff', 2)
        self.defaultTarget = 'gitHEAD'

    def setDependencies( self ):
        self.hardDependencies['virtual/base'] = 'default'

from Package.CMakePackageBase import *

class Package(CMakePackageBase):
    def __init__( self, **args ):
        self.subinfo = subinfo()
        CMakePackageBase.__init__(self)

if __name__ == '__main__':
    Package().execute()


"""
    代码作用为合并DOT的TLSA记录和对应证书链，用于验证DANE
    输入依次为TLSA文件，cert文件，输出文件。
    输出为json文件
"""

__author__ = "lrx"

import argparse
import sys
import json

def getTLSA(tlsafile, merge_dict):
    f = open(tlsafile, "r")

    while True:
        line = f.readline()
        if not line: break
        data = json.loads(line)

        if data["tlsa"] != "":
            key = data["domain"] + ":" + data["ip"]

            merge_dict[key] = {"domain": data["domain"], "ip": data["ip"], "tlsa": data["tlsa"],
                               "dnssec": data["tlsa_dnssec"]}

    return merge_dict

def getCert(certfile, merge_dict):
    f = open(certfile, "r")
    keys = merge_dict.keys()

    while True:
        line = f.readline()
        if not line: break
        data = json.loads(line)

        key = data["domain"] + ":" + data["ip"]
        if key in keys:
            merge_dict[key]["cert_chain"] = data["raw_cert_chain"]

    return merge_dict

def main(args):
    global transport_type
    parser = argparse.ArgumentParser(description="Merge TLSA records and certificates to validate DANE")
    parser.add_argument('tlsa_file', help="Input file containing a list of TLSA records")
    parser.add_argument('cert_file', help="Input file containing a list of certificate")
    parser.add_argument('output', help="Output dir to write results to")

    args = parser.parse_args(args)

    merge_dict = {}
    merge_dict = getTLSA(args.tlsa_file, merge_dict)
    merge_dict = getCert(args.cert_file, merge_dict)

    fOut = open(args.output, "w")

    for key in merge_dict.keys():
        if merge_dict[key]["cert_chain"] != "":
            json.dump(merge_dict[key], fOut)
            fOut.write("\n")

if __name__ == "__main__":
    main(sys.argv[1:])


from django.core.urlresolvers import reverse

from core.tests.base import LoginWithUserTestCase

class CalculatorTestCase(LoginWithUserTestCase):
    def test_index_smoke(self):
        response = self.client.get(reverse('calculator:index'))
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'calculator/calculator.html')


import pygame
from pygame.locals import *
from gui_form import Form
from gui_button import Button
from gui_textbox import TextBox
from gui_progressbar import ProgressBar
from constantes import *
from gui_label import Label

import sqlite3

class FormMostrarDatos(Form):
    def __init__(self, name, master_surface, x, y, w, h, color_background, color_border, active):
        super().__init__(name, master_surface, x, y, w, h, color_background, color_border, active)
        #self.tablero = TextBox(master=self, x=0, y=0, w=w/2, h=h/2, color_background=color_background, color_border=None, text=text, font="Arial", font_size=14, font_color=C_BLACK)
        self.lista_widget  = []
        self.boton = Button(master=self, x=40, y=300, w=90, h=80, color_background=None, color_border=None, image_background="images/gui/set_gui_01/Pixel_Border/Buttons/arrowLeft.png",
                             on_click=self.on_click_boton_active, on_click_param="form_menu_A", text="", font="Verdana", font_size=22, font_color=C_BLACK)
        self.label_score = Label(master=self, x=150, y=10, w=200, h=50, color_background=(53,57,69), color_border=None, text="Rating", font="Arial", font_size=20, font_color=C_BLACK)
        self.lista_widget.append(self.label_score)
        self.lista_widget.append(self.boton)

    def update(self, lista_eventos,keys,delta_ms,tiempo_actual, tiempo_restante):
          for aux_widget in self.lista_widget:
            aux_widget.update(lista_eventos)

    def on_show(self, datos):
        lineas = datos.splitlines()

        for i, linea in enumerate(lineas):
            label = Label(master=self, x=150, y=70*i, w=250, h=50, color_background=(53,57,69), color_border=C_BLACK, text=linea, font="Arial", font_size=16, font_color=C_BLACK)
            self.lista_widget.append(label)

    def on_click_boton_active(self, parametro):
        print("Hola")
        self.set_active(parametro)

    def draw(self):
        super().draw()
        for aux_widget in self.lista_widget:
            aux_widget.draw()

class FormMenuB(Form):
    def __init__(self,name,master_surface,x,y,w,h,color_background,color_border,active):
        super().__init__(name,master_surface,x,y,w,h,color_background,color_border,active)
        self.text_score=""
        self.boton1 = Button(master=self,x=150,y=150,w=200,h=40,color_background=None,color_border=None,image_background="images/gui/set_gui_01/Comic_Border/Buttons/Button_XL_08.png",on_click=self.on_click_boton1,on_click_param="form_game_L1",text="BACK",font="Verdana",font_size=30,font_color=C_BLACK)
        self.boton2 = Button(master=self,x=150,y=200,w=200,h=40,color_background=None,color_border=None,image_background="images/gui/set_gui_01/Comic_Border/Buttons/Button_XL_08.png",on_click=self.on_click_boton2,on_click_param="",text="AGREGAR",font="Verdana",font_size=30,font_color=C_BLACK)
        self.boton3 = Button(master=self,x=150,y=250,w=200,h=40,color_background=None,color_border=None,image_background="images/gui/set_gui_01/Comic_Border/Buttons/Button_XL_08.png",on_click=self.on_click_boton3,on_click_param="",text="CREAR",font="Verdana",font_size=30,font_color=C_BLACK)
        self.boton4 = Button(master=self,x=150,y=300,w=200,h=40,color_background=None,color_border=None,image_background="images/gui/set_gui_01/Comic_Border/Buttons/Button_XL_08.png",on_click=self.on_click_boton4,on_click_param="",text="MOSTRAR",font="Verdana",font_size=30,font_color=C_BLACK)
        self.boton5 = Button(master=self,x=150,y=350,w=200,h=40,color_background=None,color_border=None,image_background="images/gui/set_gui_01/Comic_Border/Buttons/Button_XL_08.png",on_click=self.on_click_boton5,on_click_param="",text="Borrar datos",font="Verdana",font_size=30,font_color=C_BLACK)

        self.txt1 = TextBox(master=self,x=130,y=50,w=240,h=40,color_background=None,color_border=None,image_background="images/gui/set_gui_01/Comic_Border/Buttons/Button_XL_08.png",text="Ingrese su nombre",font="Verdana",font_size=20,font_color=C_BLACK)
        #self.label = Label(master=self, x=0, y=100, w=250, h=40, color_background=(53,57,69), color_border=C_BLACK, text="Score: {0}".format(self.text_score), font="Arial", font_size=20, font_color=C_BLACK)

        self.lista_widget = [self.boton1,self.boton2,self.boton3,self.boton4,self.txt1, self.boton5]

    def on_click_boton1(self, parametro):
        self.set_active(parametro)

    def on_click_boton2(self, parametro):
        import sqlite3
        with sqlite3.connect("db/db_score.db") as conexion:
            try:
                conexion.execute("insert into score (nombre,value) values (?,?)", (self.txt1._text, self.text_score))
                conexion.commit()# Actualiza los datos realmente en la tabla
            except:
                print("Error")

    def on_click_boton3(self, parametro):

        with sqlite3.connect("db/db_score.db") as conexion:
            try:
                sentencia = ''' create  table score
                                (
                                        id integer primary key autoincrement,
                                        nombre text,
                                        value real
                                )
                            '''
                conexion.execute(sentencia)
                print("Se creo la tabla personajes")
            except sqlite3.OperationalError:
                print("La tabla ya existe")

    def on_click_boton4(self, parametro):
        with sqlite3.connect("db/db_score.db") as conexion:
            cursor=conexion.execute("SELECT * FROM score")
            datos=""
            lista_datos=[]
            for fila in cursor:
                datos += f"Nombre: {fila[1]}, Score: {fila[2]}\n"
                lista_datos.append(fila)

            form_mostrar = FormMostrarDatos("MostrarDatos", self.master_surface,300,200, self.w, self.h, (53,57,69), (53,57,69), False)
            form_mostrar.on_show(datos)  # Configurar los datos en la etiqueta del formulario mostrado
            self.set_active("MostrarDatos")  # Mostrar el formulario FormMostrarDatos

    def on_click_boton5(self, parametro):
        with sqlite3.connect("db/db_score.db") as conexion:
            cursor = conexion.cursor()
            cursor.execute("DROP TABLE IF EXISTS score;")
            conexion.commit()

    def update(self, lista_eventos,keys,delta_ms,tiempo_actual, tiempo_restante):
        self.text_score = str(self.score)
        label = Label(master=self, x=130, y=100, w=250, h=40, color_background=(53,57,69), color_border=C_BLACK, text="Score: {0}".format(self.text_score), font="Arial", font_size=30, font_color=C_BLACK)
        self.lista_widget.append(label)

        for aux_widget in self.lista_widget:
            aux_widget.update(lista_eventos)

    def draw(self):
        super().draw()
        for aux_widget in self.lista_widget:
            aux_widget.draw()


from django.urls import path
from .views import *
from django.contrib.auth.views import LogoutView

app_name = 'blogjmv'

urlpatterns = [

    path("", Index.as_view(), name="index"),

    path("login/", login_request, name="login"),
    path("register/", register, name="register"),
    path("logout/", LogoutView.as_view(template_name="logout.html"), name="logout"),

    path("about/", About.as_view(), name="about"),
    path("post_detail/<pk>", PostDetail.as_view(), name="post_detail"),
    path("post_like/<id>", post_like, name="post_like"),
    path("comment_create/<id>", comment_create, name="comment_create"),
    path("post_by_subject/<pk>", PostBySubject.as_view(), name="post_by_subject"),
    path("post_by_author/<pk>", PostByAuthor.as_view(), name="post_by_author"),

]


# coding: utf-8
"""
This module is based off of the below article:
http://fjavieralba.com/basic-sentiment-analysis-with-python.html

I took what Javiar was doing and ran with it. A 1000 thanks mate :-)
"""

import nltk
import yaml

def split(text):
    """
    input format: a paragraph of text
    output format: a list of lists of words.
        e.g.: [['this', 'is', 'a', 'sentence'], ['this', 'is', 'another', 'one']]
    """

    nltk_splitter = nltk.data.load('tokenizers/punkt/english.pickle')
    nltk_tokenizer = nltk.tokenize.TreebankWordTokenizer()
    return [nltk_tokenizer.tokenize(sent) for sent in nltk_splitter.tokenize(text)]

def pos_tag(sentences):
    """
    input format: list of lists of words
        e.g.: [['this', 'is', 'a', 'sentence'], ['this', 'is', 'another', 'one']]
    output format: list of lists of tagged tokens. Each tagged tokens has a
    form, a lemma, and a list of tags
        e.g: [[('this', 'this', ['DT']), ('is', 'be', ['VB']), ('a', 'a', ['DT']), ('sentence', 'sentence', ['NN'])],
                [('this', 'this', ['DT']), ('is', 'be', ['VB']), ('another', 'another', ['DT']),
                ('one', 'one', ['CARD'])]]
    """

    pos = [nltk.pos_tag(sentence) for sentence in sentences]
    # adapt format
    pos = [[(word, word, [postag]) for (word, postag) in sentence] for sentence in pos]
    return pos

class DictionaryTagger(object):
    """
        Class to tag sentences
    """
    def __init__(self, dictionary_paths):
        """
            Opens YAML files and instantiates object of type DictionaryTagger
        :param dictionary_paths:
        """
        files = [open(path, 'r') for path in dictionary_paths]
        dictionaries = [yaml.load(dict_file) for dict_file in files]
        map(lambda x: x.close(), files)
        self.dictionary = {}
        self.max_key_size = 0
        for curr_dict in dictionaries:
            for key in curr_dict:
                if key in self.dictionary:
                    self.dictionary[key].extend(curr_dict[key])
                else:
                    self.dictionary[key] = curr_dict[key]
                    self.max_key_size = max(self.max_key_size, len(key))

    def tag(self, postagged_sentences):
        """
            Tags sentences with internal tags for positive and negative
        :param postagged_sentences:
        :return: tagged sentences
        """
        return [self.tag_sentence(sentence) for sentence in postagged_sentences]

    def tag_sentence(self, sentence, tag_with_lemmas=False):
        """
        the result is only one tagging of all the possible ones.
        The resulting tagging is determined by these two priority rules:
            - longest matches have higher priority
            - search is made from left to right
        """

        tag_sentence = []
        N = len(sentence)

        if self.max_key_size == 0:
            self.max_key_size = N
        i = 0

        while i < N:
            j = min(i + self.max_key_size, N)  # avoid overflow
            tagged = False

            while j > i:
                expression_form = ' '.join([word[0] for word in sentence[i:j]]).lower()
                expression_lemma = ' '.join([word[1] for word in sentence[i:j]]).lower()

                if tag_with_lemmas:
                    literal = expression_lemma
                else:
                    literal = expression_form
                if literal in self.dictionary:
                    # self.logger.debug("found: %s" % literal)
                    is_single_token = j - i == 1
                    original_position = i
                    i = j
                    taggings = [tag for tag in self.dictionary[literal]]
                    tagged_expression = (expression_form, expression_lemma, taggings)
                    if is_single_token:  # if the tagged literal is a single token, conserve its previous taggings:
                        original_token_tagging = sentence[original_position][2]
                        tagged_expression[2].extend(original_token_tagging)
                    tag_sentence.append(tagged_expression)
                    tagged = True
                else:
                    j = j - 1
            if not tagged:
                tag_sentence.append(sentence[i])
                i += 1
        return tag_sentence

def __value_of(sentiment):
    """
        Internal method to quantify polarity
    :param sentiment:
    :return:
    """
    if sentiment == 'positive': return 1
    if sentiment == 'negative': return -1
    return 0

def run_sentiment_analysis(network, add_polarity=True, flag_changes=True):
    """
    Runs Sentiment analysis on a network and returns an analyzed and scored network.
    :param network:
    :param add_polarity:
    :param flag_changes:
    :return: scored network
    """
    score = []
    data = [col for col in network.columns if ('msrc' or 'Data') in col]
    for chunk in network[data]:
        split_sentences = split(chunk)
        pos_sentences = pos_tag(split_sentences)
        tagged_sentences = DictionaryTagger(
        ['/Users/markrice/Documents/GitHub/RGH_NLP/DataTools/positive.yml',
        '/Users/markrice/Documents/GitHub/RGH_NLP/DataTools/negative.yml',
        './inv.yml']).tag(pos_sentences)
        relationship_score = sentiment_score(tagged_sentences)

        score.append(relationship_score)

    network['Sentiment Score'] = score

    if add_polarity:
        polarity = []
        for sc in score:
            if sc > 0:
                polarity.append('positive')
            elif sc < 0:
                polarity.append('negative')
            else:
                polarity.append('unknown')

        network['Polarity'] = polarity

    if flag_changes:
        network.loc[network['Polarity'] != network['PS_Polarity'], 'Polarity_Changed'] = True
        network.loc[network['Polarity'] == network['PS_Polarity'], 'Polarity_Changed'] = False

    return network

def sentence_score(sentence_tokens, previous_token, acum_score):
    """
        scores sentences thats been tagged.
    :param sentence_tokens:
    :param previous_token:
    :param acum_score:
    :return:
    """
    if not sentence_tokens:
        return acum_score
    else:
        current_token = sentence_tokens[0]
        tags = current_token[2]
        token_score = sum([__value_of(tag) for tag in tags])
        if previous_token is not None:
            previous_tags = previous_token[2]
            # if 'inc' in previous_tags:
            #    token_score *= 2.0
            # elif 'dec' in previous_tags:
            #    token_score /= 2.0
            if 'inv' in previous_tags:
                token_score *= -1.0
        return sentence_score(sentence_tokens[1:], current_token, acum_score + token_score)

def sentiment_score(review):
    """
    Returns cumulative score of scored sentences
    :param review:
    :return:
    """
    return sum([sentence_score(sentence, None, 0.0) for sentence in review])

def weighted_sentence_score(sentence_tokens):
    """
    Weighted score...
    :param sentence_tokens:
    :return: Totally arbitrary weight based on hokey pokey
    """
    tags = []
    for x in range(len(sentence_tokens)):
        tags.append(sentence_tokens[x][2])
    return sum([__value_of(tag[0]) / len(sentence_tokens) for tag in tags])

def weighted_sentiment_score(review, matrix_flag):
    """
        Totally arbitrary weight based on hokey pokey
    :param review:
    :param matrix_flag:
    :return: Totally arbitrary weight based on hokey pokey
    """
    if matrix_flag:
        return [weighted_sentence_score(sentence) for sentence in review]
    else:
        return sum([weighted_sentence_score(sentence) for sentence in review])


import http
from datetime import datetime, timedelta
import unittest
from department_app import app, db
from department_app import service
from config import Config, TestingConfig
from department_app.models import Department, Employee
from department_app.tests.tests import BaseCase

class EmployeeViewTestCase(BaseCase):
    def test_employees_view(self):
        response = self.client.get('/employees')
        self.assertEqual(response.status_code, http.HTTPStatus.OK)
        response = self.client.post('/employees', data=dict(name='test'), follow_redirects=True)
        self.assertEqual(response.status_code, http.HTTPStatus.OK)

    def test_employee_view(self):
        response = self.client.get('/employees/1')
        self.assertNotEqual(response.status_code, http.HTTPStatus.OK)
        employee = Employee(name="test",
                            date_of_birth=datetime.strptime('1999-01-01', '%Y-%m-%d'),
                            salary=123,
                            department_id=1,
                            )

        db.session.add(employee)
        db.session.commit()
        response = self.client.get('/employees/1')
        self.assertEqual(response.status_code, http.HTTPStatus.OK)

    def test_employee_delete_view(self):
        response = self.client.get('/employees/1/delete')
        self.assertEqual(response.status_code, http.HTTPStatus.NOT_FOUND)
        employee = Employee(name="test",
                            date_of_birth=datetime.strptime('1999-01-01', '%Y-%m-%d'),
                            salary=123,
                            department_id=1,
                            )

        db.session.add(employee)
        db.session.commit()
        response = self.client.get('/employees/1/delete')
        self.assertEqual(response.status_code, http.HTTPStatus.FOUND)


import asyncio

from sqlalchemy import select

from database import async_session_maker
from auth.models import Role

async def db_init():
    async with async_session_maker() as session:
        roles = await session.scalars(select(Role))
        if len(roles.all()) == 0:
            session.add(Role(name='user'))
            session.add(Role(name='admin'))
            await session.commit()
            print("`admin` and `user` roles was added")

if __name__ == '__main__':
    asyncio.run(db_init())


import hikari
import lightbulb
from datetime import timedelta, timezone, datetime

mod = lightbulb.Plugin("mod")

@mod.command
@lightbulb.add_checks(
    lightbulb.has_guild_permissions(hikari.Permissions.MANAGE_MESSAGES),
    lightbulb.bot_has_guild_permissions(hikari.Permissions.MANAGE_MESSAGES)
)
@lightbulb.option("amount", "How many messages should I delete?", type = int, required = True)
@lightbulb.command("clear", "Delete some messages")
@lightbulb.implements(lightbulb.SlashCommand)
async def clear(ctx: lightbulb.Context):
    amount = ctx.options.amount
    channel = ctx.channel_id
    msgs = await ctx.bot.rest.fetch_messages(channel).limit(amount)
    await ctx.bot.rest.delete_messages(channel, msgs)

@mod.command
@lightbulb.add_checks(
    lightbulb.has_guild_permissions(hikari.Permissions.KICK_MEMBERS),
    lightbulb.bot_has_guild_permissions(hikari.Permissions.KICK_MEMBERS)
)
@lightbulb.option("user", "Who should I kick?", type = hikari.Member, required = True)
@lightbulb.option("reason", "Why would you like to kick this user?", type = str, required = False)
@lightbulb.command("kick", "Kick an user!")
@lightbulb.implements(lightbulb.SlashCommand)
async def kick(ctx: lightbulb.Context):
    embed = hikari.Embed(title = "Success!")
    embed.add_field(name = f"You kicked {ctx.options.user}", value = f"Reason: {ctx.options.reason}")
    embed.set_footer(text = f"Requested by: {ctx.author}", icon = ctx.author.avatar_url)
    gid = ctx.guild_id
    await ctx.bot.rest.kick_member(user = ctx.options.user, guild = gid)
    await ctx.respond(embed=embed)

@mod.command
@lightbulb.add_checks(
    lightbulb.has_guild_permissions(hikari.Permissions.BAN_MEMBERS),
    lightbulb.bot_has_guild_permissions(hikari.Permissions.BAN_MEMBERS)
)
@lightbulb.option("user", "Who should I ban?", type = hikari.Member, required = True)
@lightbulb.option("reason", "Why would you like to ban this user?", type = str, required = False)
@lightbulb.command("ban", "Ban an user!")
@lightbulb.implements(lightbulb.SlashCommand)
async def ban(ctx: lightbulb.Context):
    embed = hikari.Embed(title = "Ban successful!")
    embed.add_field(name = f"You banned {ctx.options.user}", value = f"Reason: {ctx.options.reason}")
    embed.set_footer(text = f"Requested by: {ctx.author}", icon = ctx.author.avatar_url)
    gid = ctx.guild_id
    await ctx.bot.rest.ban_member(user = ctx.options.user, guild = gid)
    await ctx.respond(embed=embed)

@mod.command
@lightbulb.add_checks(
    lightbulb.has_guild_permissions(hikari.Permissions.MODERATE_MEMBERS),
    lightbulb.bot_has_guild_permissions(hikari.Permissions.MODERATE_MEMBERS)
)
@lightbulb.option("days", "Duration of the timeout in days", type=int, default=0)
@lightbulb.option("hours", "Duration of the timeout in hours", type=int, default=0)
@lightbulb.option("minutes", "Duration of the timeout in minutes", type=int, default=0)
@lightbulb.option("seconds", "Duration of the timeout in seconds", type=int, default=0)
@lightbulb.option("member", "Which user should recieve the timeout?", type=hikari.Member, required=True)
@lightbulb.command("timeout", "Timeout a member!")
@lightbulb.implements(lightbulb.SlashCommand)
async def timeout(ctx: lightbulb.Context):
    member = ctx.options.member
    now = datetime.now(timezone.utc)
    then = now + timedelta(days=ctx.options.days, hours=ctx.options.hours, minutes=ctx.options.minutes, seconds=ctx.options.seconds)
    if (then - now).days > 28:
        await ctx.respond("You can't time someone out for more than 28 days", flags=hikari.MessageFlag.EPHEMERAL)
        return
    elif (then - now).days < 28:
        embed = hikari.Embed(title="Timeout successful!", description=f"{ctx.options.member} is now muted for {ctx.options.days} days, {ctx.options.minutes} minutes and {ctx.options.seconds} seconds")
        embed.set_footer(text = f"Requested by: {ctx.author}", icon = ctx.author.avatar_url)
        await ctx.bot.rest.edit_member(user=member, guild=ctx.guild_id, communication_disabled_until=then)
        await ctx.respond(embed=embed)

def load(bot):
    bot.add_plugin(mod)


import imageio
import numpy as np

def leer_imagen(ruta):
    """
    La función leer_imagen recibe un string con la ruta
    de una imagen en formato BMP y retorna una lista de
    tres dimensiones con el mapa de bits de la imagen.
    Asimismo, convertimos la lista de numpy a una lista
    común y corriente.
    """
    np_array = np.array(imageio.imread(ruta), dtype='int')
    # noinspection PyTypeChecker
    lista_3d = np_array.tolist()
    return lista_3d

def guardar_imagen(ruta, lista_3d):
    """
    La función guardar_imagen recibe una lista de 3
    dimensiones con el mapa de bits de la imagen
    y retorna la imagen en formato bmp.
    """
    return imageio.imwrite(ruta, np.array(lista_3d, dtype='uint8'))

class Solution:

    def aplicar_escala_de_grises(self, lista_3d=leer_imagen('foto_utec.bmp')):
        result = lista_3d

        # SU SOLUCION EMPIEZA AQUI
        for matrix_2d in result:
          for matrix_1d in matrix_2d:
            suma = round(sum(matrix_1d)/3, 0)
            matrix_1d[0] = suma
            matrix_1d[1] = suma
            matrix_1d[2] = suma

        # SU SOLUCION TERMINA AQUI
        return result

    def aplicar_sepia(self, lista_3d=leer_imagen('foto_utec.bmp')):
        result = lista_3d
        # SU SOLUCION EMPIEZA AQUI
        for matrix_2d in result:
          for matrix_1d in matrix_2d:
            sepia_R = round(0.393*matrix_1d[0] + 0.769 * matrix_1d[1] + 0.189 * matrix_1d[2],0)
            sepia_G = round(0.349*matrix_1d[0] + 0.686 * matrix_1d[1] + 0.168 * matrix_1d[2],0)
            sepia_B = round(0.272*matrix_1d[0] + 0.534 * matrix_1d[1] + 0.131 * matrix_1d[2],0)

            if sepia_R > 255:
              sepia_R = 255
            if sepia_G > 255:
              sepia_G = 255
            if sepia_B > 255:
              sepia_B = 255
            matrix_1d[0] = sepia_R
            matrix_1d[1] = sepia_G
            matrix_1d[2] = sepia_B
        # SU SOLUCION TERMINA AQUI
        return result

    def aplicar_reflejo_horizontal(self, lista_3d=leer_imagen('foto_utec.bmp')):
        result = lista_3d

        # SU SOLUCION EMPIEZA AQUI
        for i in range(len(result)):
          result[i] = result[i][::-1]

        # SU SOLUCION TERMINA AQUI
        return result

    def aplicar_difuminado(self, lista_3d=leer_imagen('foto_utec.bmp')):
        result = lista_3d
        # SU SOLUCION EMPIEZA AQUI
        matriz = []
        for i in range(len(result)):
          matriz2d = []
          for j in range(len(result[i])):
            fila = []
            for k in range(len(result[i][j])):
              if i == 0 and j == 0:
                suma = round((result[i][j][k] + result[i][j+1][k] + result[i+1][j][k] + result[i+1][j+1][k])/4, 0)
                fila.append(suma)
              elif i == 0 and j == len(result[i]) - 1:
                suma = round((result[i][j][k] + result[i+1][j][k] + result[i][j-1][k] + result[i+1][j-1][k])/4, 0)
                fila.append(suma)
              elif i == len(result) - 1 and j == 0:
                suma = round((result[i][j][k] + result[i-1][j][k] + result[i][j+1][k] + result[i-1][j+1][k])/4, 0)
                fila.append(suma)
              elif i == len(result) - 1 and j == len(result[i]) - 1:
                suma = round((result[i][j][k] + result[i-1][j][k] + result[i][j-1][k] + result[i-1][j-1][k])/4, 0)
                fila.append(suma)
              elif i == 0 and j  > 0 and j < len(result[i]) - 1:
                suma = round((result[i][j][k] + result[i][j+1][k] + result[i+1][j][k] + result[i][j-1][k] + result[i+1][j-1][k]+result[i+1][j+1][k])/6, 0)
                fila.append(suma)
              elif i > 0 and j  == 0 and i < len(result) - 1:
                suma = round((result[i][j][k] + result[i-1][j+1][k] + result[i][j+1][k] + result[i+1][j+1][k] + result[i+1][j][k]+result[i][j][k])/6, 0)
                fila.append(suma)
              elif i == len(result) - 1 and j  > 0 and j < len(result[i]) - 1:
                suma = round((result[i][j][k] + result[i-1][j-1][k] + result[i-1][j][k] + result[i-1][j+1][k] + result[i][j+1][k]+result[i][j][k])/6, 0)
                fila.append(suma)

              elif i > 0 and j  == len(result[i]) - 1 and i < len(result) - 1:
                suma = round((result[i][j][k] + result[i-1][j-1][k] + result[i][j-1][k] + result[i+1][j-1][k] + result[i+1][j][k]+result[i][j][k])/6, 0)
                fila.append(suma)
              else:
                suma = round((result[i][j][k] + result[i-1][j][k] + result[i-1][j+1][k] + result[i][j+1][k] + result[i+1][j+1][k]+result[i+1][j][k] + \
                result[i+1][j-1][k] + result[i][j-1][k] + result[i][j][k])/9, 0)
                fila.append(suma)
            matriz2d.append(fila)
        matriz.append(matriz2d)
        # SU SOLUCION TERMINA AQUI
        return result


import tensorflow as tf
import matplotlib.pyplot as plt
from model import transformer
from datasets import VOCAB_SIZE, MAX_LENGTH, dataset

tf.keras.backend.clear_session()

MODEL_WEIGHT_FILE = "./transformer.h5"

# Hyper-parameters
NUM_LAYERS = 2
D_MODEL = 256
NUM_HEADS = 8
UNITS = 512
DROPOUT = 0.1

model = transformer(
    vocab_size=VOCAB_SIZE,
    num_layers=NUM_LAYERS,
    units=UNITS,
    d_model=D_MODEL,
    num_heads=NUM_HEADS,
    dropout=DROPOUT)

def loss_function(y_true, y_pred):
    y_true = tf.reshape(y_true, shape=(-1, MAX_LENGTH - 1))

    loss = tf.keras.losses.SparseCategoricalCrossentropy(
        from_logits=True, reduction='none')(y_true, y_pred)

    mask = tf.cast(tf.not_equal(y_true, 0), tf.float32)
    loss = tf.multiply(loss, mask)

    return tf.reduce_mean(loss)

class CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):

    def __init__(self, d_model, warmup_steps=4000):
        super(CustomSchedule, self).__init__()

        self.d_model = d_model
        self.d_model = tf.cast(self.d_model, tf.float32)

        self.warmup_steps = warmup_steps

    def __call__(self, step):
        arg1 = tf.math.rsqrt(step)
        arg2 = step * (self.warmup_steps**-1.5)

        return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)

sample_learning_rate = CustomSchedule(d_model=128)

plt.plot(sample_learning_rate(tf.range(200000, dtype=tf.float32)))
plt.ylabel("Learning Rate")
plt.xlabel("Train Step")

learning_rate = CustomSchedule(D_MODEL)

optimizer = tf.keras.optimizers.Adam(
    learning_rate, beta_1=0.9, beta_2=0.98, epsilon=1e-9)

def accuracy(y_true, y_pred):
    # ensure labels have shape (batch_size, MAX_LENGTH - 1)
    y_true = tf.reshape(y_true, shape=(-1, MAX_LENGTH - 1))
    return tf.keras.metrics.sparse_categorical_accuracy(y_true, y_pred)

model.compile(optimizer=optimizer, loss=loss_function, metrics=[accuracy])

EPOCHS = 20

model.fit(dataset, epochs=EPOCHS)

model.save_weights(MODEL_WEIGHT_FILE)


import random

def jogar():
    print ("*****************\nBEM VINDO AO JOGO\n*****************")

    numero_secreto = random.randint(0, 100)
    pontos = 1000

    nivel_str = input("Qual nível de dificuldade voce quer?\n1-fácil \n2-médio \n3-difícil\n")
    nivel = int(nivel_str)

    if(nivel == 1):
        total_de_tentativas = 10
    elif(nivel == 2):
        total_de_tentativas = 6
    else:
        total_de_tentativas = 4

    for rodada in range(1,total_de_tentativas+1):
        print("Tentativa {} de {}".format(rodada,total_de_tentativas))
        chute_str = input("Digite um número inteiro de 0 a 100: ")
        print(chute_str)
        chute = int(chute_str)

        if (chute < 0 or chute > 100):
            print("Você precisa digitar um valor entre 0 e 100!")
            continue
        else:
            maior_que = chute > numero_secreto
            menor_que = chute < numero_secreto

            correto = numero_secreto == chute

        if (correto):
            print("Voce acertou o número")
            print("Sua pontuação foi de: ",pontos)
            break
        else:
            if (maior_que):
                print("Voce errou o número! Seu chute foi maior do que o número secreto")
                pontos = pontos - 100
                print("Sua pontuação foi: ", pontos)
            elif (menor_que):
                print("Voce errou o número! Seu chute foi menor do que o número secreto")
                pontos = pontos - 100
                print("Sua pontuação foi: ", pontos)

    print("O número secreto é: ",numero_secreto)
    print("************\nFIM DO JOGO!\n************")

if(__name__ == "__main__"):
    jogar()


import numpy as np
import matplotlib.pyplot as plt
from itertools import product

n_items = 3
tau = .5
kappa = .5  # self inhibition
lambda_param = 8.  # lateral inhibition
threshold = 1.
noise_std = 0

n_time_steps = 50

L = np.ones((n_items, n_items)) - np.eye(n_items)

def accumulate_one_step(old_x, input_strength, params):
    coef_var = np.std(input_strength) / input_strength.mean()
    noise = np.random.normal(0, params['noise_std'], params['n_items'])
    x_new = (1 - params['tau'] * params['kappa'] - params['tau'] * params['lambda'] * L).T @ old_x \
            + coef_var * params['tau'] * input_strength + noise
    return np.maximum(x_new, 0)

def run_accumulator(n_steps, parameters, distractor_activation=.2):
    # initialize x
    x = np.zeros(parameters['n_items'])
    x_in_time = np.empty((n_steps + 1, n_items))
    x_in_time[0] = x
    for t in range(1, n_steps + 1):
        f_strength = np.eye(parameters['n_items'])[0] + (np.ones(parameters['n_items']) -
                                                         np.eye(parameters['n_items'])[0]) * distractor_activation  # note these inputs!
        x = accumulate_one_step(x, f_strength, parameters)
        x_in_time[t, :] = x
    return x_in_time

if __name__ == '__main__':

    params = {
        'n_items': n_items,
        'kappa': kappa,
        'lambda': lambda_param,
        'tau': tau,
        'threshold': threshold,
        'noise_std': noise_std
    }

    n_rows = 5
    n_cols = 5

    k_min, k_max = (.42, 1.4)
    l_min, l_max = (.53, 1.8)

    fig, axes = plt.subplots(n_rows, n_cols, figsize=(9, 9), sharex=True, sharey=True)

    kappa_range = np.linspace(k_min, k_max, n_rows)
    lambda_range = np.linspace(l_min, l_max, n_cols)

    i = 0
    for k, l in product(kappa_range, lambda_range):
        params['kappa'] = k
        params['lambda'] = l
        all_x = run_accumulator(n_time_steps, params)
        row, col = np.unravel_index(i, (n_rows, n_cols))
        axes[row, col].plot(all_x)
        axes[row, col].set_ylim([0, 1.2])
        plt.sca(axes[row, col])
        plt.axhline(params['threshold'], color='k', linestyle='--')

        axes[row, col].set_ylabel('kappa: {:.2f}'.format(k))
        axes[row, col].set_xlabel('lambda: {:.2f}'.format(l))

        i += 1

    plt.tight_layout()
    plt.savefig('accumulator_with_different_params.png')
    plt.show()

    # Now check for a requirement that one but only one accumulator reaches threshold
    k_min, k_max = (.1, 4.)
    l_min, l_max = (.1, 1.5)

    n_rows = 40
    n_cols = 40
    n_z = 11

    kappa_range = np.linspace(k_min, k_max, n_rows)
    lambda_range = np.linspace(l_min, l_max, n_cols)
    distractor_range = np.linspace(0., 1., n_z)

    param_grid = np.zeros((n_rows, n_cols, n_z), dtype=bool)
    i = 0
    for k, l, dist in product(kappa_range, lambda_range, distractor_range):

        params['kappa'] = k
        params['lambda'] = l

        all_x = run_accumulator(n_time_steps, params, distractor_activation=dist)
        idx = np.unravel_index(i, (n_rows, n_cols, n_z))

        max_accum_value = all_x.max(axis=0)  # get max for each item
        good_param = sum(max_accum_value >= params['threshold']) == 1
        param_grid[idx] = good_param
        i += 1

    # the code below plots a matrix of true and false values where true means only one item crossed
    # the threshold. This means that you can see the parameter values for which this is true.
    # i also plotted that for 10 different values for the "distractor" strength.
    xx, yy = np.meshgrid(kappa_range, lambda_range)
    for i, d in enumerate(distractor_range):
        plt.figure()
        plt.pcolormesh(xx, yy, param_grid[:, :, i])
        plt.xlabel('Kappa')
        plt.ylabel('Lambda')
        plt.title('distractor strength {:.2f}'.format(d))
        plt.savefig('good_param_vals{:.2f}.png'.format(d))
        plt.show()


from typing import Any, Dict, Union

class CharacterSheet:
    def __init__(self) -> None:
        self.data: Dict[str, Any] = {
            "alignment": "",
            "ancestry": "",
            "armors": list(),
            "attributes": dict(),
            "background": "",
            "bonus_spells": dict(),
            "classes": dict(),
            "darkvision": 0,
            "equipment": list(),
            "feats": list(),
            "features": list(),
            "gender": "",
            "height": "",
            "hit_points": 0,
            "initiative": 0,
            "is_caster": False,
            "languages": list(),
            "level": 1,
            "name": "",
            "prepared_spells": dict(),
            "proficiency_bonus": 0,
            "race": "",
            "resistances": list(),
            "savingthrows": list(),
            "size": "",
            "skills": list(),
            "speed": 0,
            "spells": list(),
            "subclasses": dict(),
            "subrace": "",
            "tools": list(),
            "traits": list(),
            "weapons": list(),
            "weight": 0,
        }

    def __getitem__(self, name: str) -> Union[Dict[str, Any], None]:
        try:
            return self.__dict__["data"][name]
        except KeyError:
            return None

    def __setitem__(self, name: str, value: Any) -> None:
        data = self.__dict__["data"]
        # Throws error on invalid entries.
        if name not in data:
            raise KeyError(f"Unknown setting key specified '{name}'.")
        # Append dictionary value to existing dictionary.
        if isinstance(data[name], dict) and isinstance(value, dict):
            data[name].update(value)
        # Append string key value to dictionary, assign value of 1.
        elif isinstance(data[name], dict) and isinstance(value, str):
            data[name][value] = 1
        elif isinstance(data[name], list) and isinstance(value, list):
            if len(data[name]) > 0:
                data[name] = list(set(data[name] + value))
            else:
                data[name] = value
        elif isinstance(data[name], list) and isinstance(value, str):
            data[name].append(value)
        else:
            data[name] = value

    def get(self, name: Union[str, None] = None) -> Union[Dict[str, Any], Any]:
        if name is None:
            return self.data
        else:
            return self.__getitem__(name)

    def set(self, name: str, value: Any) -> None:
        self.__setitem__(name, value)


import multiprocessing as mp
import numpy as np
import os
import pandas as pd
import pytorch_lightning as pl

from pathlib import Path
from torch.utils.data import Dataset, DataLoader
from transformers import AutoTokenizer
from tqdm import tqdm
from typing import Any, Dict, Optional, Tuple, Union

from .config import GuidedSummarizationConfig
from .preprocess_inputs import *
from lib.utils import checksum_of_file, read_file_to_object, read_file_to_string, write_object_to_file, write_string_to_file

tqdm.pandas()

class GuidedSummarizationDataset(Dataset):

    def __init__(self,
                 x_input: List[GuidedSummarizationInput],
                 x_guidance: List[GuidedSummarizationInput],
                 y: Optional[Union[List[GuidedSummarizationTarget], List[GuidedSummarizationExtractiveTarget]]] = None):

        self.x_input = x_input
        self.x_guidance = x_guidance
        self.y = y

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

    def __getitem__(self, idx):
        if self.y is not None:
            result = {
                'x_input': self.x_input[idx].to_dict(),
                'x_guidance': self.x_guidance[idx].to_dict(),
                'y': self.y[idx].to_dict()
            }
        else:
            result = {
                'x_input': self.x_input[idx].to_dict(),
                'x_guidance': self.x_guidance[idx].to_dict()
            }

        return result

class SummaryDataset(Dataset):

    def __init__(self, source: List[str], references: Optional[List[str]] = None):
        if references is not None:
            assert len(references) == len(source)

        self.source = source
        self.references = references

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

    def __getitem__(self, index) -> Tuple[str, Optional[str]]:
        if self.references is not None:
            return self.source[index], self.references[index]
        else:
            return self.source[index], None

class GuidedSummarizationDataModule(pl.LightningDataModule):

    def __init__(self, config: GuidedSummarizationConfig, is_extractive: bool = False):
        super(GuidedSummarizationDataModule, self).__init__()
        self.config = config
        self.lang = spacy.load(config.spacy_model)
        self.tokenizer = AutoTokenizer.from_pretrained(self.config.base_model_name)
        self.is_extractive = is_extractive

        self.train: Optional[GuidedSummarizationDataset] = None
        self.test: Optional[GuidedSummarizationDataset] = None
        self.validate: Optional[GuidedSummarizationDataset] = None

    def prepare_data(self) -> None:
        #
        # Preprocess raw data including tokenization and cleansing.
        #
        self.__prepare_dataset('test')
        self.__prepare_dataset('train')
        self.__prepare_dataset('validation')
        print("Preparation done.")

    def preprocess(self, x: List[str]) -> DataLoader:
        #
        # Pre-processes input sequences for prediction
        #
        x_prepared = [preprocess_input_sample(sample, self.lang, self.tokenizer, self.config.max_input_length, self.config.max_input_sentences, self.config.min_sentence_tokens) for sample in x]

        if self.config.guidance_method is None:
            dataset = GuidedSummarizationDataset(x_prepared, x_prepared)
        elif self.config.guidance_method == 'keywords':
            x_guidance = [preprocess_guidance_keywords(sample, self.lang, self.tokenizer, self.config.max_input_length) for sample in x]
            dataset = GuidedSummarizationDataset(x_prepared, x_guidance)
        elif self.config.guidance_method == 'extractive':
            x_guidance = [preprocess_guidance_extractive(sample, self.lang, self.tokenizer, self.config.max_input_signal_length, self.config.max_input_sentences, self.config.min_sentence_tokens) for sample in x]
            dataset = GuidedSummarizationDataset(x_prepared, x_guidance)
        else:
            raise Exception(f"Invalid guidance signal `{self.config.guidance_method}`")

        return DataLoader(dataset, num_workers=0)

    def preprocess_target(self, x: List[str]) -> DataLoader:
        y = [preprocess_output_sample(sample, self.lang, self.tokenizer, self.config.max_target_length) for sample in x]
        x_prepared = [preprocess_input_sample(sample, self.lang, self.tokenizer, self.config.max_input_length, self.config.max_input_sentences, self.config.min_sentence_tokens) for sample in x]
        dataset = GuidedSummarizationDataset(x_prepared, x_prepared, y)
        return DataLoader(dataset, num_workers=0)

    def prepare_source(self, params: (str, int, pd.DataFrame)) -> str:
        """
        Processes a batch, stores the result in a file and returns the file path.
        """
        dataset, batch_idx, df = params
        path = self.config.data_prepared_path + '/' + dataset + '.prepared.' + str(batch_idx) + '.source.pkl'
        result = df['text']\
            .progress_apply(lambda s: preprocess_input_sample(s, self.lang, self.tokenizer, self.config.max_input_length, self.config.max_input_sentences, self.config.min_sentence_tokens))\
            .to_list()

        write_object_to_file(path, result)
        return path

    def prepare_guidance_extractive(self, params: (str, int, pd.DataFrame)) -> str:
        """
        Process a batch, store the result in a file and returns the path.
        """
        dataset, batch_idx, df = params

        path = self.config.data_prepared_path + '/' + dataset + '.prepared.' + str(batch_idx) + '.guidance.ext.' + self.config.extractive_preparation_method + '.pkl'
        result = [
            preprocess_guidance_extractive_training(row['text'], row['summary'], self.lang, self.tokenizer, self.config.max_input_signal_length, self.config.max_input_sentences, self.config.min_sentence_tokens, method=self.config.extractive_preparation_method)
            for idx, row in tqdm(df.iterrows(), total=len(df.index))]
        write_object_to_file(path, result)
        return path

    def prepare_guidance_keywords(self, params: (str, int, pd.DataFrame)) -> str:
        """
        Process a batch, store the result in a file and returns the path.
        """
        dataset, batch_idx, df = params

        path = self.config.data_prepared_path + '/' + dataset + '.prepared.' + str(batch_idx) + '.guidance.key.pkl'
        result = [preprocess_guidance_keywords(row['text'], self.lang, self.tokenizer, self.config.max_input_signal_length, self.config.max_input_sentences, self.config.min_sentence_tokens) for idx, row in tqdm(df.iterrows(), total=len(df.index))]
        write_object_to_file(path, result)
        return path

    def prepare_extractive_target(self, params: (str, int, pd.DataFrame)) -> str:
        """
        Processes a batch, stores the result in a file and returns the file path.
        """
        dataset, batch_idx, df = params
        path = self.config.data_prepared_path + '/' + dataset + '.prepared.' + str(batch_idx) + '.target.ext.' + self.config.extractive_preparation_method + '.pkl'
        if os.path.isfile(path):
            return path
        else:
            result = [preprocess_extractive_output_sample(row['text'], row['summary'], self.lang, self.config.max_input_length, self.config.max_input_sentences, self.config.min_sentence_tokens, self.config.extractive_preparation_method) for idx, row in tqdm(df.iterrows(), total=len(df.index))]
            write_object_to_file(path, result)
            return path

    def prepare_target(self, params: (str, int, pd.DataFrame)) -> str:
        """
        Processes a batch, stores the result in a file and returns the file path.
        """
        dataset, batch_idx, df = params
        path = self.config.data_prepared_path + '/' + dataset + '.prepared.' + str(batch_idx) + '.target.pkl'
        result = df['summary']\
            .progress_apply(lambda s: preprocess_output_sample(s, self.lang, self.tokenizer, self.config.max_target_length))\
            .to_list()
        write_object_to_file(path, result)
        return path

    def __prepare_dataset(self, dataset: str = 'test') -> None:
        print(f'Preparing dataset {dataset} ...')
        # Make sure that the target directory exists
        Path(self.config.data_prepared_path).mkdir(parents=True, exist_ok=True)

        #
        # Load raw data
        #
        raw_data_checksum_path = self.config.data_prepared_path + '/' + dataset + '.raw.md5'
        raw_data_checksum_latest = read_file_to_string(raw_data_checksum_path)

        raw_source_path = self.config.data_raw_path + '/' + dataset + '.source'
        raw_target_path = self.config.data_raw_path + '/' + dataset + '.target'

        raw_source_checksum = checksum_of_file(raw_source_path)
        raw_target_checksum = checksum_of_file(raw_target_path)

        raw_source_df = pd.read_csv(raw_source_path)
        raw_target_df = pd.read_csv(raw_target_path)

        if self.config.is_debug:
            raw_data = pd.concat([raw_source_df, raw_target_df], axis=1)[:200]
        else:
            raw_data = pd.concat([raw_source_df, raw_target_df], axis=1)

        raw_data_checksum = raw_source_checksum + raw_target_checksum
        write_string_to_file(raw_data_checksum_path, raw_data_checksum)

        batches = enumerate(np.array_split(raw_data, self.config.max_batches))
        batches = list(map(lambda t: (dataset, t[0], t[1]), batches))

        #
        # Prepare source data
        #
        prepared_source_path = self.config.data_prepared_path + '/' + dataset + '.prepared.source.pkl'
        if (os.path.isfile(prepared_source_path) is False) or (raw_data_checksum != raw_data_checksum_latest):
            print('> process source data')
            with mp.Pool(min(self.config.max_cpus, mp.cpu_count())) as p:
                results = p.map(self.prepare_source, batches)

            prepared_target = []
            for result in results:
                prepared_target += list(read_file_to_object(result))
                os.remove(result)

            print(f'> processed {len(prepared_target)} samples')
            write_object_to_file(prepared_source_path, prepared_target)

        #
        # Prepare target data
        #
        if not self.is_extractive:
            prepared_target_path = self.config.data_prepared_path + '/' + dataset + '.prepared.target.pkl'
            if (os.path.isfile(prepared_target_path) is False) or (raw_data_checksum != raw_data_checksum_latest):
                print('> process target data')
                with mp.Pool(min(self.config.max_cpus, mp.cpu_count())) as p:
                    results = p.map(self.prepare_target, batches)

                prepared_target = []
                for result in results:
                    prepared_target += read_file_to_object(result)
                    os.remove(result)

                print(f'> processed {len(prepared_target)} samples')
                write_object_to_file(prepared_target_path, prepared_target)

        #
        # Prepare extractive target data
        #
        if self.is_extractive:
            prepared_ext_target_path = self.config.data_prepared_path + '/' + dataset + '.prepared.target.ext.' + self.config.extractive_preparation_method + '.pkl'
            if (os.path.isfile(prepared_ext_target_path) is False) or (raw_data_checksum != raw_data_checksum_latest):
                print(f'> process extractive target data ({self.config.extractive_preparation_method})')

                with mp.Pool(min(self.config.max_cpus, mp.cpu_count())) as p:
                    results = p.map(self.prepare_extractive_target, batches)

                prepared_ext_target = []
                for result in results:
                    prepared_ext_target += read_file_to_object(result)
                    os.remove(result)

                print(f'> processed {len(prepared_ext_target)} samples')
                write_object_to_file(prepared_ext_target_path, prepared_ext_target)

        #
        # Prepare summary as guidance signal
        #
        if self.config.guidance_method == 'extractive':
            prepared_guidance_ext_path = self.config.data_prepared_path + '/' + dataset + '.prepared.guidance.ext.' + self.config.extractive_preparation_method + '.pkl'

            if (os.path.isfile(prepared_guidance_ext_path) is False) or (raw_data_checksum != raw_data_checksum_latest):
                print('< process guidance signals (extractive)')

                with mp.Pool(min(self.config.max_cpus, mp.cpu_count())) as p:
                    results = p.map(self.prepare_guidance_extractive, batches)

                prepared_guidance_ext = []
                for result in results:
                    prepared_guidance_ext += read_file_to_object(result)
                    os.remove(result)

                print(f'> processed {len(prepared_guidance_ext)} samples')
                write_object_to_file(prepared_guidance_ext_path, prepared_guidance_ext)
        elif self.config.guidance_method == 'keywords':
            prepared_guidance_key_path = self.config.data_prepared_path + '/' + dataset + '.prepared.guidance.key.pkl'

            if (os.path.isfile(prepared_guidance_key_path) is False) or (raw_data_checksum != raw_data_checksum_latest):
                print('< process guidance signals (keywords)')

                with mp.Pool(min(self.config.max_cpus, mp.cpu_count())) as p:
                    results = p.map(self.prepare_guidance_keywords, batches)

                prepared_guidance_key = []
                for result in results:
                    prepared_guidance_key += read_file_to_object(result)
                    os.remove(result)

                print(f'> processed {len(prepared_guidance_key)} samples')
                write_object_to_file(prepared_guidance_key_path, prepared_guidance_key)

    def setup(self, stage: Optional[str] = None) -> None:
        self.train = self.__setup_dataloader('train')
        self.test = self.__setup_dataloader('test')
        self.validate = self.__setup_dataloader('validation')
        print(f'Setup data module with summarization dataset.')

    def __setup_dataloader(self, dataset: str = 'test'):
        print(f'Loading dataset `{dataset}` ...')
        prepared_source_path = self.config.data_prepared_path + '/' + dataset + '.prepared.source.pkl'
        prepared_target_path = self.config.data_prepared_path + '/' + dataset + '.prepared.target.pkl'
        prepared_ext_target_path = self.config.data_prepared_path + '/' + dataset + '.prepared.target.ext.' + self.config.extractive_preparation_method + '.pkl'

        prepared_source: List[GuidedSummarizationInput] = read_file_to_object(prepared_source_path)

        if self.is_extractive:
            prepared_target: List[GuidedSummarizationExtractiveTarget] = read_file_to_object(prepared_ext_target_path)
        else:
            prepared_target: List[GuidedSummarizationTarget] = read_file_to_object(prepared_target_path)

        if self.config.guidance_method == 'extractive':
            prepared_guidance_ext_path = self.config.data_prepared_path + '/' + dataset + '.prepared.guidance.ext.' + self.config.extractive_preparation_method + '.pkl'
            prepared_guidance: List[GuidedSummarizationInput] = read_file_to_object(prepared_guidance_ext_path)
        elif self.config.guidance_method == 'keywords':
            prepared_guidance_key_path = self.config.data_prepared_path + '/' + dataset + '.prepared.guidance.key.pkl'
            prepared_guidance: List[GuidedSummarizationInput] = read_file_to_object(prepared_guidance_key_path)
        else:
            prepared_guidance = read_file_to_object(prepared_source_path)

        #
        # Remove empty samples as they would lead to errors during training.
        #
        remove_indices = []

        for i in range(len(prepared_source)):
            if torch.sum(prepared_source[i].token_ids) == 0:
                remove_indices.append(i)

            if self.is_extractive and torch.sum(prepared_target[i].sentence_ids) == 0:
                remove_indices.append(i)
            elif not self.is_extractive and torch.sum(prepared_target[i].to_dict()['token_ids']) == 0:
                remove_indices.append(i)
            elif not self.is_extractive and torch.sum(prepared_guidance[i].to_dict()['token_ids']) == 0:
                remove_indices.append(i)

        if len(remove_indices) > 0:
            print(f'Removing indices due to invalid samples {remove_indices} ...')

        for i in reversed(remove_indices):
            del prepared_target[i]
            del prepared_source[i]
            del prepared_guidance[i]

        assert len(prepared_source) == len(prepared_guidance)
        assert len(prepared_source) == len(prepared_target)

        print(f'Prepared {len(prepared_source)} samples ...')

        return GuidedSummarizationDataset(prepared_source, prepared_guidance, prepared_target)

    def train_dataloader(self) -> Union[DataLoader, List[DataLoader], Dict[str, DataLoader]]:
        if self.train is None:
            raise RuntimeError('DataModule not setup properly. Call `setup` before accessing datasets.')
        else:
            return DataLoader(self.train, self.config.batch_sizes[0], num_workers=0, shuffle=True)

    def test_dataloader(self) -> Union[DataLoader, List[DataLoader]]:
        if self.test is None:
            raise RuntimeError('DataModule not setup properly. Call `setup` before accessing datasets.')
        else:
            return DataLoader(self.test, self.config.batch_sizes[1], num_workers=0)

    def val_dataloader(self) -> Union[DataLoader, List[DataLoader]]:
        if self.validate is None:
            raise RuntimeError('DataModule not setup properly. Call `setup` before accessing datasets.')
        else:
            return DataLoader(self.validate, self.config.batch_sizes[2], num_workers=0)

    def inference_dataloader(self, dataset: str = 'test', shuffle: bool = True) -> DataLoader:
        """
        Returns data for inference. The data is not pre-processed, the data loader also contains the reference sample for
        calculating ROUGE scores later.

        :param dataset The name of the dataset to load the data from.
        :param shuffle Whether data should be shuffled while loading.
        """
        raw_source_path = self.config.data_raw_path + '/' + dataset + '.source'
        raw_target_path = self.config.data_raw_path + '/' + dataset + '.target'

        raw_source_df = pd.read_csv(raw_source_path)
        raw_target_df = pd.read_csv(raw_target_path)

        raw_data = pd.concat([raw_source_df, raw_target_df], axis=1)
        sources = [row['text'] for _, row in raw_data.iterrows()]
        references = [row['summary'] for _, row in raw_data.iterrows()]

        return DataLoader(SummaryDataset(sources, references), batch_size=self.config.batch_sizes[3], num_workers=0, shuffle=shuffle)

    def transfer_batch_to_device(self, batch: Any, device: Optional[torch.device] = None) -> Any:
        batch['x_input']['token_ids'] = batch['x_input']['token_ids'].to(device)
        batch['x_input']['segment_ids'] = batch['x_input']['segment_ids'].to(device)
        batch['x_input']['attention_mask'] = batch['x_input']['attention_mask'].to(device)
        batch['x_input']['cls_indices'] = batch['x_input']['cls_indices'].to(device)
        batch['x_input']['cls_mask'] = batch['x_input']['cls_mask'].to(device)

        batch['x_guidance']['token_ids'] = batch['x_guidance']['token_ids'].to(device)
        batch['x_guidance']['segment_ids'] = batch['x_guidance']['segment_ids'].to(device)
        batch['x_guidance']['attention_mask'] = batch['x_guidance']['attention_mask'].to(device)
        batch['x_guidance']['cls_indices'] = batch['x_guidance']['cls_indices'].to(device)
        batch['x_guidance']['cls_mask'] = batch['x_guidance']['cls_mask'].to(device)

        if self.is_extractive:
            batch['y']['sentence_ids'] = batch['y']['sentence_ids'].to(device)
            batch['y']['sentence_mask'] = batch['y']['sentence_mask'].to(device)
            batch['y']['sentence_padding_mask'] = batch['y']['sentence_padding_mask'].to(device)
        else:
            batch['y']['token_ids'] = batch['y']['token_ids'].to(device)
            batch['y']['attention_mask'] = batch['y']['attention_mask'].to(device)

        return batch


contents = ["AWS Solutions Architect", "Python", "Linux"]

filenames = ["AWS Study Guide.txt", "Python Bootcamp.txt", "Linux guide.txt"]

"""The zip() function returns a zip object, which is an iterator of tuples where
the first item in each passed iterator is paired together, and then the second item in each
passed iterator are paired together etc."""

for content, filename in zip(contents, filenames):
    file = open(f"../files/{filename}", 'w')
    file.write(content)


import requests
import schedule
import custom_schedule
import time

class TelegramBot():

    def __init__(self, url):
        self.url = url
        self.chat_id = -1001367674629

    def get_updates(self):
        response = requests.get(self.url + 'getUpdates')
        return response.json()

    def last_update(self):
        results = self.get_updates()['result']
        last_updates = len(results) - 1
        return results[last_updates]

    def get_last_chat_id(self):
        return self.last_update()['message']['chat']['id']

    def send_message(self, chat_id, text):
        params = {'chat_id' : chat_id, 'text' : text}
        response = requests.post(self.url + 'sendMessage', data=params)
        return response

def send(bot):
    chat_id = -1001367674629
    bot.send_message(chat_id, "anime")

def main():
    bot = TelegramBot("https://api.telegram.org/bot1112357683:AAHsOL-X4oOku65teNY074LZuHbHdIFfGSs/")
    lessons = custom_schedule.create_schedule()
    bot.send_message(chat_id, "ANIME")
    while True:
        time.sleep(1)
        for lesson in lessons:
            if lesson.day == time.strftime("%w") and lesson.time == time.strftime("%H:%M"):
                if lesson.week == 3 or lesson.week == int(time.strftime("%W")) % 2:
                    chat_id = -1001367674629
                    resp = bot.send_message(chat_id, lesson.name + '\n' + lesson.zoom)
                    if resp.status_code == 200:
                        time.sleep(70)

if __name__ == '__main__':
	main()


"""
This class is base module for all trainers
inherit from this class.  It has basic functionality
for all trainers.

Author:Mus mbayramo@stanford.edu
"""
import argparse
import os
import sys
import tempfile
import warnings
from pathlib import Path

import loguru
import torch
import torch.distributed as dist
from accelerate import Accelerator

from igc.shared.shared_torch_utils import get_device
from ...shared.shared_accelerator import build_accelerator

class IgcBaseState:
    """
    This base state shared in trainer , modules.
    Rank, Devices, Logging
    """

    def __init__(self,
                 module_name: str,
                 spec: argparse.Namespace,
                 device=None):
        """
        This only shared states,  devices, accelerators, logging, etc.

        :param module_name:
        :param spec:
        :param device:
        """
        if not isinstance(spec, argparse.Namespace):
            raise TypeError(f"spec should be an instance of argparse.Namespace, "
                            f"received {type(spec).__name__}.")

        self._log_file = None
        self._is_trained = False
        self._trainer_args = spec

        self.logger = loguru.logger
        self._configure_logger(module_name)
        self.rank = int(os.environ.get('LOCAL_RANK', -1))

        self.is_accelerator = False
        if device is not None:
            self._device = torch.device(device)

        self._accelerator = None

        if hasattr(spec, 'use_accelerator') and spec.use_accelerator:
            self._accelerator = build_accelerator(spec)
            self.is_accelerator = True
            # let accelerator choose device.
            self._device = self._accelerator.device
            self.logger.info(f"Rank {self.rank}, Running accelerator , accelerate selected device {self.device}")
        elif hasattr(spec, "device"):
            self._device = spec.device
        else:
            self.logger.info(f"Rank {self.rank}, Running on selected device {self.device}")
            # if we are not using accelerator, we need to set device
            self._device = get_device(self.rank) if device is None else device
            raise

        self.scheduler = None

    @property
    def accelerator(self) -> Accelerator:
        """Return accelerator.
        :return:
        """
        return self._accelerator

    @property
    def device(self):
        """Return ether cuda or cpu device or accelerator device.
        :return:
        """
        if self._accelerator:
            return self.accelerator.device
        else:
            return self._device

    def _prepare_checkpoint_dir(self):
        """

        Prepares the checkpoint directory.

        :return:
        """
        checkpoint_path_dir = Path(self._trainer_args.output_dir)
        checkpoint_path_dir = checkpoint_path_dir.resolve()
        if not checkpoint_path_dir.is_dir():
            raise ValueError(f"Indicate path to checkpoint dir {checkpoint_path_dir}.")

        return str(checkpoint_path_dir)

    def _configure_logger(self, module_name: str):
        """
        Configures the logger for the module.

        :param module_name: The name of the module.
        """
        logs_dir = getattr(self._trainer_args, "log_dir", None)
        if not logs_dir:
            warnings.warn("log_dir is not provided. "
                          "Using a temporary directory as a fallback.")
            logs_dir = tempfile.mkdtemp()
        else:
            os.makedirs(logs_dir, exist_ok=True)

        self._log_file = os.path.join(logs_dir, f"{module_name}.log")
        self._log_level = getattr(
            self._trainer_args, "log_level", "ERROR"
        )
        if self._log_level:
            self._log_level = self._log_level.upper()

        self.logger = loguru.logger.bind(module_name=module_name)
        self.logger.remove()

        log_to_file = getattr(self._trainer_args, "log_to_file", None)
        if not log_to_file:
            self.logger.add(sys.stdout, level=self._log_level)
        else:
            if self._trainer_args.log_to_file:
                log_file = os.path.join(logs_dir, f"{module_name}.log")
                self.logger.add(log_file, level=self._log_level)
            else:
                self.logger.add(sys.stdout, level=self._log_level)

    def is_distributed(self):
        """
        :return:
        """
        return self.rank != -1

    def is_rank_zero(self):
        """
        :return:
        """
        return self.rank == -1 or self.rank == 0

    def is_last_worker(self):
        """

        :return:
        """
        if self.rank == -1:
            return True

        rank = dist.get_rank()
        world_size = dist.get_world_size()

        is_last_worker = rank == (world_size - 1)
        return is_last_worker

    def log_memory_usage(self):
        """
        Log memory usage.
        :return:
        """
        if torch.cuda.is_available():
            mem_get_info = torch.cuda.memory_stats()
            self.logger.info("Memory allocated:", mem_get_info["allocated_bytes.all.current"] / 1024 ** 3, "GB")
            # additional CUDA statistics if available
            if hasattr(torch.cuda, 'utilization'):
                self.logger.info(f"CUDA utilization:", torch.cuda.utilization())
            if hasattr(torch.cuda, 'memory_summary'):
                torch.cuda.memory_summary()

    def show_accelerator_info(self):
        """
        Show information about the accelerator used.
        """
        if self.is_accelerator:
            self.logger.debug("Accelerator Configuration:")
            self.logger.debug(f"is main process: {self.accelerator.is_main_process}")
            self.logger.debug(f"Distributed Training: {self.accelerator.distributed_type}")
            self.logger.debug(f"Device Placement: {self.accelerator.device_placement}")
            self.logger.debug(f"Split Batches: {self.accelerator.split_batches}")
            self.logger.debug(f"Mixed Precision: {self.accelerator.mixed_precision}")
            self.logger.debug(f"Project Directory: {self.accelerator.project_dir}")
            self.logger.debug(f"Dispatch Batches: {self.accelerator.dispatch_batches}")
            self.logger.debug(f"Even Batches: {self.accelerator.even_batches}")
            self.logger.debug(f"RNG Types: {self.accelerator.rng_types}")
            self.logger.debug(f"Log With: {self.accelerator.log_with}")
            self.logger.debug(f"Step Scheduler with Optimizer: {self.accelerator.step_scheduler_with_optimizer}")


# Программа которая:
# 1. Принимает на вход слово
# 2. Если слово "корова", то печатает "му"
# 3. В остальных случаях печатает "фиг его взнает"

t = str(input("Введи название животного: "))
if t == "корова":
  print ("Мууууууууууу!!!!!")
if not t == "корова":
  print ("фиг его знает")


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('advertisements', '0007_auto_20151115_1859'),
    ]

    operations = [
        migrations.CreateModel(
            name='category_type',
            fields=[
                ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
                ('Category_ID', models.CharField(max_length=8, null=True, blank=True)),
                ('Category', models.CharField(max_length=20, null=True, blank=True)),
            ],
            options={
                'db_table': 'category_type',
                'verbose_name_plural': 'category_type',
            },
        ),
        migrations.RemoveField(
            model_name='advertisement',
            name='Buyer_User_ID',
        ),
        migrations.RemoveField(
            model_name='advertisement',
            name='Sold_Date',
        ),
    ]


dataList = []

dataType = input("Select data type: ")
raw = input("Please input shit: ")
if dataType == "f":
    raw = raw.split(",")

    for i in range(int(len(raw)/2)):
        for j in range(int(raw[i * 2])):
            dataList.append(int(raw[i * 2 + 1]))
elif dataType == "fs":
    dataList = raw.split(", ")
    dataList = list(map(int, dataList))
elif dataType == "fn":
    dataList = raw.split(",")
    dataList = list(map(int, dataList))

devList = []
avg = sum(dataList)/len(dataList)
print("The average is:", avg)

for i in dataList:
    devList.append((i - avg)**2)

print("The standard deviation is:", (sum(devList)/len(devList))**0.5)


# -*- coding: utf-8 -*-
import scrapy
import re
from datetime import datetime
from scrapy import log
from scrapy.http import Request
from scrapy.spider import BaseSpider
from scrapy.contrib.loader import ItemLoader
from travelzoo.items import TravelZooDeal

class TravelZooComSpider(BaseSpider):
    """Spider for regularly updated travelzoo.com site, UK version"""
    name = 'travelzoo.com'
    allowed_domains = ['www.travelzoo.com']
    start_urls = ['http://www.travelzoo.com/uk/']

    def parse(self, response):
        # select all links in the left hand menu which aren't top level ones (don't have li class attribute) and aren't in the Destinations menu
        hrefs = response.xpath("//div[@id='leftNavigationWrapper']/ul/li[a/text()!='Destinations']//ul/li[not(@class)]/a/@href").extract()
        for href in hrefs:
            self.log("Yielding request for url: %s" % href)
            yield Request(url=href, callback=self.parse_section)

    def parse_section(self, response):
        items = response.xpath("//div[contains(@class,'featuredDeal') or contains(@class, 'premiumPlacement') or contains(@class, 'dealItem')]")
        for item in items:
            item_href = item.xpath(".//h2/a/@href").extract()[0]
            pattern = '[-/](\d{6,7})[/0-9A-Za-z-]*$'
            match = re.search(pattern, item_href)
            if match is None:
                self.log("ERROR couldn't parse id from url: %s using regex: %s" % (item_href, pattern), level=log.ERROR)
                return
            item_id = match.group(1)
            self.log("Item id: %s, yielding url: %s" % (item_id, item_href))
            yield Request(url=item_href, callback=self.parse_item, meta={'url': item_href, 'id': item_id})

    def parse_item(self, response):
        self.log("Parsing item url: %s" % response.url)
        self.log("Url of the page is actually %s" % response.url)
        i = TravelZooDeal()
        i['id'] = response.meta['id']
        i['url'] = response.meta['url']
        if len(response.css('.page.noBorder')):
            return self.parse_item_no_border(response, i)
        elif len(response.css('.page.withBorder')):
            return self.parse_item_with_border(response, i)
        else:
            self.log("Parsing unknown page type, this may not give many details...")
            loader = ItemLoader(item=i, response=response)
            loader.add_css('name', 'h1::text')
            loader.add_css('description', '.dealText p:first-child')
            loader.add_css('whats_included', '.dealText ul')
            return loader.load_item()

    def parse_item_with_border(self, response, i):
        self.log("Parsing page with border")
        page = response.css('.innerDealPage')
        loader = ItemLoader(item=i, selector=page)
        loader.add_css('name', 'h1::text')
        loader.add_xpath('description', "//div[contains(@class, 'introDescription')]//text()")
        loader.add_xpath('why_we_love_it', ".//div[contains(@class,'dealDetailsSection') and h2[text()='Why we love it']]/ul//text()")

        loader.add_xpath('whats_included', ".//div[contains(@class,'dealDetailsSection') and h2[contains(text(), 'included')]]/ul//text()")
        loader.add_xpath('small_print', ".//div[contains(@class,'dealDetailsSection') and h2[text()='The small print']]/p//text()")

        div_where = page.xpath(".//div[contains(@class,'dealDetailsSection') and h2[text()='Where']]")
        loader.selector = div_where
        loader.add_xpath('contact_name', "div[contains(@id,'MerchantName')]/text()")
        loader.add_xpath('contact_address', "div[contains(@id,'MerchantAddress')]/text()")
        loader.add_xpath('contact_map', "div[contains(@id,'LinkMap')]/text()")
        loader.add_xpath('contact_phone', "div[contains(@id,'MerchantPhone')]/text()")
        loader.add_xpath('contact_website', "div[contains(@id,'MerchantWebsite')]/text()")

        deal_page_right = response.css('#dealPageRightPart')
        loader.selector = deal_page_right
        loader.add_xpath('price', ".//span[@id='ctl00_Main_OurPrice']/text()")
        loader.add_xpath('value', ".//span[@id='ctl00_Main_PriceValue']/text()")
        loader.add_xpath('discount', ".//span[@id='ctl00_Main_Discount']/text()")
        loader.add_xpath('bought', ".//span[contains(@id,'Bought')]/text()")
        return loader.load_item()

    def parse_item_no_border(self, response, i):
        self.log("Parsing page no border")
        page = response.css('.page.noBorder')
        loader = ItemLoader(item=i, selector=page)
        loader.add_css('name', 'h1::text')
        loader.add_xpath("why_we_love_it", ".//div[contains(@id,'spanWhyLove')]/ul")
        loader.add_xpath("whats_included", ".//div[contains(@id,'DivWhatsIncluded')]/div")
        return loader.load_item()


class Solution:
    def checkRecord(self, s):
        """
        :type s: str
        :rtype: bool
        """
        countA = 0
        streakOfL = 0

        for i in range(0, len(s)): # iterate through record
            if s[i] == 'L': # if we find a L, we continue loop and check the streak if we need to return False, if not streak will be reset
                streakOfL += 1
                if streakOfL > 2:
                    return False
                continue

            elif s[i] == 'A': # if we find more then one A at any point we return false
                countA += 1
                if countA > 1:
                    return False
            streakOfL = 0

        return True


# quickstart.py
import asyncio
import time

async def main():
    print(f"{time.ctime()} Hello!")
    await asyncio.sleep(1.0)
    print(f"{time.ctime()} Goodbye!")
    loop.stop()

loop = asyncio.get_event_loop()
loop.create_task(main())
loop.run_forever()
pending = asyncio.Task.all_tasks(loop=loop)
group = asyncio.gather(*pending, return_exceptions=True)
loop.run_until_complete(group)
loop.close()

# Output:
# $ python quickstart.py
# Sun Sep 17 14:17:37 2017 Hello!
# Sun Sep 17 14:17:38 2017 Goodbye!