"""
Crawler implementation
"""
import json
import os
import re
import datetime
import shutil
from time import sleep
import requests
from bs4 import BeautifulSoup
from article import Article
from constants import CRAWLER_CONFIG_PATH, ASSETS_PATH

headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
                  'Chrome/89.0.4389.82 Safari/537.36'}

class IncorrectURLError(Exception):
    """
    Custom error
    """

class NumberOfArticlesOutOfRangeError(Exception):
    """
    Custom error
    """

class IncorrectNumberOfArticlesError(Exception):
    """
    Custom error
    """

class UnknownConfigError(Exception):
    """
    Most general error
    """

class Crawler:
    """
    Crawler implementation
    """

    def __init__(self, seed_urls: list, total_max_articles: int, max_articles_per_seed: int):
        self.seed_urls = seed_urls
        self.total_max_articles = total_max_articles
        self.max_articles_per_seed = max_articles_per_seed
        self.urls = []

    @staticmethod
    def _extract_url(article_bs):
        return article_bs.find('a').attrs['href']

    def find_articles(self):
        """
        Finds articles
        """
        for s_url in self.seed_urls:
            response = requests.get(s_url, headers=headers)
            sleep(5)
            if not response:
                raise IncorrectURLError
            article_bs = BeautifulSoup(response.content, features='lxml')
            links = article_bs.find_all('div', {'class': 'entry-summary'})
            urls_number = min(articles_per_seed, len(links), (max_articles - len(self.urls)))
            for index in range(urls_number):
                self.urls.append('https://kostroma.news/' + self._extract_url(article_bs=links[index]))

        return self.urls

    def get_search_urls(self):
        """
        Returns seed_urls param
        """
        return self.seed_urls

class ArticleParser:
    """
    ArticleParser implementation
    """

    def __init__(self, full_url: str, article_id: int):
        self.article_url = full_url
        self.ids = article_id
        self.article = Article(full_url, article_id)

    def _fill_article_with_text(self, article_soup):
        self.article.text = article_soup.find(name='div', class_="entry-content").text

    def _fill_article_with_meta_information(self, article_soup):
        self.article.title = article_soup.find('h1', class_='entry-title').text.strip()
        self.article.author = 'NOT FOUND'
        for topic in article_soup.find_all('a', rel="tag"):
            self.article.topics.append(topic.text)
        self.article.date = self.unify_date_format(article_soup.find('span', class_='date updated').text)

    @staticmethod
    def unify_date_format(date_str):
        """
        Unifies date format
        """
        return datetime.datetime.strptime(date_str, "%d.%m.%Y")

    def parse(self):
        """
        Parses each article
        """
        article_bs = BeautifulSoup(requests.get(self.article_url, headers=headers).content, 'lxml')
        self._fill_article_with_text(article_bs)
        self._fill_article_with_meta_information(article_bs)
        self.article.save_raw()
        return self.article

def prepare_environment(base_path):
    """
    Creates ASSETS_PATH folder if not created and removes existing folder
    """
    if os.path.exists(base_path):
        shutil.rmtree(base_path)
    os.makedirs(base_path)

def validate_config(crawler_path):
    """
    Validates given config
    """
    with open(crawler_path, 'r', encoding='utf-8') as file:
        crawler_config = json.load(file)

    for base_url in crawler_config['base_urls']:
        if not re.match('https://', base_url):
            raise IncorrectURLError

    if 'total_articles_to_find_and_parse' in crawler_config and \
            isinstance(crawler_config['total_articles_to_find_and_parse'], int) and \
            crawler_config['total_articles_to_find_and_parse'] > 100:
        raise NumberOfArticlesOutOfRangeError

    if not isinstance(crawler_config['total_articles_to_find_and_parse'], int):
        raise IncorrectNumberOfArticlesError

    return crawler_config['base_urls'], crawler_config['total_articles_to_find_and_parse'], \
           crawler_config['max_number_articles_to_get_from_one_seed']

if __name__ == '__main__':
    # YOUR CODE HERE
    prepare_environment(ASSETS_PATH)
    urls, max_articles, articles_per_seed = validate_config(CRAWLER_CONFIG_PATH)

    crawler = Crawler(seed_urls=urls, total_max_articles=max_articles, max_articles_per_seed=articles_per_seed)
    crawler.find_articles()

    for i, url in enumerate(crawler.urls):
        parser = ArticleParser(full_url=url, article_id=i+1)
        parser.parse()


import numpy as np
import cv2 as cv
import argparse

#
# cap = cv.VideoCapture("slow_traffic_small.mp4")
# # cap = cv.VideoCapture("method_2_forground.avi")
#
# # params for ShiTomasi corner detection
# feature_params = dict( maxCorners = 100,
#                        qualityLevel = 0.3,
#                        minDistance = 7,
#                        blockSize = 7 )

# Parameters for lucas kanade optical flow
lk_params = dict( winSize  = (15,15),
                  maxLevel = 2,
                  criteria = (cv.TERM_CRITERIA_EPS | cv.TERM_CRITERIA_COUNT, 10, 0.03))

# Create some random colors for drawing tracks
color = np.random.randint(0,255,(100,3))

# Take first frame and find corners in it
old_frame = cv.imread("blob/BB_0.png")
old_gray = cv.cvtColor(old_frame, cv.COLOR_BGR2GRAY)
# x[475, 462, 499, 796, 322, 466, 445, 436, 437, 532, 455, 521, 437, 498, 57, 727, 426, 498, 827, 421, 522, 635, 854]
# y[636, 626, 625, 621, 600, 599, 595, 590, 587, 583, 582, 567, 567, 560, 559, 557, 551, 541, 538, 536, 535, 528, 439]

p0 = np.array([[475 ,636] ,[462, 626] ,[499 ,625], [796, 621] ,[322 ,600], [466 ,599]])
print(p0)

# Create a mask image for drawing purposes
mask = np.zeros_like(old_frame)

for z in range(1,199):
    frame = cv.imread("blob/BB_"+str(z)+".png")
    frame_gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
    cv.imwrite(str(z)+".png",frame_gray)

    # calculate optical flow
    p1, st, err = cv.calcOpticalFlowPyrLK(old_gray, frame_gray, p0, None, **lk_params)
    # Select good points
    good_new = p1[st==1]
    good_old = p0[st==1]

    # draw the tracks
    for i,(new,old) in enumerate(zip(good_new,good_old)):
        a,b = new.ravel()
        c,d = old.ravel()
        mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)
        frame = cv2.circle(frame,(a,b),5,color[i].tolist(),-1)
    img = cv2.add(frame,mask)

    cv2.imshow('frame',img)
    k = cv2.waitKey(30) & 0xff
    if k == 27:
        break

    # Now update the previous frame and previous points
    old_gray = frame_gray.copy()
    p0 = good_new.reshape(-1,1,2)


import random
import numpy as np
from scipy.misc import imread
import matplotlib.pyplot as plt

def imstack(img, s1, s2):
    n1, n2 = img.shape
    s = (2*s1+1)*(2*s2+1)
    xstack = np.empty((n1, n2, 0))
    for k in range(-s1,s1+1):
        for l in range(-s2,s2+1):
            xshift = np.expand_dims(imshift(img, -k, -l), axis=-1)
            xstack = np.append(xshift,xstack, axis=-1)
    return xstack

def imshift(x, k, l):
    h,w = x.shape
    xshifted = np.zeros((h,w))
    if k == 0:
        k = h
    if l == 0:
        l = w
    xshifted[-k:,-l:] = x[:k,:l]
    xshifted[:-k,:-l] = x[k:,l:]
    xshifted[:-k,-l:] = x[k:,:l]
    xshifted[-k:,:-l] = x[:k,l:]
    return xshifted

def sort(simg):
    n1, n2 = simg.shape
    for h in range(n1):
        for w in range(n2):
            simg[h, w].sort()
    return simg

def imosf(x, typ, s1, s2):
    n1, n2 = x.shape
    xosf = np.zeros((n1, n2))
    xstack = imstack(x, s1, s2)
    if typ == "median":
        xosf = np.median(xstack, axis=-1)
    elif typ =="erode":
        xosf = np.min(xstack, axis=-1)
    elif typ == "dilate":
        xosf = np.max(xstack, axis=-1)
    elif typ == "trimmed":
        xosf = np.sort(xstack, axis=-1)
        s = 2*(s1+1)*2*(s2+1)
        xosf = np.mean(xosf[:, :, int(s*0.25):int(s*0.75)], axis=-1)
    elif typ == "close":
        tem = np.max(xstack, axis=-1)
        tem = imstack(tem, s1, s2)
        xosf =  np.min(tem, axis=-1)
    elif typ == "open":
        tem = np.min(xstack, axis=-1)
        tem = imstack(tem, s1, s2)
        xosf =  np.max(tem, axis=-1)
    return xosf

def pepper(x, rate):
    n1, n2 = x.shape
    noise_p = int(n1*n2*rate)
    for r in range(noise_p):
        x[random.randint(0, n1-1),random.randint(0, n2-1)] = random.choice([0, 255])
    return x

s1 = 2
s2 = 2
img = imread('castle.png')
img_noise = pepper(img, 0.05)

plt.subplot(1, 5, 1)
plt.title("noise")
plt.axis('off')
plt.imshow(img_noise ,cmap = plt.get_cmap('gray'))

img1 = imosf(img_noise,"median",s1,s2)
plt.subplot(1, 5, 2)
plt.title("median")
plt.axis('off')
plt.imshow(img1 ,cmap = plt.get_cmap('gray'))

img2 = imosf(img_noise,"trimmed",s1,s2)
plt.subplot(1, 5, 3)
plt.title("trimmed")
plt.axis('off')
plt.imshow(img2 ,cmap = plt.get_cmap('gray'))

img11 = imosf(img_noise,"close",s1,s2)
plt.subplot(1, 5, 4)
plt.title("closing")
plt.axis("off")
plt.imshow(img11 ,cmap = plt.get_cmap('gray'))

img22 = imosf(img_noise,"open",s1,s2)
plt.subplot(1, 5, 5)
plt.title("opening")
plt.axis("off")
plt.imshow(img22 ,cmap = plt.get_cmap('gray'))

plt.show()


# Standard Library

# First Party
from smdebug.core.json_config import CONFIG_FILE_PATH_ENV_STR
from smdebug.core.modes import ModeKeys
from smdebug.tensorflow.session import SessionHook

# Local
from .utils import pre_test_clean_up

def test_collection_defaults_json(out_dir, monkeypatch):
    pre_test_clean_up()
    monkeypatch.setenv(
        CONFIG_FILE_PATH_ENV_STR,
        "tests/tensorflow/hooks/test_json_configs/test_collection_defaults.json",
    )
    hook = SessionHook.create_from_json_file()

    # Check save_intervals for each mode
    assert hook.save_config.get_save_config(ModeKeys.TRAIN).save_interval == 2
    assert hook.save_config.get_save_config(ModeKeys.EVAL).save_interval == 3
    assert hook.save_config.get_save_config(ModeKeys.PREDICT).save_interval == 1
    assert hook.save_config.get_save_config(ModeKeys.GLOBAL).save_interval == 1
    # Check include_collections
    assert "weights" in hook.include_collections and "losses" in hook.include_collections

    assert len(hook.include_collections) == 4
    # Check collection configurations for losses
    assert (
        hook.collection_manager.collections["losses"]
        .save_config.get_save_config(ModeKeys.TRAIN)
        .save_interval
        == 2
    )
    assert (
        hook.collection_manager.collections["losses"]
        .save_config.get_save_config(ModeKeys.EVAL)
        .save_interval
        == 4
    )
    assert (
        hook.collection_manager.collections["losses"]
        .save_config.get_save_config(ModeKeys.PREDICT)
        .save_interval
        == 1
    )
    assert (
        hook.collection_manager.collections["losses"]
        .save_config.get_save_config(ModeKeys.GLOBAL)
        .save_interval
        == 5
    )
    # Check collection configuration for weights
    assert (
        hook.collection_manager.collections["weights"]
        .save_config.get_save_config(ModeKeys.TRAIN)
        .save_interval
        == 2
    )
    assert (
        hook.collection_manager.collections["weights"]
        .save_config.get_save_config(ModeKeys.EVAL)
        .save_interval
        == 3
    )
    assert (
        hook.collection_manager.collections["weights"]
        .save_config.get_save_config(ModeKeys.PREDICT)
        .save_interval
        == 1
    )
    assert (
        hook.collection_manager.collections["weights"]
        .save_config.get_save_config(ModeKeys.GLOBAL)
        .save_interval
        == 1
    )


class Solution:
    def stoneGameVI(self, aliceValues: List[int], bobValues: List[int]) -> int:
        s=sorted(zip(aliceValues, bobValues), key=sum, reverse=True)
        print(s)
        a=sum(i for i, j in s[::2])
        b=sum(j for i, j in s[1::2])
        if a>b: return 1
        elif a<b: return -1
        else: return 0


from __future__ import absolute_import, unicode_literals
from logging import Logger
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from celery import task
from api.models import Container
from django.db import OperationalError
import logging
import subprocess
import docker
import requests

# Get an instance of a logger
logger = logging.getLogger(__name__)  # type: Logger

@task()
def probe_per_sec():
    # Only CPU logging for now
    bulk = str(subprocess.check_output("docker stats --format '{{.Container}} {{.CPUPerc}}' --no-stream", shell=True))
    bulk_list = filter(None, bulk.split("\n"))
    # logger.info(bulk_list)
    for line in bulk_list:
        all_info = line.split()
        cont_id = all_info[0]
        cpu = all_info[1][:-1]
        # Lock access to db during transaction (safeguard against concurrent increments)
        with transaction.atomic():
            try:
                cont = Container.objects.select_for_update().get(cont_id=cont_id)
            except ObjectDoesNotExist:
                # Create container representation in the db if it does not exist
                cont = Container(cont_id=cont_id)
            cont.accu_cpu += float(cpu)
            cont.ticks += 1
            try:
                cont.save()
            except OperationalError:
                logger.warning("DB locked: concurrency avoided")
        # logger.info(cont.acu_cpu)
        # logger.info(cont.ticks)

@task()
def probe_per_interval():
    # Get docker client
    client = docker.from_env()
    # Get containers
    containers = client.containers.list()
    # Get Container stats & predict
    for container in containers:
        cont = Container.objects.get(cont_id=container.id[:12])
        port = subprocess.check_output(["docker port {0} | cut -d ':' -f 2".format(container.id)], shell=True)[:-1]
        get_url = "http://localhost:{0}/ca_tf/getLogs/".format(port)
        interval_info = requests.get(get_url)
        logger.info(interval_info.text)
        logger.info(interval_info.json())
        interval_info_dict = interval_info.json()
        cont.prev_subm = interval_info_dict['requests_submitted']
        cont.prev_rej = interval_info_dict['requests_rejected']
        cont.prev_fin = interval_info_dict['requests_finished']
        cont.prev_art = interval_info_dict['average_response_time']
        cont.predict_next_rr(sampling_interval=30)
        cont.print_logs(start_time)
        cont.save()


#!/usr/bin/env python

"""
Spectra class to wrap extracted spectra, their resolution matrix, and
their projection back to CCD pixels.

Stephen Bailey, Summer 2011
"""

import sys
import os
import numpy as N
import pyfits
from bbspec.spec2d import ResolutionMatrix
from scipy import sparse

class Spectra(object):
    def __init__(self, flux, ivar, loglam,
                 R=None,
                 xflux=None, ixcovar=None, fullflux=None,
                 ispecmin=0, ifluxmin=0,
                 pix=None, xmin=0, ymin=0):
        """
        Initialize Spectra object

        Required inputs:
            flux   2D array of flux values [nspec, nflux]
            ivar   2D array of flux inverse variances [nspec, nflux]
            loglam 1D or 2D array of log10(wavelength) [nflux] or [nspec,nflux]

        Optional:
            R       : array of ResolutionMatrix objects [nspec]
            xflux   : deconvolved spectra [nspec,nflux]
            ixcovar : inverse covariance of xflux [nspec*nflux, nspec*nflux]
            ispecmin, ifluxmin : if these spectra are subset of the total,
                                 these indices give the offset from 0

        Use Spectra.blank(loglam) to create a blank Spectrum object

        TODO: Incorporate projected spectra -> pixels
        """
        #+ Add array consistency checks; raise exceptions for inconsistencies

        #- Basic array dimensions
        nspec, nflux = flux.shape
        self.nspec = nspec
        self.nflux = nflux

        #- Required inputs and defaults
        self.flux = flux
        self.ivar = ivar
        if loglam.ndim == 1:
            loglam = N.tile(loglam, nspec).reshape(nspec, nflux)
        self.loglam = loglam

        #- Starting indices default 0, but may be >0 to indicate subset
        self.ispecmin = ispecmin
        self.ifluxmin = ifluxmin

        #- Optional inputs; these could be None
        self.R = R
        self.xflux = xflux
        self.fullflux = fullflux
        self.ixcovar = ixcovar
        self.pix = pix
        self.xmin = xmin
        self.ymin = ymin

    def merge(self, spectra):
        """
        Merge these spectra with values from another Spectra object.
        For overlaps, assumes new Spectra are correct
        """
        i0 = spectra.ispecmin-self.ispecmin
        iispec = slice(i0, i0+spectra.nspec)

        i1 = spectra.ifluxmin-self.ifluxmin
        iiflux = slice(i1, i1+spectra.nflux)

        self.flux[iispec, iiflux] = spectra.flux
        self.ivar[iispec, iiflux] = spectra.ivar

        if self.xflux is not None:
            self.xflux[iispec, iiflux] = spectra.xflux

        for i in range(spectra.nspec):
            j = (spectra.ispecmin - self.ispecmin) + i
            if self.R[j] is None:
                full_range = self.ifluxmin, self.ifluxmin + self.nflux
                self.R[j] = ResolutionMatrix.blank(bandwidth=15, \
                            nflux=self.nflux, full_range=full_range)

            self.R[j].merge(spectra.R[i])

        if self.pix is None:
            if spectra.pix is not None:
                self.pix = spectra.pix.copy()
                self.xmin = spectra.xmin
                self.ymin = spectra.ymin
            else:
                pass
        elif spectra.pix is not None:
            xmin = min(self.xmin, spectra.xmin)
            ymin = min(self.ymin, spectra.ymin)
            xmax = max(self.xmax, spectra.xmax)
            ymax = max(self.ymax, spectra.ymax)
            nxtot = xmax-xmin+1
            nytot = ymax-ymin+1
            pix = N.zeros((nytot, nxtot))
            for spec in self, spectra:
                ny, nx = spec.pix.shape
                x0 = spec.xmin - xmin
                y0 = spec.ymin - ymin
                #- Add, not replace pixels
                pix[y0:y0+ny, x0:x0+nx] += spec.pix

            self.pix = pix
            self.xmin = xmin
            self.ymin = ymin

    @property
    def xmax(self):
        if self.pix is None:
            return None
        else:
            return self.xmin + self.pix.shape[1]

    @property
    def ymax(self):
        if self.pix is None:
            return None
        else:
            return self.ymin + self.pix.shape[0]

    @property
    def nx(self):
        if self.pix is None:
            return 0
        else:
            return self.pix.shape[1]

    @property
    def ny(self):
        if self.pix is None:
            return 0
        else:
            return self.pix.shape[0]

    def calc_model_image(self, psf, xyrange=None):
        """
        Calculate model image using psf object; fill in self.pix array

        xyrange = (xmin, xmax, ymin, ymax) in pixels
        """
        spec_range = (self.ispecmin, self.ispecmin+self.nspec)
        flux_range = (self.ifluxmin, self.ifluxmin+self.nflux)
        if xyrange is None:
            xyrange = psf.xyrange(spec_range, flux_range)
        xmin, xmax, ymin, ymax = xyrange
        self.pix = psf.spec2pix(self.xflux, xyrange=xyrange, \
                    ispecmin=self.ispecmin, ifluxmin=self.ifluxmin )
        self.xmin = xmin
        self.ymin = ymin

    def write(self, filename, comments=None, clobber=True):
        """
        Write spectra to a fits file
        """
        hdus = list()
        hdus.append( pyfits.PrimaryHDU(self.flux) )
        hdus.append( pyfits.ImageHDU(self.ivar) )
        hdus.append( pyfits.ImageHDU(self.loglam) )
        R = list()
        bandwidth = 15
        for i, Rx in enumerate(self.R):
            if Rx is not None:
                R.append(ResolutionMatrix.to_diagonals(Rx))
            else:
                R.append(N.zeros((bandwidth, self.nflux)))
        R = N.array(R)
        hdus.append( pyfits.ImageHDU(R) )

        #- Optional HDUs; data may be blank
        hdus.append( pyfits.ImageHDU(self.xflux) )
        hdus.append( pyfits.ImageHDU(self.ixcovar) )
        hdus.append( pyfits.ImageHDU(self.pix) )

        #- Add EXTNAME keywords
        hdus = pyfits.HDUList(hdus)
        hdus[0].update_ext_name('FLUX',   'Extracted re-convolved flux')
        hdus[1].update_ext_name('IVAR',   'Inverse variance of extracted re-convolved flux')
        hdus[2].update_ext_name('LOGLAM', 'log10(wavelength) of extracted spectra')
        hdus[3].update_ext_name('R',      'Resolution matrix')
        hdus[4].update_ext_name('XFLUX',  'Extracted deconvolved spectra')
        hdus[5].update_ext_name('IXCOVAR', 'Inverse Covar of extracted deconvolved flux')
        hdus[6].update_ext_name('PIX',    'Reconstructed CCD image')

        #- Add spectra/flux ranges
        hdus[0].header.update('ISPECMIN', self.ispecmin, 'Index of first spectrum')
        hdus[0].header.update('IFLUXMIN', self.ifluxmin, 'Index of first flux bin')
        hdus[0].header.update('NSPEC', self.nspec, 'Number of spectra')
        hdus[0].header.update('NFLUX', self.nflux, 'Number of flux bins')

        hdus[6].header.update('CRPIX1', 1, 'Reference pixel (1..n)')
        hdus[6].header.update('CRPIX2', 1, 'Reference pixel (1..n)')
        hdus[6].header.update('CRVAL1', self.xmin, 'Coordinate of first X pixel')
        hdus[6].header.update('CRVAL2', self.ymin, 'Coordinate of first Y pixel')

        if comments is not None:
            for c in comments:
                hdus[0].header.add_comment(c)

        hdus.writeto(filename, clobber=clobber)

    @staticmethod
    def coadd(spectra):
        """
        Given a list of spectra on the same wavelength grid, coadd them
        and return a new Spectra object with the effective ivar,
        resolution matrices R, etc.

        TODO: Not yet implemented
        """
        raise NotImplementedError

    @staticmethod
    def load(filename):
        """
        Load Spectrum object from a fits file
        """

        fx = pyfits.open(filename)
        flux = fx[0].data.astype('=f8')  #- convert to native endian
        ivar = fx[1].data.astype('=f8')
        loglam = fx[2].data.astype('=f8')

        #- spectral/flux ranges
        ispecmin = fx[0].header['ISPECMIN']
        ifluxmin = fx[0].header['IFLUXMIN']
        nspec, nflux = flux.shape

        #- Resolution matrix
        full_range = (ifluxmin, ifluxmin+nflux)
        good_range = (ifluxmin, ifluxmin+nflux)
        R = fx[3].data.astype('=f8')
        if R is not None:
            R = ResolutionMatrix.from_diagonals(R, full_range=full_range, good_range=good_range)

        #- Optional, these may be blank
        xflux = fx[4].data.astype('=f8')
        pix = fx[6].data.astype('=f8')
        xmin = fx[6].header['CRVAL1']
        ymin = fx[6].header['CRVAL2']

        fx.close()
        s = Spectra(loglam=loglam, flux=flux, ivar=ivar, R=R, xflux=xflux,
                     ispecmin=ispecmin, ifluxmin=ifluxmin,
                     pix=pix, xmin=xmin, ymin=ymin)
        return s

    @staticmethod
    def blank(nspec, loglam, ispecmin=0, ifluxmin=0):
        """
        Create a blank spectra object

        nspec  : int, number of spectra
        loglam : 1D numpy array of log10(wavelengths) [nflux], or
                 2D numpy array of log10(wavelengths) [nspec, nflux]
        """
        if loglam.ndim == 1:
            nflux = loglam.size
            loglam = N.tile(loglam, nspec).reshape(nspec, nflux)
        else:
            n, nflux = loglam.shape
            assert n == nspec, 'loglam dimension mismatch %d != %d' % (n,nspec)

        flux = N.zeros((nspec, nflux))
        ivar = N.zeros((nspec, nflux))
        xflux = N.zeros((nspec, nflux))
        R = [None, ] * nspec

        return Spectra(flux, ivar, loglam, xflux = xflux, R=R,
                       ispecmin=ispecmin, ifluxmin=ifluxmin)

    @property
    def wavelength(self):
        return 10**self.loglam

    @property
    def w(self):
        return 10**self.loglam


from django import template
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q

from quiz.models import Question, QuizTries

register = template.Library()

@register.simple_tag(takes_context=True)
def radio_or_checkbox(context):
    question = context['question']

    if question.correct_number == 1:
        return "radio"
    return "checkbox"

@register.simple_tag(takes_context=True)
def tries_or_dash(context):
    quiz = context['quiz']
    student = context['student']

    try:
        return QuizTries.objects.get(quiz=quiz, student=student).tries
    except ObjectDoesNotExist:
        return "-"


#!/usr/bin/env python
# -*- coding:utf-8 -*-

import argparse

def parse_args():
    parser = argparse.ArgumentParser(usage='Identify related words in tmt based on the '
                                           '1. LCS between source and tms'
                                           '2. word alignment between tms and tmt')

    parser.add_argument('-s', '--src', required=True,
                        help='Path to the plain source file.')
    parser.add_argument('-tms', required=True)
    parser.add_argument('-tmt', required=True)
    parser.add_argument('--match-file', required=True,
                        help='Match file indicating the relationship between source and TMS.')
    parser.add_argument('-a', '--alignment', required=True,
                        help='Alignment file indicating the relationship between TMS and TMT.')
    parser.add_argument('-o', '--output', required=True)

    parser.add_argument('--source-tag', default='0',
                        help='DEFAULT: 0')
    parser.add_argument('--relate-tag', default='1',
                        help='DEFAULT: 1')
    parser.add_argument('--unrelate-tag', default='2',
                        help='DEFAULT: 2')
    parser.add_argument('--concat-tag', default=None,
                        help='DEFAULT: None. If set to None, will use the unrelate_tag.')

    args = parser.parse_args()

    return args

def find_longest_common_subsequences(seq_1, seq_2, sep=' '):
    # Ensure the smaller of the two sequences is used to create the columns for
    # the DP table.
    flag = 'col'
    if len(seq_1) < len(seq_2):
        new_seq_1 = seq_2
        seq_2 = seq_1
        seq_1 = new_seq_1
        flag = 'row'

    seq_1_len = len(seq_1)
    seq_2_len = len(seq_2)
    seq_1_len_plus_1 = seq_1_len + 1
    seq_2_len_plus_1 = seq_2_len + 1

    subseq_last_row = [''] * seq_2_len_plus_1
    subseq_current_row = [''] + [''] * seq_2_len

    for row in range(1, seq_1_len_plus_1):

        for col in range(1, seq_2_len_plus_1):

            if seq_1[row - 1] == seq_2[col - 1]:
                diagonal_cell_value = subseq_last_row[col - 1]
                # matched_element = seq_1[row-1]
                if flag == 'col':  # seq_2 corresponds to tms
                    rec = col - 1
                else:  # seq_1 corresponds to tms
                    rec = row - 1
                new_cell_value = f'{diagonal_cell_value}{sep}{rec}'
            else:
                above_set = subseq_last_row[col]
                left_set = subseq_current_row[col - 1]
                if len(above_set) >= len(left_set):
                    new_cell_value = above_set
                else:
                    new_cell_value = left_set
            subseq_current_row[col] = new_cell_value

        subseq_last_row = subseq_current_row
        subseq_current_row = [''] + [''] * seq_2_len

    return [int(i) for i in subseq_last_row[-1].split()]

def process_one_line(src_tokens, tms_tokens, tmt_tokens, aligns, opt):
    # find the LCS of src_line and tms_line
    # record the indices of LCS's tokens in tms_line
    lcs_indices = find_longest_common_subsequences(src_tokens, tms_tokens)

    # re-arrange the alignment information into a list of tuple and from the "target" perspective
    align_info = []
    for p in aligns:
        s_i, t_i = p.split('-')
        s_i, t_i = int(s_i), int(t_i)
        align_info.append((t_i, s_i))

    # iterate every possible pair of t-s alignment and filter out the indices of the related words
    # referring to paper: Boosting Neural Machine Translation with Similar Translations(ACL2020)
    set_pos = set([])
    set_neg = set([])

    for t in range(len(tmt_tokens)):
        neg_flag = True
        for s in range(len(tms_tokens)):
            if (t, s) in align_info and s in lcs_indices:
                set_pos.add(t)
            elif (t, s) in align_info and s not in lcs_indices:
                neg_flag = False
        if neg_flag:
            set_neg.add(t)

    final_set = set_pos.intersection(set_neg)

    # 1: T  2: R
    map_table = [opt.relate_tag if t in final_set else opt.unrelate_tag for t in range(len(tmt_tokens))]
    concat_tag = opt.concat_tag if opt.concat_tag is not None else opt.unrelate_tag
    map_table = [opt.source_tag] * len(src_tokens) + [concat_tag] + map_table

    return map_table

def main():
    opt = parse_args()

    print('Reading source lines...')
    with open(opt.src, 'r') as f:
        src_lines = [l.strip() for l in f]

    print('Reading TMS lines...')
    with open(opt.tms, 'r') as f:
        tms_lines = [l.strip() for l in f]

    print('Reading TMT lines...')
    with open(opt.tmt, 'r') as f:
        tmt_lines = [l.strip() for l in f]

    print('Reading match file lines...')
    with open(opt.match_file, 'r') as f:
        match_lines = [l.strip() for l in f]

    print('Reading alignment lines...')
    with open(opt.alignment, 'r') as f:
        align_lines = [l.strip() for l in f]

    assert len(src_lines) == len(match_lines), 'Every source line should and have to have one row of match ' \
                                               'information(if no match, then leave an empty row)'

    assert len(tms_lines) == len(tmt_lines)
    assert len(tms_lines) == len(align_lines), 'TMS and TMT alignment information should be integrated.'

    wf = open(opt.output, 'w')
    for i, src_line in enumerate(src_lines):
        match_line = match_lines[i]
        src_tokens = src_line.strip().split()
        # only one-best is supported now.
        if match_line.strip() != '':
            tm_i = int(match_line.strip().split('|||')[0].split()[0])
            tms_line = tms_lines[tm_i]
            tmt_line = tmt_lines[tm_i]
            align_line = align_lines[tm_i]

            tms_tokens = tms_line.strip().split()
            tmt_tokens = tmt_line.strip().split()
            aligns = align_line.strip().split()
            line_res = process_one_line(src_tokens, tms_tokens, tmt_tokens, aligns, opt)
        else:
            line_res = [opt.source_tag] * len(src_tokens)

        wf.write(' '.join([f'{i}' for i in line_res]) + '\n')

if __name__ == '__main__':
    main()


row = int(input())  # get number of row from user

for n in range(row):

    # [:-2] is to remove the ' ;' at the end of each string
    str = input()[:-2].split(' ')

    for x in str:
        print('*' * len(x))

    print('')  # print newline after each test case


from collections import Counter
import operator

class HighScoringWords:
    # the maximum number of items that can appear in the leaderboard
    MAX_LEADERBOARD_LENGTH = 100
    MIN_WORD_LENGTH = 3  # words must be at least this many characters long
    letter_values = {}
    valid_words = []

    def __init__(self, validwords='auticon/wordlist.txt', lettervalues='auticon/letterValues.txt'):
        """
        Initialise the class with complete set of valid words and letter values by parsing text files containing the data
        :param validwords: a text file containing the complete set of valid words, one word per line
        :param lettervalues: a text file containing the score for each letter in the format letter:score one per line
        :return:
        """
        with open(validwords) as f:
            self.valid_words = f.read().splitlines()

        with open(lettervalues) as f:
            for line in f:
                (key, val) = line.split(':')
                self.letter_values[str(key).strip().lower()] = int(val)

    def build_leaderboard_for_word_list(self):
        """
        Build a leaderboard of the top scoring MAX_LEADERBOAD_LENGTH words from the complete set of valid words.
        :return: The list of top words.
        """
        # list of top-scoring words
        top_words = []

        # while length of list is less than or equal to 100 words
        while len(top_words) <= self.MAX_LEADERBOARD_LENGTH:
            all_words = {}
            for word in self.valid_words:
                # intialize counter
                word_score = 0
                # QA print(word)
                # minimum word length
                if len(word) >=3:
                    for letter in word:
                        points = self.letter_values[letter]
                        word_score += points
                    # adding word and score to all_words dictionary
                    all_words[word] = word_score

            # sorting words by word score
            sorted_by_value = dict(
                sorted(all_words.items(), key=operator.itemgetter(1), reverse=True))
            # adding the high scoring words to the top_words list
            for key, value in sorted_by_value.items():
                top_words.append(key)

        return top_words

    def build_leaderboard_for_letters(self, starting_letters):
        """
        Build a leaderboard of the top scoring MAX_LEADERBOARD_LENGTH words that can be built using only the letters contained in the starting_letters String.
        The number of occurrences of a letter in the startingLetters String IS significant. If the starting letters are bulx, the word "bull" is NOT valid.
        There is only one l in the starting string but bull contains two l characters.
        Words are ordered in the leaderboard by their score (with the highest score first) and then alphabetically for words which have the same score.
        :param starting_letters: a random string of letters from which to build words that are valid against the contents of the wordlist.txt file
        :return: The list of top buildable words.
        """
        # initialize empty words list
        viable_words = []
        # creating a list of the letters from a given string
        letters = list(starting_letters)

        # ensure word list is within desired length
        while len(viable_words) <= self.MAX_LEADERBOARD_LENGTH:
            for word in self.valid_words:
                count = 1
                # create dictionary using Counter built-in library
                l_count = Counter(word)
                # QA print(l_count)
                # iterate through dictionary
                for key in l_count:
                    # only counting letters that are in the starting_letters list
                    if key not in letters:
                        count = 0
                    else:
                        # making sure to match the number of letters
                        if letters.count(key) != l_count[key]:
                            count = 0
                # add to list if count is correct
                if count == 1:
                    viable_words.append(word)

            return sorted(viable_words)

# w = HighScoringWords()
# w.build_leaderboard_for_word_list()
# w.build_leaderboard_for_letters('asdlkfjna')


import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
#importing libraries and data
dataset=pd.read_csv('Train.csv');
#print(dataset.head());
#print(dataset.shape);
#print(dataset.describe());
#print(dataset.isnull().any());

X = dataset[['feature_1', 'feature_2', 'feature_3', 'feature_4','feature_5']].values
Y = dataset['target'].values

#dividing our dataset into train dataset and test dataset as per 80 20 rule
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=0)

#training phase
regressor=LinearRegression()
regressor.fit(X,Y);
columns_dataset=np.array(['feature_1', 'feature_2', 'feature_3', 'feature_4','feature_5']);
weights=pd.DataFrame(regressor.coef_, index=columns_dataset, columns=['Coefficient'])
print(weights);

#testing phase

print("hwjehwjejwejhwjh");
y_hat=regressor.predict(X_test);
loss=pd.DataFrame({'Acutal':y_test,'predicted':y_hat});
print(loss);
top_five=loss.head();
top_five.plot(kind='bar',figsize=(10,8))
plt.show();


"""An implementation and demonstration of Bayesian Networks in Python.
"""

import cygraph as cg

class BayesianNetwork:
    """A bayesian network class capable of inneficient inference using
    the enumeration algorithm. Only capable of handling binary
    variables.
    """

    def __init__(self):
        self.graph = cg.graph(static=False, graph_=None, directed=True,
            vertices=[])

    def add_edge(self, A: str, B: str, conditional_probability: float):
        """Adds an edge to the network, representing the conditional
        proability between the two variables.

        Parameters
        ----------
        A: str
            The causing variable (parent).
        B: str
            The dependent variable (child).
        conditional_probability: float
            The probability that event A occurs given that event B
            occurs. P(A | B)
        """
        self.graph.add_edge(A, B, conditional_probability)

    def add_vertex(self, name: str, prior_probability: float):
        """Adds a vertex to the network, representing a new variable.

        Parameters
        ----------
        name: str
            The name of the variable.
        prior_probability: float
            The probability that the event represented by this variable
            will occur.
        """
        self.graph.add_vertex(name)
        self.graph.set_vertex_attribute(name, key="Prior Probability",
            val=prior_probability)

    def get_joint_probability(self, false_vars: list=[]) -> float:
        """Gets the joint probability of all the nodes in the network.

        Parameters
        ----------
        false_vars: list of str
            Variables that are treated as false instead of true (so that
            their prior probability is one minus what was inputted when
            they were added to the network.)

        Returns
        -------
        float
            The joint probability of all of the variables in the network
            being either true or false (depending on false_vars).
        """
        joint_probability = 1.0

        for variable in self.graph.vertices:
            variable_probability = 1.0

            false_var = variable in false_vars
            parents = self.graph.get_parents(variable)
            if parents:
                # Use conditional probability.
                for parent in parents:
                    conditional_probability = self.graph.get_edge_weight(
                        parent, variable)
                    variable_probability *= (
                        1 - conditional_probability if false_var
                        else conditional_probability)
            else:
                # Use prior probability.
                prior_probability = self.graph.get_vertex_attribute(
                    variable, "Prior Probability")
                variable_probability = (1 - prior_probability if false_var
                    else prior_probability)

            joint_probability *= variable_probability

        return joint_probability

    def marginalize_joint_probability(self, nuisance_variables: list) -> float:
        """Finds the joint probability of the network after summing out
        the nuisance variables.

        Parameters
        ----------
        nuisance_variables: list
            A list of variables to exclude from the joint probability
            using marginalization.

        Returns
        -------
        float
            The joint probability of the network after summing out each
            of the variables in `nuisance_variables`.
        """
        probability_sum = 0.0
        n_nuisance_variables = len(nuisance_variables)
        stack = [[]]
        while stack:
            var_states = stack.pop()
            if len(var_states) == n_nuisance_variables:
                # Base case: The code inside the final for-loop in the
                # nested for-loops of enumeration.
                probability_sum += self.get_joint_probability(
                    [var for var, state in zip(nuisance_variables, var_states)
                     if not state])
            else:
                for state in [True, False]:
                    stack.append(var_states + [state])

        return probability_sum

    def get_conditional_probability(self, A: str, B: str) -> float:
        """Calculates the conditional probability of a node being true given
        any other node.

        Parameters
        ----------
        A: str
            The causing variable (parent).
        B: str
            The dependent variable (child).

        Returns
        -------
        float
            The probability that event A occurs given that event B
            occurs. In mathematical notation, P(A | B)
        """
        # Calculate joint probability of distribution with only the
        # relevant variables.
        nuisance_variables = [var for var in self.graph.vertices
                              if var not in (A, B)]
        marginalized_joint_probability = \
            self.marginalize_joint_probability(nuisance_variables)

        return (marginalized_joint_probability
              / self.graph.get_vertex_attribute(B, "Prior Probability"))

if __name__ == '__main__':
    # Example from 3Blue1Brown video "Bayes theorem".
    bayesian_network = BayesianNetwork()
    # 1/21 chance Steve is a librarian.
    bayesian_network.add_vertex('L', 1 / 21)
    # 24 / 210 change Steve is shy.
    bayesian_network.add_vertex('S', 24 / 210)
    # 10% change Steve only wears white shirts.
    bayesian_network.add_vertex('W', 0.1)
    # 40% chance Steve is shy given that he is a librarian.
    bayesian_network.add_edge('L', 'S', 0.4)

    cond_prob_1 = bayesian_network.get_conditional_probability('L', 'S')
    print("The probability that Steve is a librarian given that he is shy: "
        f"{cond_prob_1}")


from __future__ import print_function
import sys, os, math
import numpy as np
from numpy import float32, int32, uint8, dtype
from PIL import Image
import glob

# Load PyGreentea
# Relative path to where PyGreentea resides
pygt_path = '../..'
sys.path.append(pygt_path)
import pygreentea.pygreentea as pygt
from pygreentea.pygreentea import malis

# Load the datasets - individual tiff files in a directory
raw_dir = '../../../project_data/dataset_01/train/raw'
label_dir = '../../../project_data/dataset_01/train/labels'

raw_path = sorted(glob.glob(raw_dir+'/*.tif'))
label_path = sorted(glob.glob(label_dir+'/*.png'))
num_images = len(raw_path)

raw_ds = [np.array(Image.open(raw_path[i]).convert('L'), 'f') for i in range(0, num_images)]
gt_ds = [np.array(Image.open(label_path[i]).convert('L'), 'f') for i in range(0,num_images)]
gt_ds_scaled = [np.floor(label/31) for label in gt_ds]

datasets = []
test_datasets = []
for i in range(0,1):
    dataset = {}
    dataset['data'] = np.expand_dims(pygt.normalize(np.asarray(raw_ds, float32)), 0)
    dataset['label'] = np.expand_dims(np.asarray(gt_ds_scaled, float32), 0)
    datasets += [dataset]

# Custom callback function to generate slices
def data_slice_callback(input_specs, batch_size, dataset_indexes, offsets, dataset_combined_sizes, data_arrays, slices):
    pass

def test_data_slice_callback(dataset_idx, offsets, datasets, slices):
    pass

# Set train options
class TrainOptions:
    loss_snapshot = 100
    test_interval = 4000
    train_device = 0
    test_device = 0
    test_net = None
    test_level = 0
    test_stages = None

options = TrainOptions()

# Set solver options
solver_config = pygt.caffe.SolverParameter()
solver_config.train_net = 'net.prototxt'
solver_config.base_lr = 0.00001
solver_config.momentum = 0.99
solver_config.weight_decay = 0.000005
solver_config.lr_policy = 'inv'
solver_config.gamma = 0.0001
solver_config.power = 0.75
solver_config.max_iter = 6000
solver_config.snapshot = 2000
solver_config.snapshot_prefix = 'net'
solver_config.type = 'Adam'
solver_config.display = 1

# Set devices
pygt.caffe.enumerate_devices(False)
pygt.caffe.set_devices((options.train_device,))

solverstates = pygt.get_solver_states(solver_config.snapshot_prefix)

# First training stage (softmax + euclid)
if (len(solverstates) == 0 or solverstates[-1][0] < solver_config.max_iter):
    solver, test_net = pygt.init_solver(solver_config, options)
    if (len(solverstates) > 0):
        solver.restore(solverstates[-1][1])
    pygt.train(solver, options, datasets, data_slice_callback,
               test_net, test_datasets, test_data_slice_callback)


from django.http import JsonResponse
from django.shortcuts import render, HttpResponse
from pacientes.models import Paciente
from personal.models import Doctores
from citas.models import Cita
from django.core import serializers
from pacientes.functpacientes import buscaPaciente

import json

# Create your views here.
def index(request):
    doctores = Doctores.objects.all()

    context = {
        'tmedicos': doctores,
    }
    return render(request, "citas/cita.html",context)

# http://www.lalicode.com/post/5/

def guardacitas(request):
    resp = ""

    paciente = Paciente()
    if request.method == "POST" and request.is_ajax():
        json_data = json.loads(request.body)

        pacid = buscaPaciente(json_data['nombre'],json_data['apellidos'],json_data["correo"])
        cita =Cita.objects.filter(id_paciente=pacid, fecha=json_data["fecha"]).count()
        doc = Doctores.objects.get(id=int(json_data['medico']))
        if cita>0:
            resp = "Ya existe una cita igual..."
        else:
            if pacid < 1:
                paciente.nombre = json_data['nombre']
                paciente.apellidos = json_data['apellidos']
                paciente.correo = json_data["correo"]
                paciente.celular = json_data['celular']
                paciente.estatus = "IP"  # paciente con información parcial cuando se atienda en la cita se hace el compelemento
                paciente.telefono = json_data['telefono']
                paciente.observaciones = json_data["motivo"]
                paciente.doctor=doc
                paciente.save()

            pacid = buscaPaciente(json_data['nombre'],json_data['apellidos'],json_data["correo"])
            cita = Cita()
            cita.nombre = json_data['nombre']
            cita.apellidos = json_data['apellidos']
            cita.telefono = json_data['telefono']
            cita.celular = json_data['celular']
            cita.correo = json_data["correo"]
            cita.fecha = json_data["fecha"]
            cita.hora = json_data["hora"]
            cita.motivo = json_data["motivo"]
            cita.id_paciente = Paciente.objects.get(id = pacid)
            cita.save()
            resp = "La cita ha sido Guardada..."

    else:
        resp = "Error al intentar guardar la cita "

    return JsonResponse({
        'respuesta': {
            'mensaje': resp,
        }
    })

def buscarcitas(request):
    return render(request, "citas/buscar.html")

def ajax_obtenDatosPacienteCitas(request):
    id = request.GET.get('id')
    if request.is_ajax():
        try:
            paciente = Paciente.objects.filter(id=id)
            data = serializers.serialize('json', paciente,
                                         fields=('nombre', 'apellidos', 'correo', 'telefono', 'celular'))
            return HttpResponse(data, content_type='application/json')
        except:
            return HttpResponse("Error al intentar recuperar datos")

def ajax_BuscaPacientes(request):
    busca = request.GET.get('empieza')
    if request.is_ajax():
        # print(busca)
        pacientes = Paciente.objects.filter(nombre__icontains=busca)
        paciente = []
        for p in pacientes:
            p_json = {}

            p_json['id'] = p.id
            p_json['nombre'] = p.nombre
            p_json['apellidos'] = p.apellidos
            paciente.append(p_json)
        # data_json = json.dumps(paciente)
    else:
        data_json = "Busqueda falló"
    mimetype = 'application/json'

    return JsonResponse({
        'respuesta': {
            'paciente': paciente
        }
    })


import socket
from tkinter import *
from tkinter.ttk import Progressbar
from multiprocessing import Queue
import threading
from queue import Empty
import time

#iniciando socket, variaveis global e listas de pareamento
UDP_IP = socket.gethostbyname(socket.gethostname())
UDP_PORT = 5000
ender = (UDP_IP,UDP_PORT)
running1=1
running2=0
addrList = []
ipList = []
q = Queue()
#sock.settimeout(None)
#caixa de mensagens
def mensagem_pareamento(ip, estado):
        win = Toplevel()
        win.geometry('200x200')
        message = str(ip)
        message = message+estado
        Label(win, text=message, fg='red',width=200).pack()
        Button(win, text='Fechar', command=win.destroy).pack(side=BOTTOM)

def pareamento(lista1,lista2):
            global running1#,sock
            running1 = 1
            ipList = lista1
            addrList = lista2

            if(running1):
                sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
                sock.bind(ender)
                q.put(sock)
                data, addr = sock.recvfrom(1024)
                #printando conexão (dados e endereço com portas)
                print ("Mensagem recebida:", data)
                print("Endereço: ",addr)
                ip = addr[0]

                if(ip in ipList):
                    mensagem_pareamento(ip,' Já foi pareado antes')
                    print('Foi pareado antes\n')

                else:
                    mensagem_pareamento(ip,' pareado')
                    sock.sendto(b"ok", addr)
                    print('Pareado')
                    ipList.append(ip)
                    addrList.append(addr)

                #printando listas de dispositivos pareados
                print('##listas##')
                print(ipList)
                print(addrList)

#janela do cronometro (classe)
class cronometro:
    def __init__(self, master):
        self.master = master
        # self.frame = Frame(self.master)
        self._start = 0.00
        self._tempo_gasto = 0.00
        self._running = 0
        self.timestr = StringVar()
        self.valor_a = ''
        self.master.geometry('500x250')
        self.desenhar_widgets()
        self.flag = 0

        #botões
        self.botao1 = Button(self.master,text='Start', command=self.Start, state=NORMAL)
        self.botao1.pack(side=LEFT)
        self.botao2 = Button(self.master, text='Parar', command=self.Stop, state=NORMAL)
        self.botao2.pack(side=LEFT)
        self.botao3 = Button(self.master, text='Resetar', command=self.Reset).pack(side=LEFT)
        self.botao4 = Button(self.master, text='Fechar', command=self.master.destroy).pack(side=LEFT)

    #métodos do cronômetro
    def desenhar_widgets(self):
        l = Label(self.master, textvariable=self.timestr,font=(None,35))
        self._setTime(self._tempo_gasto)
        l.pack(fill=X, expand=NO, pady=2, padx=2)

    def _update(self):
        self._tempo_gasto = time.time() - self._start
        self._setTime(self._tempo_gasto)
        self._timer = self.master.after(5, self._update)

    def _setTime(self, elap):
        minutos = int(elap/60)
        segundos = int(elap - minutos*60.0)
        msegundos = int((elap - minutos*60.0 - segundos)*1000)
        self.timestr.set('%02d:%02d:%03d' % (minutos, segundos, msegundos))

    def Start(self):
        global running2
        if not self._running:
            self.botao1.config(state=DISABLED)
            self.botao2.config(state=NORMAL)
            self._start = time.time() - self._tempo_gasto
            self._update()
            self._running = 1
            self.flag = 0
            running2 = 1
            self.t2 = threading.Thread(target=self.Rec_dados)
            self.t2.start()

    def Stop(self):
        if self._running:
            self.botao2.config(state=DISABLED)
            #self.botao2.config(state=NORMAL)
            self.master.after_cancel(self._timer)
            self._tempo_gasto = time.time() - self._start
            self._setTime(self._tempo_gasto)
            self._running = 0

    def Reset(self):
        self._start = time.time()
        self._tempo_gasto = 0.0
        self._setTime(self._tempo_gasto)

    def Rec_dados(self):
        global addrList,ipList#, sock
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        sock.bind(ender)
        #if(not self.flag):
        for j in addrList:
            sock.sendto(b"start", j)
        for i in ipList:
            data, addr = sock.recvfrom(1024)
            ip = addr[0]
            print (data)
            if(((data == b'ok') and (ip in ipList))is True):
                tempo_atual= self.timestr.get()
                l2 = Label(self.master, text=tempo_atual, font=(None,12)).pack(side=BOTTOM)
                print ("Mensagem recebida:", data)
                print("Endereço: ",addr)
            else:
                print('nao pareado ou mensagem incorreta')

        self.botao1.config(state=NORMAL)
        self.master.after_cancel(self._timer)
        self._tempo_gasto = time.time() - self._start
        self._setTime(self._tempo_gasto)
        self._running = 0
        sock.close()
#aplicação de GUI
class Application:
    def __init__(self, master):
        self.master = master

        #frames da tela
        self.bottomFrame = Frame()
        self.bottomFrame.pack(side=BOTTOM)

        #tamanho da tela
        master.geometry('500x250')

        #botões
        self.buttom2 = Button(self.bottomFrame,fg='red',text='parar servidor', command=self.parar)
        self.buttom2.pack()
        self.teste = Button(self.bottomFrame,text='Cronometro', command=self.abrir_janela).pack(side=LEFT)
        self.buttom1 = Button(self.bottomFrame,fg='blue',text='Parear', command=self.chamar_pareamento)
        self.buttom1.pack()
        #queue variable e barra de progresso
        self.pbar = Progressbar(mode='indeterminate')
        self.pbar.pack(side=BOTTOM)

        #labels
        self.label1 = Label(text ='SpeedRun',font=(None,40))
        self.label1.pack(side=TOP)

    #métodos da classe de aplicação
    def parar(self):
        print("Setado para falso")
        global running1
        running1 = 0

    def onGetValue(self):
        global running1
        if(self.t1.is_alive()):
            print("Esperando conexão")
            self.master.after(100, self.onGetValue)
            self.buttom1.config(state=DISABLED)

        else:
            try:
                print('FIM', q.get(0))
                self.buttom1.config(state=NORMAL)
                self.pbar.stop()

            except Empty:
                print("queue está vazia")

    def chamar_pareamento(self):
        self.t1 = threading.Thread(target=pareamento,args=(ipList, addrList))
        self.t1.daemon = True
        self.t1.start()
        self.pbar.start(20)
        self.master.after(100, self.onGetValue)

    def abrir_janela(self):
        self.janela = Toplevel(self.master)
        self.nova_janela = cronometro(self.janela)

#iniciando a aplicação e rodando o loop
if __name__ == '__main__':
    root = Tk()
    app = Application(root)
    root.mainloop()


# _*_coding:utf-8_*_
# Name:Brian
# Create_time:2021/2/3 13:47
# file: utils2.py
# location:chengdu
# number:610000
import os
import logging
import time
from metrics import *
import matplotlib.pyplot as plt

def get_logger(root, name=None, debug=True):
    time_lag = time.time()
    # when debug is true, show DEBUG and INFO in screen
    # when debug is false, show DEBUG in file and info in both screen&file
    # INFO will always be in screen
    # create a logger
    logger = logging.getLogger(name)
    # critical > error > warning > info > debug > notset
    logger.setLevel(logging.DEBUG)

    # define the formate
    formatter = logging.Formatter('%(asctime)s: %(message)s', "%Y-%m-%d %H:%M:%S")
    # create another handler for output log to console
    console_handler = logging.StreamHandler()
    if debug:
        console_handler.setLevel(logging.DEBUG)
    else:
        console_handler.setLevel(logging.INFO)
        # create a handler for write log to file
        logfile = os.path.join(root, 'run_%s.log' % time_lag)
        print('Creat Log File in: ', logfile)
        file_handler = logging.FileHandler(logfile, mode='w')
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    # add Handler to logger
    logger.addHandler(console_handler)
    if not debug:
        logger.addHandler(file_handler)
    return logger

def train_epoch(train_loader, adj_mx, net, optimizer, epoch, logger, loss_criterion, device="cuda", log_step=10):
    """
    Trains one epoch with the given data.
    :param training_input: Training inputs of shape (num_samples, num_nodes,
    num_timesteps_train, num_features).
    :param training_target: Training targets of shape (num_samples, num_nodes,
    num_timesteps_predict).
    :param batch_size: Batch size to use during training.
    :return: Average loss for this epoch.
    """
    epoch_training_losses = []
    for batch_idx, (X_data, y_batch) in enumerate(train_loader):
        net.cuda()
        net.train()
        optimizer.zero_grad()
        y_batch = y_batch.to(device)
        X_batch = X_data[:, 0:1, :, :].permute(2, 0, 3, 1).to(device)  # T B  N C z
        mask_missing = X_data[:, 1:2, :, :].permute(2, 0, 3, 1).to(device)
        out = net(X_batch, adj_mx, mask_missing)
        del X_batch
        loss = loss_criterion(out, y_batch)
        # loss = loss_criterion(out, y_batch.to(device))
        loss.backward()
        optimizer.step()
        del out
        del y_batch
        if batch_idx % log_step == 0:
            logger.info('Train Epoch {}: {}/{} Loss: {:.6f}'.format(
                epoch, batch_idx, len(train_loader), loss.item()))
        epoch_training_losses.append(loss.detach().cpu().numpy())
    train_epoch_loss = sum(epoch_training_losses) / len(epoch_training_losses)
    logger.info('**********Train Epoch {}: averaged Loss: {:.6f}'.format(epoch, train_epoch_loss))
    del train_loader
    return train_epoch_loss

def val_epoch(val_loader, net, adj_mx, epoch, logger, loss_criterion, device="cuda", log_step=20):
    epoch_val_losses = []
    with torch.no_grad():
        for batch_idx, (X_data, y_batch) in enumerate(val_loader):
            y_batch = y_batch.to(device)
            X_batch = X_data[:, 0:1, :, :].permute(2, 0, 3, 1).to(device)  # T B  N C z
            mask_missing = X_data[:, 1:2, :, :].permute(2, 0, 3, 1).to(device)
            out = net(X_batch, adj_mx, mask_missing)
            # y_batch=y_batch.to(device)
            val_loss = loss_criterion(out, y_batch)
            del y_batch
            del out
            if batch_idx % log_step == 0:
                logger.info('val Epoch {}: {}/{} Loss: {:.6f}'.format(
                    epoch, batch_idx, len(val_loader), val_loss.item()))
            epoch_val_losses.append(val_loss.detach().cpu().numpy())
        train_epoch_loss = sum(epoch_val_losses) / len(epoch_val_losses)
        logger.info('**********val Epoch {}: averaged Loss: {:.6f}'.format(epoch, train_epoch_loss))
        del val_loader
        return train_epoch_loss

def test_all(adj_mx, test_loader, model, max_speed, logger, epochs, device="cuda"):
    model.to(device)
    model.eval()
    mae_list = []
    mape_list = []
    rmse_list = []
    with torch.no_grad():
        for batch_idx, (X_data, y_batch) in enumerate(test_loader):
            y_batch = y_batch.to(device)
            y_batch = y_batch * max_speed
            mask_missing = X_data[:, 1:2, :, :].permute(2, 0, 3, 1).to(device)
            X_batch = X_data[:, 0:1, :, :].permute(2, 0, 3, 1).to(device)  # T B  N C z
            output = model(X_batch, adj_mx, mask_missing) * max_speed

            # target_unnormalized = y_batch.detach().cpu().numpy()
            mae, rmse, mape, _, _ = All_Metrics(output, y_batch, None, 0.)
            logger.info("test_eopch_old:{}/{}:, MAE: {:.2f}, RMSE: {:.2f}, MAPE: {:.2f}%".format(
                batch_idx, len(test_loader), mae, rmse, mape * 100))

            mape_list.append(mape)
            mae_list.append(mae)
            rmse_list.append(rmse)
            # logger.info("test_eopch_all index:{}/{}, MAE: {:.2f}, RMSE: {:.2f}, MAPE: {:.2f}%".format(
            #     batch_idx, len(test_loader), mae, rmse, mape * 100))
        fig = plt.figure()
        ax1 = fig.add_subplot(111)
        plt.plot(mae_list, "b", label="mae_list")
        plt.plot(rmse_list, "g", label="rmse_list")
        ax1.set_ylabel('MSE and RMSE values')
        ax1.set_title("Result of test epochs-> %s " % epochs)
        ax1.set_ylim(0, 20)
        ax2 = ax1.twinx()  # this is the important function
        plt.plot(mape_list, "r", label="MAPE")
        ax2.set_ylabel('MAPE values')
        ax2.set_ylim(0, 0.25)
        ax1.legend()
        ax2.legend()
        plt.show()
        mae_ave = sum(mae_list) / len(mae_list)
        mape_ave = sum(mape_list) / len(mape_list)
        rmse_ave = sum(rmse_list) / len(rmse_list)
        logger.info("test_eopch average： MAE: {:.2f}, RMSE: {:.2f}, MAPE: {:.4f}%".format(
            mae_ave, rmse_ave, mape_ave * 100))


def maximize_value(weights, values, volume):
    items = [0] * (volume + 1)
    max_value = [0] * (volume + 1)
    for i in range(volume + 1):
        maximum = 0
        for j in [c for c in weights if c <= i]:
            if maximum < max_value[i - j] + values[weights.index(j)]:
                maximum = max_value[i - j] + values[weights.index(j)]
                items[i] = j
        max_value[i] = maximum
    return max_value, items

def print_items(items):
    item_list = []
    current_weight = len(items) - 1
    while current_weight > 0:
        item_list.append(items[current_weight])
        current_weight -= items[current_weight]
    return item_list

maximum_20 = maximize_value([2, 3, 4, 5, 9], [3, 4, 8, 8, 10], 20)
print('Max value: {}; items are as follows: {}'.format(maximum_20[0][20], print_items(maximum_20[1])))


for x in [1, 2, 3]:
    print(x)

D = {'a': 1, 'c': 2, 'b': 3}
for key in D:
    print('{}--->{}'.format(key, D[key]))

D = {'a': 1, 'c': 2, 'b': 3}
for key, value in D.items():
    print('{}--->{}'.format(key, value))


""""
Crie um programa que calcule o Imposot de Renda pela faixa salarial, sabendo que os salários até
R$ 1.000 reais não pagam Imposto, ou seja, 0 % de aliquota. Salários entre R$ 1.000 e R$ 3.000
pagam Imposto de 20 % de aliquota e os salários acima de R$ 3.000, pagam  35 % de aliquota.
"""

salario = float(input("Digite seu salário: "))

if salario < 1000:
    imposto = 0
    valor = (salario * imposto)
elif salario >=1000 and salario <= 3000:
    imposto = 0.20
    valor = (salario * imposto)
else:
    imposto = 0.35
    valor = (salario * imposto)

total = salario - valor

print("O salário de R$ %.2f, terá um desconto de imposto de %.2f e o valor líquido: R$ %.2f" % (salario, valor, total))


from setuptools import setup, find_packages
import requests
import os
from ppickle import dump, load
package_info_filename = "package_info.ppickle"
package_info = load(package_info_filename)
USERNAME = package_info["USERNAME"]
REPONAME = package_info["REPONAME"] or os.path.split(os.path.dirname(os.path.abspath(__file__)))[-1]
GITHUB_API_URL = package_info["GITHUB_API_URL"] or f"https://api.github.com/repos/{USERNAME}/{REPONAME}"
URL = package_info["URL"] or f'https://github.com/{USERNAME}/{REPONAME}'
AUTHOR_EMAIL = package_info["AUTHOR_EMAIL"] or f'{USERNAME}@users.noreply.github.com'
README_PATH = package_info["README_PATH"] or 'README.md'
requirements = [
    "requests",
]

def get_description():
    description = requests.get(GITHUB_API_URL).json()['description']
    return description

def get_topic():
    topics = requests.get(GITHUB_API_URL + "/topics", headers={
        "Accept": "application/vnd.github.mercy-preview+json", }).json()['names']
    return ' '.join(topics)

def increment_version():
    raw_version = package_info['version'] or '0.0.0'
    int_version = int(raw_version.replace('.', ''))  # 3
    int_version += 1
    new_version = '.'.join(str(int_version).zfill(3))  # 0.0.4
    package_info['version'] = new_version
    dump(package_info_filename, package_info)
    with open('version.txt', 'w') as f:
        f.write(new_version)
    return new_version

def get_long_description():
    with open(README_PATH, 'r', encoding='utf-8') as f:
        long_description = f.read()

description = get_description()
keywords = get_topic()
version = increment_version()
long_description = get_long_description()
setup(
    name=REPONAME,
    version=version,
    description=description,
    long_description=long_description,
    long_description_content_type='text/markdown',
    url=URL,
    author=USERNAME,
    author_email=AUTHOR_EMAIL,
    license='MIT',
    keywords=keywords,
    packages=find_packages(),
    install_requires=requirements,
    classifiers=[
        'Programming Language :: Python :: 3.6',
    ],
)


# 그리디 알고리즘 - 회의실 배정

# 내가 작성한 코드
N = int(input())
arr = [tuple(map(int, input().split())) for _ in range(N)]
arr = sorted(arr, key=lambda x: x[1]) # 끝나는 시간에 맞춰서 오름차순 정렬

k = 0
cnt = 1
for j in range(1, N):
    if arr[k][1] <= arr[j][0]:
        cnt += 1
        k = j

print(cnt)

# 강의 코드
n = int(input())
meeting = []
for i in range(n):
    s, e = map(int, input().split())
    meeting.append((s, e)) # 튜플 형태로 리스트에 데이터를 입력
meeting.sort(key=lambda x: (x[1], x[0]))
et = 0 # 끝나는 시간 기록
cnt = 0
for s, e in meeting:
    if s >= et:
        et = e
        cnt += 1
print(cnt)


from tkinter import *
import tkinter.ttk as ttk
import tkinter.messagebox as tkMessageBox

root = Tk()
root.title("Contact List")
width = 700
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width/2) - (width/2)
y = (screen_height/2) - (height/2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)
root.config(bg="#f0f0f0")

lbl_title = ttk.Label(root, text="Contact Management System")
lbl_title.config(font=('helvetica', 20))
lbl_title.pack()

#buttons
'''b = Button(root, text ="Hello")
b.pack(fill =BOTH, expand =1)'''

def addInfo():
   tkMessageBox.showinfo("Add Info", "")

B1 = ttk.Button(root, text ="Add Info", command = addInfo)
B1.pack(side =TOP)

def updateInfo():
   tkMessageBox.showinfo("Update Info", "")

B2 = ttk.Button( text ="Update Info", command = updateInfo)
B2.pack(side =TOP)

def deleteInfo():
    tkMessageBox.showinfo("Delete Info")

B3 = ttk.Button(text ="Delete Info", command = deleteInfo)
B3.pack(side =TOP)

lbl_table = ttk.Label(root, text="Contact List", font=('arial', 16))
lbl_table.pack()

lbl_fname = ttk.Label(root, text ="First name")
lbl_fname.pack(padx =1,pady =1, side =LEFT)

lbl_lname = ttk.Label(root, text ="Last name")
lbl_lname.pack(padx=2, pady=5, side=LEFT)

lbl_gender = ttk.Label(root, text ="Gender")
lbl_gender.pack(padx=1, pady=10, side=LEFT)

lbl_contact = ttk.Label(root, text ="Contact")
lbl_contact.pack(padx=1, pady=15, side=LEFT)

lbl_address =ttk.Label(root, text ="Address")
lbl_address.pack(padx=1, pady=20, side=LEFT)

#w.pack(padx=5, pady=10, side=tk.LEFT)

root.mainloop()


'''
Created on Jan 17, 2021

@author: kulkarnivasanti
'''

set1 = {'arti','bharti','keerti','murti','spoorti','arundhati'}
set2 = {'amarsh','bhavesh','ramesh','satish','umesh'}
set3 = {}
for x in set1:
    if "a" in x:
        set3.append(x)
print(set3)


import logging
import locale

from can.web.orm import db

_CHUNK_SIZE = 10000

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
locale.setlocale(locale.LC_ALL, 'en_US')

def bulk_insert(mapper, mapping, chunk_size=_CHUNK_SIZE):
    if db:
        for i in xrange(0, len(mapping), chunk_size):
            batch = mapping[i:i + chunk_size]
            db.bulk_insert_mappings(mapper, batch)
            db.flush()
            total = locale.format("%d", i + len(batch), grouping=True)
            log.info("inserted {0} {1} records".format(total, mapper.__name__))


from tkinter import *
from perfWuxian import PerfilWu
from perfXi import Perfilxi

class Perf(Toplevel):
    #cores
    cor_azul_esc = '#1d3557'
    cor_azul = '#00b4d8'
    cor_azul2 = '#48cae4'
    cor_azul_clar = '#caf0f8'
    cor_white = '#edf6f9'
    cor_fundo = '#b6e0f8'

    def __init__(self, original):
        self.frame_original = original

        Toplevel.__init__(self)
        self.geometry('375x680+979+15')
        self.title('Perfil')
        self.configure(bg='#dbe2ec')
        self.iconbitmap('cloud.ico')

        #configuração do botão de voltar do perfil
        self.btn = Button(
            self,
            text='Voltar',
            bg=self.cor_azul_esc,
            activebackground=self.cor_azul,
            font=('Please write me a song', 14, 'bold'),
            fg=self.cor_white,
            activeforeground=self.cor_azul,
            command=self.onClose)

#555555555555555555555 Botão 5555555555555555555555

        self.btn.pack()
        self.btn.place(
            relx=0.0,
            rely=0.95,
            relwidth=0.20,
            relheight=0.05)

        self.btn = Button(
            self,
            text='Wei Wuxian',
            bg=self.cor_azul,
            activebackground=self.cor_azul,
            font=('Please write me a song', 12, 'bold'),
            fg=self.cor_white,
            activeforeground=self.cor_azul,
            command=self.clica_entrar4)

        self.btn.pack()
        self.btn.place(
            relx=0.80,
            rely=0.95,
            relwidth=0.20,
            relheight=0.05)

        self.btn = Button(
            self,
            text='Lan Xichen',
            bg=self.cor_azul,
            activebackground=self.cor_azul,
            font=('Please write me a song', 12, 'bold'),
            fg=self.cor_white,
            activeforeground=self.cor_azul,
            command=self.clica_entrar5)

        self.btn.pack()
        self.btn.place(
            relx=0.60,
            rely=0.95,
            relwidth=0.20,
            relheight=0.05)

#88888888888888888888888 Frames 888888888888888888888888888888888888888888888888

        self.frame = Frame(self, bg=self.cor_azul)
        self.frame.place(relx=0.05, rely=0.03, relwidth=0.36, relheight=0.19)

        self.frame2 = Frame(self, bg=self.cor_azul_clar)
        self.frame2.place(relx=0.43, rely=0.03, relwidth=0.52, relheight=0.19)

        self.frame3 = Frame(self, bg=self.cor_azul)
        self.frame3.place(relx=0.05, rely=0.23, relwidth=0.90, relheight=0.46)

        self.frame4 = Frame(self, bg=self.cor_azul_esc)
        self.frame4.place(relx=0.05, rely=0.70, relwidth=0.90, relheight=0.23)

#999999999999999999999999999 Imagem 999999999999999999999999999999999999999999999

        self.modelo = PhotoImage(file='wangji.png')
        self.img1 = Label(
            self.frame,
            image=self.modelo,
            bd=0
        )
        self.img1.place(
            relx=0.0,
            rely=0.0)

        self.modelo2 = PhotoImage(file='xichen.png')
        self.img2 = Label(
            self.frame4,
            image=self.modelo2,
            bd=0
        )
        self.img2.place(
            relx=0.05,
            rely=0.0)

        self.modelo3 = PhotoImage(file='wuxian.png')
        self.img3 = Label(
            self.frame4,
            image=self.modelo3,
            bd=0
        )
        self.img3.place(
            relx=0.5,
            rely=0.0)

#6666666666666666666666666666666 informacões da imagem 66666666666666666666666666666666666666666666666666666666666666666

        self.nomeirm = Label(
            self.frame4,
            text='Irmão: Lan Xichen',
            font=('Consolas', 10),
            bg=self.cor_azul_esc,
            fg=self.cor_white
        )
        self.nomeirm.place(relx=0.08, rely=0.86)

        self.nomenam = Label(
            self.frame4,
            text='Namorado: Wei Wuxian',
            font=('Consolas', 10),
            bg=self.cor_azul_esc,
            fg=self.cor_white
        )
        self.nomenam.place(relx=0.50, rely=0.86)

#9999999999999999999999999999999 Informações do Lan Wangji que fica do lado da foto 999999999999999999999999999999999999

        self.nome = Label(
            self.frame2,
            text='Nome de nascimento:\nLan Zhan\nN. de cortesia:\nLan Wangji\nTítulo: HanGuang-Jun\nClã: Lan\nSeita: Gusulan\nAniversário: 23/01',
            font=('Consolas', 10),
            bg=self.cor_azul_clar,
            fg='#000000',
        )
        self.nome.place(relx=0.1, rely=0.0)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~ texto abaixo da foto ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        self.nome = Label(
            self.frame3,
            text='Espada: Bichen (significa "evitar a poeira/\nassuntos mundanos").\nOutras ferramentas: Uma guqin chamada "Wangji".\n• Info. adicional: Como Segundo Jovem Mestre\n da familia Lan, possui a excelente \nreputação dheroico cultivador por "estar aonde\n quer que o caos esteja".',
            font=('Consolas', 10),
            bg=self.cor_azul,
            fg=self.cor_white
        )
        self.nome.place(relx=0.0, rely=0.0)

        self.nome = Label(
            self.frame3,
            text ='Classificado em segundo lugar na lista\n dos cinco melhores cultivadores de sua\n geração, nem mesmo os olhares complacentes\n poderiam evitar que sua amarga expressão\n facial o faça parecer',
            font=('Consolas', 10),
            bg=self.cor_azul,
            fg=self.cor_white
        )
        self.nome.place(relx=0.0, rely=0.4)
        self.nome = Label(
            self.frame3,
            text ='como se tivesse acabado de perder sua esposa.\nJuntamente com seu irmão mais velho, Lan Xichen,\nsão chamados de "As Duas Jades de Lan".',
            font = ('Consolas', 10),
            bg=self.cor_azul,
            fg=self.cor_white
        )
        self.nome.place(relx=0.0, rely=0.7)

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    def onClose(self):
        self.destroy()
        self.frame_original.show()
    def clica_entrar4(self):
        self.subFrame = PerfilWu(self)
    def clica_entrar5(self):
        self.subFrame = Perfilxi(self)


from http.server import BaseHTTPRequestHandler
from io import BytesIO

class HttpParse(BaseHTTPRequestHandler):
    """
    """
    def __init__(self, request):
        self.rfile = BytesIO(request)
        self.raw_requestline = self.rfile.readline()
        self.error_code = None
        self.error_message = None
        self.parse_request()

    def send_error(self, code, message):
        self.error_code = code
        self.error_message = message

req = b'GET /Foobar HTTP/1.1\r\nHost: localhost:8888\r\nConnection: keep-alive\r\nCache-Control: max-age=0\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nUser-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36\r\nAccept-Encoding: gzip, deflate, sdch\r\nAccept-Language: en-US,en;q=0.8\r\nCookie: splunkweb_csrf_token_9090=7895092559780224874; splunkweb_csrf_token_9000=15323466259499609533\r\n\r\n'
hp = HttpParse(req)
for item in dir(hp):
    print('{}: {}'.format(item, getattr(hp, item)))


#!/usr/bin/env python

# Italy EPG is a script that will communicate with remote EPG provider
# and  parse through all the channels and format into XML so that it can be used
# in xTeve or Plex

from bs4 import BeautifulSoup   ### html parsing
import re                       ### text manipulation
import requests                 ### for making json requests
import json                     ### for json formatting and manipulation
import datetime as dt           ### to format the dates and times properly into xml file
import time                     ### for the sleeps

print("Starting EPG script...")

### Define variables

print("Setting variables...")
network_url = "https://remote_epg_url/"
network_image_url = "https://remote_image_url"
italy_channels = [ 'channel1', 'channel2', 'channel3' ] ### define channels
local_image_url = "http://local.url/italy/"

#######################################################################
### writexmlchannel - write channel headers to xml file
#######################################################################

def writexmlchannel(write_channel):

    f.write('    <channel id="{}">\n'.format(write_channel))
    f.write('      <display-name>{}</display-name>\n'.format(write_channel))
    f.write('      <icon src="{}{}" />\n'.format(local_image_url,write_channel))  ### channel icon located on local server
    f.write('    </channel>\n')

###############################################################################################################################
### writexmlprogramme - writes the input data into xml format into the xml epgtv file
##############################################################################################################################

def writexmlprogramme(requested_channel,iso_start_date,iso_end_date,title,stitle,desc,imagelink,ns_epnum,air_date):

    f.write('    <programme channel="{}" start="{}" stop="{}">\n'.format(requested_channel,iso_start_date,iso_end_date))
    f.write('      <title lang="it">{}</title>\n'.format(title))
    f.write('      <sub-title lang="it">{}</sub-title>\n'.format(stitle))
    if desc:
      f.write('      <desc lang="it">{}</desc>\n'.format(desc))
    if imagelink:
      f.write('      <icon src="{}"/>\n'.format(imagelink))
    if ns_epnum:
      f.write('      <episode-num system="xmltv_ns">{}</episode-num>\n'.format(ns_epnum))
    if air_date:
      f.write('      <episode-num system="original-air-date">{}</episode-num>\n'.format(air_date))
    f.write('    </programme>\n')

##########################################################################################
### dateincrementer - increment date and put into format required for xmltv
##########################################################################################

def dateincrementer(date_increment_requested):

    today = dt.datetime.now()
    today_format = today.strftime('%d-%m-%Y')
    #print("today is: ",today_format)
    date_increment = dt.datetime.now() + dt.timedelta(days=date_increment_requested)
    date_increment_format = date_increment.strftime('%d-%m-%Y')
    #print("Incremented by: {} Day is: {}".format(date_increment_requested,date_increment_format))
    return date_increment_format

#############################################################################################
### Main Loop
#############################################################################################

eventcount = 0  ### Reset counter

### Write XML Header at top of xml epgtv file
print("Opening/creating xml file...")
f = open("italy_epg.xmltv","w")
print("Writing XML header")
f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
f.write('  <tv source-info-url="" generator-info-name="Italy EPG Generator : on {}" source-info-name="Big Vs generator">\n'.format(dt.datetime.now()))

### write all the channel headers
print("Writing channel headers")
for channel in italy_channels:
  writexmlchannel(channel)

### Main program loop

print("Starting main programme parser")
for i in range(6):

  epg_date_requested = dateincrementer(i)
  print("Requested EPG date is: ",epg_date_requested)
  request_date = str(epg_date_requested)

  for channel in italy_channels:

    time.sleep(5)
    request_url = "{}{}/{}.json".format(network_url,channel,request_date)
    request_epg = requests.get(request_url)                                                                ### Grab the json data from provider
    reqjson = json.loads(request_epg.text)                                                                      ### Put json data into variable/json list
    events = reqjson['events']                     ### events are the tv programmes

    for event in events:                           ### parse individual programmes

      eventcount = eventcount + 1                  ### reset counters
      info_grab_errors = 0

      ### Grab program name
      namegrab = event['program']
      namegrab = namegrab['name']
      if namegrab:  ### if program name exists
        namegrab = re.sub(r'&',r'and',namegrab)
        title=namegrab
      else:
        title=""                               ### no program name provided

      episode = event['episode_title']
      if episode:
        episode = re.sub(r'&',r'and',episode)
        stitle=episode
      else:
        stitle=""

      startdate = event['date']
      if not startdate:
        info_grab_errors = info_grab_errors + 1     ### error out if no start time exists

      starttime = event['hour']
      if not starttime:
        info_grab_errors = info_grab_errors + 1      ### error if no start hour exists
      duration = event['duration']
      if not duration:
        info_grab_errors = info_grab_errors + 1      ### error if no duration exists

      ### Calculate start time ######################################

      mytime = dt.datetime.strptime(starttime,'%H:%M').time() # Convert time string to time object
      mydate = dt.datetime.strptime(startdate,'%d/%m/%Y') #convert date string to date object
      combinedstarttime = dt.datetime.combine(mydate,mytime) #combine date and time together

      timezone="+0200" ###Italy Time Zone
      isodt=combinedstarttime.strftime('%Y%m%d%H%M%S') ### Convert date string to ISO for XMLTV

      ### Convert datetime object to string to paste into XMLTV file
      strdate=str(isodt) #Convert back to string and add timezone
      iso_start_time=strdate+" "+ timezone

      ### Figure out end time #########################################

      duration_time = dt.datetime.strptime(duration,'%H:%M:%S').time() #Convert duration time string to time object

      duration_add_hour = int(duration_time.strftime('%H')) #Strip out Hour and convert to int to use with timedelta
      duration_add_minutes = int(duration_time.strftime('%M'))

      duration_add = combinedstarttime + dt.timedelta(hours=duration_add_hour)
      duration_add = duration_add + dt.timedelta(minutes=duration_add_minutes)

      iso_end_time=duration_add.strftime('%Y%m%d%H%M%S')
      iso_end_time=str(iso_end_time)
      iso_end_time=iso_end_time+" "+timezone   ### Final end time, formatted to ISO and in proper time zone

      ################################
      ### Parse program description
      ################################

      description = str(event['description'])
      if description:
        description = re.sub(r'&',r'and',description)
      else:
        pass      ### No description provided

      sforcheck = False
      episodeforcheck = False

      ### Parse episode number

      episodenumber = event['episode']
      if episodenumber:
        if str.isdecimal(episodenumber):
          ns_episode = int(episodenumber)
          ns_episode = ns_episode - 1
          episodeforcheck = True

      ### Parse season number

      season = event['season']
      if season:
        if str.isdecimal(season):
            sforcheck = True
            ns_season = int(season)
            ns_season = ns_season - 1

      ns_epnum = ""
      air_date = ""

      if sforcheck == True and episodeforcheck == True:

        ns_epnum = "{}.{}.".format(ns_season,ns_episode)

      elif "Puntata del" in stitle:  ### If exists an original air date, use that for season or episode number

        punt = re.sub(r' ','',stitle)
        punt = re.sub(r'Puntatadel','',punt)

        puntsearch = re.search('[0-9]{2}/[0-9]{2}/[0-9]{4}',punt)

        if puntsearch is not None:  ### Found an air date, start to parse
          punt = puntsearch.group()

          punt_date = dt.datetime.strptime(punt,'%d/%m/%Y')
          comb_punt_time = dt.datetime.combine(punt_date,mytime)
          comb_fpunt_time = comb_punt_time.strftime('%Y-%m-%d %H:%M')
          air_date = comb_fpunt_time
        else:
          air_date = ""

      else:
        pass        ### No series or episode information provided

      ### Check for a show thumbnail

      image = event['image']
      if image:
          imagelink = str(network_image_url+image)
      else:
          imagelink = ""

      requested_channel = channel ### Use already provided channel number/name

      ### If there were no errors above, proceed to write data to XML file

      if info_grab_errors == 0:
        writexmlprogramme(requested_channel,iso_start_time,iso_end_time,title,stitle,description,imagelink,ns_epnum,air_date)
      else:
        pass ### Errors parsing program
        #print("Failed to find critical information, not writing to xml") ### Program found errors, not writing program to xml

      ### Finished writing programme

#############################################
### Finished writing channels and programs
#############################################
print("Finished parsing. Programmes added: ",eventcount)          ### Give number of found programs

### Close the output xml file

f.write('  </tv>\n')
f.close()

### Push Results via MQTT ###

network = "Italy"

### If using MQTT, uncomment the below 2 lines

### from pushresults import PushResultsMqtt
###PushResultsMqtt(network,eventcount)

### If using xTeve, Force XTeve to update M3U file, which is pointed at localhost, otherwise comment out below lines
apiurl="http://xteve.lan:34400/api/"
headers = {'Content-type': 'application/json'}

print("Pushing JSON POST update to XTeve")
r = requests.post(apiurl, json={"cmd": "login"}, headers=headers)
t = requests.post(apiurl, json={"cmd": "update.xmltv"}, headers=headers)
datares=json.loads(t.text)

if datares['status'] == True:
     print("POST Successful")

### Done


"""
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,

a^2 + b^2 = c^2
For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""

numbers = []  # for numbers which a+b+c=1000 and pythagorean

def pyth():
    global numbers
    for a in range(1, 333):
        b = a + 1
        c = 1000 - (a + b)
        while b < c:
            if pow(a, 2) + pow(b, 2) == pow(c, 2):
                numbers.append(a)
                numbers.append(b)
                numbers.append(c)
            b += 1
            c -= 1

pyth()

result = 1
for n in numbers:
    result *= n

print(result)


print('Welcome To The SplitSmart App')
person = input('Enter Your Name: ')

print('Enter 1 if you want to view your Balance or Enter 2 if you want to Add Expense: ')
while True:
    rn = int(input('Enter 1 or 2: '))
    if rn == 1:
        print("You have chosen 'View Balance'.")
        with open(person, 'r') as t:
            d = t.readlines()
            i = 0
            no_user = len(d) / 2

            print(no_user)
            all_user = []
            for user in range(int(no_user)):
                u = []
                u.sort()
                for x in range(2):
                    u.append(d[i + x])
                i = +2

                all_user.append(u)
            print(all_user)
        break
    elif rn == 2:
        print("You have chosen 2 'Add Expenses'. ")
        print('Enter the space separated names of the members:')
        members_names = (input())
        print('Total amount paid:')
        amount_paid = int(input())
        z = members_names.split()
        d = z, amount_paid
        emp_list = []

        num_of_members = len(z)
        p = amount_paid/(num_of_members+1)
        for i in range(len(z)):
            y=(emp_list.append(z[i]))
            for i in range(1):
                j = (emp_list.append(p))
        print(emp_list)
        with open(person, 'a') as filecope:
            for leadset in emp_list:
                filecope.write('%s\n' % leadset)

        g = open(person, 'r')
        cc = (g.readlines())
        g.close()
        break


# # library
import unittest
import os
import json

# # modules
from config import path_to_dir

class TestForJenkins(unittest.TestCase):

    def test_existence_of_files(self):
        paths = ('src/intense.json', 'main.py', 'bot.py', 'chatbot.py', 'config.py', 'logger.py', 'training.py')

        for name in paths:
            path = f'{path_to_dir}/{name}'
            exist = os.path.exists(path)
            if not exist:
                print(f'FILE NOT EXIST: {name} ({path})')
            self.assertTrue(exist)

    def test_structure_intense_json(self):
        with open('src/intense.json', 'r') as file:
            full_intents = json.load(file)

        languages = full_intents.keys()
        for language in languages:
            intense = full_intents[language]
            self.assertTrue('intents' in intense.keys())

            intense = intense['intents']
            for element in intense:
                keys = element.keys()
                headers = ('tag', 'patterns', 'responses')
                for header in headers:
                    self.assertTrue(header in keys)

if __name__ == "__main__":
    unittest.main()


import random
import numpy as np
import pandas as pd
import re
import uuid
import json
import hashlib
import io
from zipfile import ZipFile, ZIP_DEFLATED
from concurrent.futures import as_completed, ProcessPoolExecutor, wait

from os import listdir

file_regex = r"(\d+)_([A-Za-z_\d]+)_(\d*)_state_(\d+)\.txt"

def progressBar(iterable):
    total = len(iterable)
    largest = 0

    # Progress Bar Printing Function
    def printProgressBar(iteration, suf):
        percent = ("{0:.2f}").format(100 * (iteration / float(total)))

        filledLength = int(20 * iteration // total)
        bar = "█" * filledLength + "_" * (20 - filledLength)

        content = f"\rProgress |{bar}| {percent}% {suf}"
        lg = max(largest, len(content))
        missing = lg - len(content)
        content += " " * missing

        print(content, end="")

        return lg

    # Initial Call
    printProgressBar(0, "")
    # Update Progress Bar
    for i, item in enumerate(iterable):
        yield item
        largest = max(largest, printProgressBar(i + 1, item))
    # Print New Line on Complete
    print()

file_id = 0

def parse_file(file, content):
    global file_id
    matches = re.findall(file_regex, file)
    seed, alg, load, it = matches[0]

    tlc = 86
    tfc = 86 * 320

    data = pd.read_csv(io.BytesIO(content), delimiter=";")
    data = data.drop(["Unnamed: 320"], axis=1)

    data = data[0:tlc].values
    data = data.reshape(1, -1)

    actual_data = [[]]
    for i in range(0, tfc, 1):
        if data[0][i] != 0:
            data[0][i] = 1
        actual_data[0].append(int(data[0][i]))

    expected_output = {
        "MAdapSPV": 2,
        "K5SP_CS": 2,
        "K2SP_LastFit": 1,
        "K5SP_Random": 0,
    }

    payload = {
        "id": file_id,
        "seed": seed,
        "alg": alg,
        "load": load,
        "it": it,
        "data": actual_data,
        "expected_output": expected_output.setdefault(alg, 3),
    }
    file_id += 1

    return payload

input_zip = ZipFile("dataset.zip")
output_zip = ZipFile("workload.zip", "w", ZIP_DEFLATED)

batch = 500
cur = []
cur_i = 0

workload_id = 0

def process():
    global cur_i
    global cur
    global output_zip
    global workload_id

    if not cur:
        return
    workload = {
        "id": workload_id,
        "count": len(cur),
        "inputs": cur,
    }

    workload_id += 1

    content = json.dumps(workload, separators=(",", ":"))
    output_zip.writestr(f"{cur_i}.json", content)
    cur = []
    cur_i += 1

namelist = input_zip.namelist()
random.shuffle(namelist)

for filename in progressBar(namelist):
    content = input_zip.read(filename)
    parsed = parse_file(filename, content)

    cur.append(parsed)
    if len(cur) >= batch:
        process()

process()
output_zip.close()

# files = []
# batch = 500
# for i in range(0, len(filenames), batch):
#     files.append(filenames[i : i + batch])

# for i in range(len(files)):
#     print(f"{i} starting...")
#     workload = {
#         "id": uuid.uuid4().hex,
#         "count": 0,
#         "inputs": [],
#     }

#     with ProcessPoolExecutor(max_workers=7) as e:
#         futuresLst = [e.submit(parse_file, f) for f in files[i]]
#         for future in as_completed(futuresLst):
#             try:
#                 workload["inputs"].append(future.result())
#             except Exception as exc:
#                 print("%r generated an exception: %s" % (future, exc))

#         wait(futuresLst)
#         e.shutdown(True)

#     with open(f"workload/{i}.json", "w") as json_file:
#         json.dump(workload, json_file, separators=(",", ":"))

#     print(f"{i} ended")


# -*- coding:utf-8 -*-
#
# Copyright (C) 2019, Maximilian Köhl <mkoehl@cs.uni-saarland.de>

from __future__ import annotations

import hashlib

from sidekick import tester
from sidekick.runner import Handle, Runner

CHUNK = '''
His man-ner was not ef-fus-ive. It sel-dom was; but he was glad, I think,
to see me. With hardly a word spoken, but with a kindly eye, he waved
me to an arm-chair, threw across his case of ci-gars, and in-dic-ated a
spirit case and a gas-o-gene in the corner. Then he stood be-fore the fire
and looked me over in his sin-gu-lar in-tro-spect-ive fash-ion.
'''.strip() * 50

HASH = '8e62798e2f857491a3e54cdb511de48ae8100a01'

@tester.add_configuration('slow')
async def test_benchmark(runner: Runner, handle: Handle):
    for _ in range(10):
        for _ in range(50):
            handle.chunk(CHUNK)
            handle.end_of_paragraph()
        handle.end_of_segment()
    handle.eof()

    assert hashlib.sha1(await handle.drain()).hexdigest(), (
        'sha1 mismatch: incorrect result'
    )