import logging
import urllib

from logging.handlers import SysLogHandler

from cache import cached_result
from config import cfg
from flask import Flask, jsonify, abort, request

app = Flask(__name__)

API_MOUNTPOINT = '/api'
API_VERSION = 'v1'

handler = SysLogHandler(address='/dev/log', facility=SysLogHandler.LOG_USER)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter("music-discovery - %(levelname)s - %(message)s")
handler.setFormatter(formatter)
logger = logging.getLogger('music-discovery')
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

def api_url(url):
    url = url[1:] if url.startswith('/') else url
    a = '/'.join([x for x in [API_MOUNTPOINT, API_VERSION, url]])
    return a

# @app.route(api_url('/artist/bio'), methods=['POST'])
def artist_bio(req):
    """Fetches the artist biography summary text from last.fm

    Expects JSON paramater 'artist'"""

    artist = req.get('result').get('parameters').get('artist')
    logger.info('received {0} request for artist="{1}"'.format('artist_bio', artist))
    bio = cached_result('get_artist_info', [artist], {})
    speech = 'Unable to locate biography for {artist}'.format(artist=artist)

    if bio and len(bio) > 0:
        speech = bio

    return jsonify(
        {'speech': speech,
         'displayText': speech,
         'source': 'last-assist'})

# @app.route(api_url('/artist/toptracks'), methods=['POST'])
def artist_top_tracks(req):
    """Fetches top tracks for artist from last.fm

    Expects JSON paramater 'artist'"""

    artist = req.get('result').get('parameters').get('artist')
    logger.info('received {0} request for artist="{1}"'.format('artist_top_tracks', artist))
    top_tracks = cached_result('get_artist_top_tracks', [artist], {})
    speech = 'Unable to locate top tracks for {artist}'.format(artist=artist)

    if top_tracks is not None:
        speech = 'The most popular songs for {artist} are'.format(artist=artist)
        for track in top_tracks:
            speech += '. ' + track

    return jsonify(
        {'speech': speech,
         'displayText': speech,
         'source': 'last-assist'})

# @app.route(api_url('/artist/similar'), methods=['POST'])
def artist_similar(req):
    """Fetches artists that are similar to the given artist

    Expects JSON paramater 'artist'"""

    artist = req.get('result').get('parameters').get('artist')
    logger.info('received {0} request for artist="{1}"'.format('artist_similar', artist))
    sim_artists = cached_result('get_similar_artists', [artist], {})
    speech = 'Unable to locate similar artists for {artist}'.format(artist=artist)

    if sim_artists and len(sim_artists) > 0:
        speech = 'The following artists are similar to {artist}'.format(
            artist=artist)
        for art in sim_artists:
            speech += u'. {artist}'.format(artist=art)

    return jsonify(
        {'speech': speech,
         'displayText': speech,
         'source': 'last-assist'})

# @app.route(api_url('/track/similar'), methods=['POST'])
def track_similar(req):
    """Given a song title and artist, this will retrieve like or similar songs.

    Expects JSON paramater 'artist' and 'track'"""

    artist = req.get('result').get('parameters').get('artist')
    track = req.get('result').get('parameters').get('track')
    logger.info('received {0} request for artist="{1}", track="{2}"'.format('track_similar', artist, track))
    sim_tracks = cached_result('get_similar_tracks', [artist, track], {})
    speech = 'Unable to locate similar tracks for song {track} by {artist}'.format(
        track=track, artist=artist)

    if sim_tracks and len(sim_tracks) > 0:
        speech = 'The following songs are similar to {track} by {artist}'.format(
            track=track, artist=artist)
        for track in sim_tracks:
            speech += '. ' + track[0] + ' by ' + track[1]

    return jsonify(
        {'speech': speech,
         'displayText': speech,
         'source': 'last-assist'}
    )

@app.route(api_url('/apiai-hook'), methods=['POST'])
def apiai_hook():
    """A single entry point into the web hook. Request is then dispersed
    to the appropriate method based on the 'action' passed from API.ai.
    API.ai allows only a single fullfillment endpoint per agent."""

    route = {
        'artist_bio': artist_bio,
        'artist_top_tracks': artist_top_tracks,
        'artist_similar': artist_similar,
        'track_similar': track_similar,
    }

    req = request.get_json(silent=True, force=True)
    response = {}
    try:
        response = route[req.get('result').get('action')](req)
    except (KeyError, AttributeError) as e:
        logger.error('Invalid action specified, error="{0}".'.format(e))
        return jsonify(response)

    return response

@app.errorhandler(500)
def server_error(e):
    logger.exception('An error occurred during a request.')
    return 'An internal error occurred.', 500

if __name__ == '__main__':
    app.run(debug=False)


from datetime import datetime
from subprocess import Popen

# WORKLOADS = range(0, 105, 5)
WORKLOADS = [75]
NUM_CLIENTS = 5
REQUESTS_PER_CLIENT = 10000

output = open('/dev/null')

for workload in reversed(WORKLOADS):
    clients = []
    start_times = []
    end_times = []
    client_times = []

    for i in range(NUM_CLIENTS + 1):
        current_core_mask = hex(0x1 << (14 - i))

        command = [
            'taskset',
            current_core_mask,
            'java',
            '-jar',
            'ChainClient/target/chain-client-dev-jar-with-dependencies.jar',
            str(REQUESTS_PER_CLIENT),
            str(workload),
            str(19*(i+1))
        ]

        start_times.append(datetime.utcnow())
        end_times.append(datetime.utcnow())
        client_times.append(datetime.utcnow())
        client = Popen(command, stdout=output, stderr=output)
        clients.append(client)

    still_running = True
    while still_running:
        still_running = False
        for i, client in enumerate(clients):
            if client.poll() is not None:
                end_times[i] = datetime.utcnow()
            else:
                still_running = True

    for i, start_time in enumerate(start_times):
        end_time = end_times[i]
        client_times[i] = str(int((end_time - start_time).total_seconds() * 1000))

    print('{WORKLOAD},{CLIENT_TIMES}'.format(WORKLOAD=workload, CLIENT_TIMES=','.join(client_times)))


import string

import pyopenjtalk
import unicodedata

from convert_label import openjtalk2julius

# 実装上の問題から2文字の音素を1文字の適当な記号にマッピング
_japanese = ['ky','sp', 'sh', 'ch', 'ts','ty', 'ry', 'ny', 'by', 'hy', 'gy', 'kw', 'gw', 'kj', 'gj', 'my', 'py','dy']
japanese = ['$', '%', '&', '「', '」', '=', '~', '^', '|', '[', ']', '{', '}', '*', '+', '#', '<', '>']
_japanese2japanese = {
    'ky': '$',
    'sp': '%',
    'sh': '&',
    'ch': '「',
    'ts': '」',
    'ty': '=',
    'ry': '~',
    'ny': '^',
    'by': '|',
    'hy': '[',
    'gy': ']',
    'kw': '{',
    'gw': '}',
    'kj': '*',
    'gj': '+',
    'my': '#',
    'py': '<',
    'dy': '>',
}

def global_phonemize(text: str):
    phonemes = pyopenjtalk.g2p(text).split(' ')
    phonemes = [openjtalk2julius(p) for p in phonemes if p != '']
    for i in range(len(phonemes)):
        phoneme = phonemes[i]
        if phoneme in _japanese:
            phonemes[i] = _japanese2japanese[phoneme]
    return phonemes

def phonemize(text, tokenizer):
    text = unicodedata.normalize("NFKC", text)
    words = tokenizer.tokenize(text)
    input_ids_ = tokenizer.convert_tokens_to_ids(words)

    phonemes = []
    input_ids = []
    for i in range(len(words)):
        word = words[i]
        input_id = input_ids_[i]
        phoneme = global_phonemize(word.replace('#', ''))
        if len(phoneme) != 0:
            phonemes.append(''.join(phoneme))
            input_ids.append(input_id)

    assert len(input_ids) == len(phonemes)
    return {'input_ids' : input_ids, 'phonemes': phonemes}


import numpy as np

from gym.spaces import Box
from gym import ObservationWrapper

class GrayScaleObservation(ObservationWrapper):
    r"""Convert the image observation from RGB to gray scale. """
    def __init__(self, env, keep_dim=False):
        super(GrayScaleObservation, self).__init__(env)
        self.keep_dim = keep_dim

        assert len(env.observation_space.shape) == 3 and env.observation_space.shape[-1] == 3
        obs_shape = self.observation_space.shape[:2]
        if self.keep_dim:
            self.observation_space = Box(low=0, high=255, shape=(obs_shape[0], obs_shape[1], 1), dtype=np.uint8)
        else:
            self.observation_space = Box(low=0, high=255, shape=obs_shape, dtype=np.uint8)

    def observation(self, observation):
        import cv2
        observation = cv2.cvtColor(observation, cv2.COLOR_RGB2GRAY)
        if self.keep_dim:
            observation = np.expand_dims(observation, -1)
        return observation


import importlib
import os
from pathlib import Path
from unittest import mock

import setuptools
from google.cloud import storage
from google.auth import compute_engine

import boto3
from botocore.exceptions import ClientError
from com.griddynamics.dsl.ml.settings.description import Platform

class Helper:

    @staticmethod
    def get_file(file):
        if file:
            f = open(file, "rb")
            return f, Helper.get_file_name(file)

    @staticmethod
    def get_file_name(path):
        return os.path.basename(path)

    @staticmethod
    def get_setup_params(setup_path):
        spec = importlib.util.spec_from_file_location("setup", setup_path)
        setup = importlib.util.module_from_spec(spec)

        with mock.patch.object(setuptools, 'setup') as mock_setup:
            spec.loader.exec_module(setup)  # This is setup.py which calls setuptools.setup

        # called arguments are in `mock_setup.call_args`
        args, kwargs = mock_setup.call_args
        return kwargs

    @staticmethod
    def build_package_name_from_params(kwargs, extension):
        return f"{kwargs['name']}-{kwargs['version']}.{extension}"

    @staticmethod
    def construct_path(filename: str, base_path, platform=Platform.GCP):
        if platform ==Platform.GCP:
            return filename if filename.startswith('gs://') else Path(base_path) / filename
        else:
            return filename if filename.startswith('s3://') else Path(base_path) / filename

class GCPHelper(Helper):

    @staticmethod
    def delete_path_from_storage(bucket_name, path, use_cloud_engine_credentials=False):
        credentials = None
        if use_cloud_engine_credentials:
            credentials = compute_engine.Credentials()

        storage_client = storage.Client(credentials=credentials)
        bucket = storage_client.get_bucket(bucket_name)
        blobs = bucket.list_blobs(prefix=path)
        for blob in blobs:
            blob.delete()

    @staticmethod
    def copy_folder_on_storage(bucket_name, path_from: str, path_to: str, use_cloud_engine_credentials=False):
        path_from = path_from.replace(f'gs://{bucket_name}/', "")
        path_to = path_to.replace(f'gs://{bucket_name}/', "")
        credentials = None
        if use_cloud_engine_credentials:
            credentials = compute_engine.Credentials()

        storage_client = storage.Client(credentials=credentials)
        bucket = storage_client.get_bucket(bucket_name)
        blobs = bucket.list_blobs(prefix=path_from)
        for blob in blobs:
            bucket.copy_blob(blob, bucket, path_to + blob.name.replace(path_from, path_to))

    @staticmethod
    def download_folder_from_storage(bucket_name, path_from, path_to, use_cloud_engine_credentials=False):
        path_from = path_from.replace(f'gs://{bucket_name}/', "")
        credentials = None
        if use_cloud_engine_credentials:
            credentials = compute_engine.Credentials()
        storage_client = storage.Client(credentials=credentials)
        bucket = storage_client.get_bucket(bucket_name)
        blobs = bucket.list_blobs(prefix=path_from, delimiter="/")

        for blob in blobs:
            destination_uri = f'{path_to} / {blob.name}'
            blob.download_to_filename(destination_uri)

    @staticmethod
    def upload_file_to_storage(project_id, bucket, file_path: str, gs_path, use_cloud_engine_credentials=False):
        gs_path = gs_path.replace(f'gs://{bucket}/', "")
        credentials = None
        if use_cloud_engine_credentials:
            credentials = compute_engine.Credentials()
        client = storage.Client(project=project_id, credentials=credentials)
        bucket = client.get_bucket(bucket)
        blob = bucket.blob('{}/{}'.format(gs_path, file_path.split('/')[-1]))
        blob.upload_from_filename(file_path)

    @staticmethod
    def copy_file_on_storage(bucket_name, blob_name, new_blob_name, new_bucket_name=None,
                             use_cloud_engine_credentials=False):
        """Copies a blob from one bucket to another with a new name."""
        if new_bucket_name is None:
            new_bucket_name = bucket_name

        credentials = None
        if use_cloud_engine_credentials:
            credentials = compute_engine.Credentials()
        storage_client = storage.Client(credentials=credentials)
        source_bucket = storage_client.get_bucket(bucket_name)
        source_blob = source_bucket.blob(blob_name.replace(f'gs://{bucket_name}/', ""))
        destination_bucket = storage_client.get_bucket(new_bucket_name)

        source_bucket.copy_blob(
            source_blob, destination_bucket, new_blob_name.replace(f'gs://{new_bucket_name}/', ""))

class AWSHelper(Helper):

    @staticmethod
    def delete_path_from_storage(bucket_name, path):
        s3 = boto3.resource('s3')
        bucket = s3.Bucket(bucket_name)
        bucket.objects.filter(Prefix=path).delete()

    @staticmethod
    def copy_folder_on_storage(bucket_name, path_from: str, path_to: str):
        s3 = boto3.client("s3")
        objects = s3.list_objects_v2(Bucket=bucket_name, Prefix=path_from)['Contents']
        for obj in objects:
            dest = obj['Key'].replace(path_from, path_to)
            copy_source = {'Bucket': bucket_name, 'Key': obj['Key']}
            s3.copy_object(CopySource=copy_source, Bucket=bucket_name, Key=dest)

    @staticmethod
    def download_folder_from_storage(bucket_name, path_from, path_to):
        s3 = boto3.client("s3")
        objects = s3.list_objects_v2(Bucket=bucket_name, Prefix=path_from)['Contents']
        for obj in objects:
            dest = obj['Key'].replace(path_from, path_to)
            if not os.path.exists(os.path.dirname(dest)):
                os.makedirs(os.path.dirname(dest))
            try:
                s3.download_file(bucket_name, obj['Key'], dest)
            except IsADirectoryError:
                pass

    @staticmethod
    def upload_file_to_storage(bucket, file_name, object_name):
        if object_name is None:
            object_name = file_name
        # Upload the file
        s3_client = boto3.client('s3')
        try:
            s3_client.upload_file(file_name, bucket, object_name)
        except ClientError as e:
            raise e

    @staticmethod
    def copy_object(source_bucket, source_object_name, dest_bucket=None, dest_object_name=None):
        copy_source = {'Bucket': source_bucket, 'Key': source_object_name}
        if dest_object_name is None:
            dest_object_name = source_object_name
        if dest_bucket is None:
            dest_bucket = source_bucket
        # Copy the object
        s3 = boto3.client('s3')
        try:
            s3.copy_object(CopySource=copy_source, Bucket=dest_bucket, Key=dest_object_name)
        except ClientError as e:
            raise e

    @staticmethod
    def upload_object_to_storage(obj, bucket, object_name):
        client = boto3.client('s3')
        client.put_object(Body=obj, Bucket=bucket, Key=object_name)


# -*- coding: utf-8 -*-
from datetime import datetime

from odoo import models, fields, api
from odoo.exceptions import UserError, ValidationError

class PaiementPecModelClient(models.Model):
    _name = 'paiement.pec.model.client'
    _description = "Modele Prise en charge Client"

    name = fields.Char(string='Nom', required=True)
    company_id = fields.Many2one('res.company', string=u'Société',
                                 default=lambda self: self.env['res.company']._company_default_get(
                                     'paiement.pec.model.client'))
    received_account = fields.Many2one('account.account', string=u'Compte: PES Client à recevoir', required=True)
    at_bank_account = fields.Many2one('account.account', string=u"Compte: PES à l'encaissement", required=True)
    bank_account = fields.Many2one('account.account', string=u"Compte: Banque", required=True)
    bank_journal_id = fields.Many2one('account.journal', string=u"Journal: Banque")

    post = fields.Boolean(string=u'A Poster', default=True)

class PaiementChequeClient(models.Model):
    _inherit = 'paiement.cheque.client'

    name = fields.Char(string=u'Numéro', readonly=True, required=False, states={'payed': [('readonly', True)]})

    @api.model
    def create(self, vals):
        vals['name'] = self.env.ref('account_tres_pec.seq_tres_customer_cheque').next_by_code('paiement.cheque.client') or ''
        res = super(PaiementChequeClient, self).create(vals)
        return res

class PaiementOvClient(models.Model):
    _inherit = 'paiement.ov.client'

    name = fields.Char(string=u'Numéro', readonly=True, required=False, states={'payed': [('readonly', True)]})

    @api.model
    def create(self, vals):
        vals['name'] = self.env.ref('account_tres_pec.seq_tres_customer_ov').next_by_code('paiement.ov.client') or ''
        res = super(PaiementOvClient, self).create(vals)
        return res

class PaiementEffetClient(models.Model):
    _inherit = 'paiement.effet.client'

    name = fields.Char(string=u'Numéro', readonly=True, required=False, states={'payed': [('readonly', True)]})

    @api.model
    def create(self, vals):
        vals['name'] = self.env.ref('account_tres_pec.seq_tres_customer_effet').next_by_code('paiement.effet.client') or ''
        res = super(PaiementEffetClient, self).create(vals)
        return res

class PaiementCbClient(models.Model):
    _inherit = 'paiement.cb.client'

    name = fields.Char(string=u'Numéro', readonly=True, required=False, states={'payed': [('readonly', True)]})

    @api.model
    def create(self, vals):
        vals['name'] = self.env.ref('account_tres_pec.seq_tres_customer_cb').next_by_code('paiement.cb.client') or ''
        res = super(PaiementCbClient, self).create(vals)
        return res

class PaiementCashClient(models.Model):
    _inherit = 'paiement.cash.client'

    name = fields.Char(string=u'Numéro', readonly=True, required=False, states={'payed': [('readonly', True)]})

    @api.model
    def create(self, vals):
        vals['name'] = self.env.ref('account_tres_pec.seq_tres_customer_cash').next_by_code('paiement.cash.client') or ''
        res = super(PaiementCashClient, self).create(vals)
        return res

class PaiementPecClient(models.Model):
    _name = 'paiement.pec.client'
    _inherit = ['mail.thread', 'mail.activity.mixin']

    _description = 'Pec Client'
    _order = "date desc"

    name = fields.Char(string=u'Numéro', readonly=True, states={'payed': [('readonly', True)]})
    amount = fields.Float(string='Montant', required=True, states={'payed': [('readonly', True)]})
    journal_id = fields.Many2one('account.journal', string=u'Journal', states={'payed': [('readonly', True)]})
    date = fields.Date(string="Date", required=True, states={'payed': [('readonly', True)]})
    payed_date = fields.Date('Date encaissment')
    due_date = fields.Date(string=u"Date d'échéance", required=True, states={'payed': [('readonly', True)]})
    note = fields.Text("Notes")
    bank_client = fields.Many2one("res.partner.bank", string="Banque client")
    client = fields.Many2one('res.partner', string='Client', required=True, states={'payed': [('readonly', True)]})
    model_id = fields.Many2one('paiement.pec.model.client', string=u'Modèle Comptable',
                               required=True, states={'payed': [('readonly', True)]})

    move_line_ids = fields.One2many('account.move.line', 'pec_client_id', string=u'Lignes Comptables',
                                    states={'payed': [('readonly', True)]})
    tres_fees_ids = fields.One2many('tres.fees', 'pec_client_id', string=u'Frais Bancaires')
    caisse_id = fields.Many2one('paiement.caisse', string=u'Caisse')
    paiement_record_id = fields.Many2one('paiement.record', string=u'Reçu de Paiement', ondelete='cascade')
    company_id = fields.Many2one('res.company', u'Société', required=True,
                                 default=lambda self: self.env['res.company']._company_default_get(
                                     'paiement.pec.client'))
    analytic_account_id = fields.Many2one('account.analytic.account', string=u'Compte Analytique',
                                          states={'payed': [('readonly', True)]})
    origin = fields.Char('Origine')
    assurance_id = fields.Many2one('pec.assurance', string="Assurance")
    state = fields.Selection([('draft', 'Brouillon'),
                              ('caisse', 'Caisse'),
                              ('caisse_centrale', 'Caisse centrale'),
                              ('done', u'Confirmé'),
                              ('cancel', u'Annulé'),
                              ('rejected', u'Rejeté')], 'Etat', default='draft', readonly=True, required=True)

    def unlink(self):
        for rec in self:
            move_ids = rec.move_line_ids.mapped('move_id')
            move_ids.button_cancel()
            move_ids.unlink()
        return super(PaiementPecClient, self).unlink()

    def action_post_fees(self):
        for record in self:
            for fees in record.tres_fees_ids:
                if fees.state == 'draft':
                    fees.create_account_lines()

    def copy(self, default=None):
        if not default:
            default = {}
        default.update({
            'state': 'draft',
            'move_line_ids': [],
            'paiement_record_id': False,
        })
        return super(PaiementPecClient, self).copy(default)

    @api.model
    def create(self, vals):
        vals['name'] = self.env.ref('account_tres_pec.seq_tres_customer_pec').next_by_code('paiement.pec.client') or ''
        res = super(PaiementPecClient, self).create(vals)
        return res

    @api.model
    def get_partner_account(self, part, type):
        account_id = False
        if part and part.id:
            account_id = part.property_account_receivable_id.id
        return account_id

    def action_post_entries(self):
        account_move_obj = self.env['account.move']
        for pec in self:
            account_id = self.get_partner_account(pec.client, 'client')
            if not account_id:
                raise UserError(u'Le partenaire doit avoir un compte comptable')

            debit_val = {
                'name': pec.name,
                'date': pec.date,
                'date_maturity': pec.due_date,
                'ref': pec.note,
                'partner_id': pec.client.id,
                'account_id': account_id,
                'credit': pec.amount,
                'debit': 0.0,
                'pec_client_id': pec.id,
                'journal_id': pec.journal_id.id,
                'analytic_account_id': pec.analytic_account_id and pec.analytic_account_id.id or False,
                'currency_id': False
            }

            credit_val = {
                'name': pec.name,
                'date': pec.date,
                'date_maturity': pec.due_date,
                'ref': pec.note,
                'partner_id': pec.client.id,
                'account_id': pec.model_id.received_account.id,
                'credit': 0.0,
                'debit': pec.amount,
                'pec_client_id': pec.id,
                'journal_id': pec.journal_id.id,
                'currency_id': False,
            }

            lines = [(0, 0, debit_val), (0, 0, credit_val)]

            # payment_id = self.env['account.payment'].create({
            #     'name': 'BNK/' + pec.name,
            #     'amount': pec.amount,
            #     'payment_type': 'inbound',
            #     'partner_type': 'customer',
            #     'date': pec.date,
            #     'journal_id': pec.journal_id.id,
            #     'partner_id': pec.client.id,
            # })
            #
            # payment_id.action_post()

            move_id = account_move_obj.create({
                'journal_id': pec.journal_id.id,
                'date': pec.date,
                'name': pec.name,
                'ref': pec.note,
                'line_ids': lines,
                # 'payment_id': payment_id.id
            })

            move_id.post()

        return True

    def action_caisse(self):
        for pec in self:
            self.action_post_entries()
            pec.write({'state': 'caisse'})

    def action_caisse_centrale(self):
        caisse_obj = self.env['paiement.caisse']
        for pec in self:
            caisse_id = caisse_obj.search([('caisse_centrale', '=', True)], limit=1)
            if not caisse_id:
                raise UserError(u"Vous devez créer une caisse centrale")
            pec.write({'caisse_id': caisse_id.id, 'state': 'caisse_centrale'})

    def action_done(self):
        for pec in self:
            pec.write({'state': 'done'})

    def action_cancel(self):
        for pec in self:
            pec.write({'state': 'cancel'})

    def action_rejected(self):
        for pec in self:
            move_new_ids = []
            move_ids = pec.move_line_ids.mapped('move_id')
            for move_line in pec.move_line_ids:
                if move_line.reconciled:
                    move_line.remove_move_reconcile()
            for move in move_ids:
                move_new_ids.append(move.copy())
            for move_obj in move_new_ids:
                for line in move_obj.line_ids:
                    credit = line.credit
                    debit = line.debit
                    line.write({'credit': debit, 'debit': credit})
                move_obj.post()
            lines = pec.move_line_ids.filtered(lambda x: x.account_id.user_type_id.type in ('receivable', 'payable'))
            lines.reconcile()
            pec.write({'state': 'rejected'})
            pec.payed_date = fields.Date.context_today(self)
        return True

class PecAssurance(models.Model):
    _name = 'pec.assurance'

    name = fields.Char('Nom')


import os
import numpy as np
import pandas as pd
import torch
from torch.utils.data import DataLoader
from sklearn.model_selection import train_test_split

from utils import CofigDataset
from spectral_analysis import linear_classifier
from utils_BASiS import train_model, modelEvaluataion, sampleAnchors

import warnings
warnings.simplefilter("ignore", UserWarning)

# hyper parameters MNIST
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
classes = ('0', '1', '2', '3', '4',
           '5', '6', '7', '8', '9')
classNum = len(classes)

anchors_per_class = 25
anchors_num = classNum * anchors_per_class

batch_size = 512 - anchors_num
iter_num = 1000

# graph parameters
ms = 10
ms_normal = 7
sigmaFlag = 0

# RANSAC parameters
ransac_nIter = 100
ransac_tol = 0.1
ransac_nPoints = 20

# siamese features
train_features_list_pd = pd.read_pickle(
    r"../MNIST/Features/MNIST/mnist_train_siamese_features_list_pd.pkl")
test_features_list_pd = pd.read_pickle(
    r"../MNIST/Features/MNIST/mnist_test_siamese_features_list_pd.pkl")

train_features_list_np = np.array(train_features_list_pd.drop(['label'], axis=1))
train_features_list_torch = torch.from_numpy(train_features_list_np)
print("Train features shape:")
print(train_features_list_torch.shape)

train_labels_np = np.array(train_features_list_pd.label)
train_labels_list_torch = torch.from_numpy(train_labels_np)
print("Train labels shape:")
print(train_labels_list_torch.shape)

test_features_list_np = np.array(test_features_list_pd.drop(['label'], axis=1))
featrues_test = torch.from_numpy(test_features_list_np)
print("Test features shape:")
print(featrues_test.shape)

test_labels_np = np.array(test_features_list_pd.label)
labels_test = torch.from_numpy(test_labels_np)
print("Test labels shape:")
print(labels_test.shape)

featrues_train, featrues_val, labels_train, labels_val = train_test_split(train_features_list_torch,
                                                                          train_labels_list_torch, test_size=0.2,
                                                                          random_state=0)

if not os.path.exists('./results'):
    os.mkdir('./results')
    os.mkdir('./results/MNIST')

model_path = r".\results\MNIST\save_MNIST"
if not os.path.exists(model_path):
    os.mkdir(model_path)
    os.mkdir(model_path + '/images')
    os.mkdir(model_path + '/linear_classifier')

anchors_index, not_anchors_index = sampleAnchors(labels_test, anchors_per_class, classNum)
X_anchors = featrues_test[anchors_index]
X_not_anchors = featrues_test[not_anchors_index]

y_anchors = labels_test[anchors_index]
y_not_anchors = labels_test[not_anchors_index]

xTrain = torch.cat((X_anchors, featrues_train), dim=0)
yTrain = torch.cat((y_anchors, labels_train), dim=0)

xValid = torch.cat((X_anchors, featrues_val), dim=0)
yValid = torch.cat((y_anchors, labels_val), dim=0)

xTest = torch.cat((X_anchors, X_not_anchors), dim=0)
yTest = torch.cat((y_anchors, y_not_anchors), dim=0)

print('xTrain shape:')
print(xTrain.shape)
print('xValid shape:')
print(xValid.shape)
print('xTest shape:')
print(xTest.shape)

model, U_sampled_base = train_model(xTrain, yTrain, xValid, yValid, classes, anchors_per_class, anchors_num,
                                    batch_size, ms, ms_normal, sigmaFlag, ransac_nPoints, ransac_nIter, ransac_tol,
                                    iter_num, model_path, device)
torch.save(U_sampled_base, model_path + '/U_sampled.pt')
torch.save(xTest, model_path + '/xTest.pt')
torch.save(yTest, model_path + '/yTest.pt')

nmi, acc, grassmann, orthogonality = modelEvaluataion(model, xTest, yTest, U_sampled_base, classes, ms,
                                                          ms_normal, sigmaFlag, anchors_num,
                                                          ransac_nPoints, ransac_nIter, ransac_tol)

# linear regression
model_path = model_path + '/linear_classifier'

model.eval()  # put in evaluation mode
with torch.no_grad():
    encoded_xTrain = model(xTrain.float())
    encoded_xValid = model(xValid.float())
    encoded_xTest = model(xTest.float())

train_iter = CofigDataset(encoded_xTrain, yTrain)
train_loader = torch.utils.data.DataLoader(train_iter, batch_size=batch_size, shuffle=True, drop_last=True)
valid_iter = CofigDataset(encoded_xValid, yValid)
valid_loader = torch.utils.data.DataLoader(valid_iter, batch_size=batch_size, shuffle=False, drop_last=True)
test_iter = CofigDataset(encoded_xTest, yTest)
test_loader = torch.utils.data.DataLoader(test_iter, batch_size=batch_size, shuffle=False, drop_last=True)

test_accuracy = linear_classifier(train_loader, valid_loader, test_loader, encoded_xTrain, classes, model_path,
                                       device)

print("---------Test Eval -----------")
print("Test NMI: ", nmi)
print("Test ACC: ", acc)
print("Test Grassmann: ", grassmann)
print("Test Orthogonality: ", orthogonality)
print("Test Accuracy: ", test_accuracy)


import torch
import torch.nn as nn
import torch.nn.functional as F
import _C_gemm

class sparse_mm_dense_atf(torch.autograd.Function):
    @staticmethod
    def forward(ctx, sparse: torch.Tensor, dense: torch.Tensor):
        # sparse: [M, N]  dense: [N, P]  y:[M, P]
        if sparse.requires_grad or dense.requires_grad:
            ctx.save_for_backward(sparse, dense)
        y = torch.zeros(size=[sparse.shape[0], dense.shape[1]], dtype=torch.float, device=sparse.device)
        _C_gemm.sparse_mm_dense_cusparse(sparse, dense, y)
        # y = torch.mm(sparse, dense)
        return y

    @staticmethod
    def backward(ctx, grad_output):
        # grad_output: [M, P]
        sparse, dense = ctx.saved_tensors
        grad_sparse = grad_dense = None
        if ctx.needs_input_grad[0]:
            grad_sparse = grad_output.mm(dense.t())
        if ctx.needs_input_grad[1]:
            grad_dense = torch.zeros_like(dense.data)
            _C_gemm.sparse_mm_dense_cusparse(sparse.t(), grad_output, grad_dense)
            # grad_dense = sparse.t().mm(grad_output)
        return grad_sparse, grad_dense

def sparse_mm_dense(sparse: torch.Tensor, dense: torch.Tensor):
    '''
    * :ref:`API in English <sparse_mm_dense-en>`

    .. _sparse_mm_dense-cn:

    :param sparse: 稀疏2D tensor
    :type sparse: torch.Tensor
    :param dense: 稠密2D tensor
    :type dense: torch.Tensor
    :return: sparse 和 dense 的矩阵乘
    :rtype: torch.Tensor

    对输入的稀疏的二维矩阵 ``sparse`` 和稠密的二维矩阵 ``dense`` 进行矩阵乘法。

    .. warning::

        代码内部的实现方式是，首先将 ``sparse`` 转换为稀疏矩阵格式，然后再调用相关库进行运算。如果 ``sparse`` 不够稀疏，则该函数的速度会比普通矩阵乘法 ``torch.mm`` 慢很多。

    .. warning::

        稀疏矩阵的乘法存在一定的计算误差，但误差并不显著，或可忽略。

    .. warning::

        本函数不支持CPU。

    * :ref:`中文API <sparse_mm_dense-cn>`

    .. _sparse_mm_dense-en:

    :param sparse: a 2D sparse tensor
    :type sparse: torch.Tensor
    :param dense: a 2D dense tensor
    :type dense: torch.Tensor
    :return: a matrix multiplication of the matrices ``dense`` and ``sparse``
    :rtype: torch.Tensor

    Performs a matrix multiplication of the matrices ``dense`` and ``sparse``.

    .. admonition:: Warning
        :class: warning

        This function is implemented by converting ``sparse`` to a sparse format and doing a sparse matrix multiplication. If the sparsity of ``sparse`` is not high enough, the speed of this function will be slower than ``torch.mm``.

    .. admonition:: Warning
        :class: warning

        There are some numeral errors when doing the sparse matrix multiplication. But the errors are not significant.

    .. admonition:: Warning
        :class: warning

        This function does not support to run on cpu.
    '''
    return sparse_mm_dense_atf.apply(sparse, dense)


from Contacto import Contacto
from io import BufferedReader, BufferedWriter
import os

class Agenda:

    def __init__(self, listaContacto = [], path = os.getcwd() + "\\agenda.txt") -> None:
        self.__ListaContacto    = listaContacto
        self.__Path             = path

    def getListaContacto(self):

        return self.__ListaContacto

    def setListaContacto(self, listaContacto):

        self.__ListaContacto = listaContacto

    def getPath(self):

        return self.__Path

    def setPath(self, path):

        self.__Path = path

    def cargarContacto(self):

        if (os.path.exists(self.__Path)):

            f  : BufferedReader = open(self.__Path, "r")

            lineas = f.readlines()

            for linea in lineas :

                self.__crearContactoFichero(linea)

            f.close()

    def __crearContactoFichero(self, linea):

        datos = linea.split(";")

        #Correo,Calle,Piso,Ciudad,CodigoPostal,Nombre,Apellido,FellaNacimiento,TMovil,TTrabajo,TFijo
        contacto : Contacto = Contacto()

        contacto.setEmail(datos[0])
        contacto.setCalle(datos[1])
        contacto.setPiso(datos[2])
        contacto.setCiudad(datos[3])
        contacto.setCodigoPostal(datos[4])
        contacto.setNombre(datos[5])
        contacto.setApellido(datos[6])
        contacto.setFNacimiento(datos[7])
        contacto.setTMovil(datos[8])
        contacto.setTTrabajo(datos[9])
        contacto.setTFijo(datos[10])

        self.__ListaContacto.append(contacto)

    def crearContacto(self):

        correo      = input("Correo Electronico : ")
        calle       = input("Calle : ")
        piso        = input("Piso : ")
        ciudad      = input("Ciudad : ")
        cPostal     = input("Codigo Postal : ")
        nombre      = input("Nombre : ")
        apellido    = input("Apellido : ")
        fNacimiento = input("Fecha Nacimiento : ")
        tMovil      = input("Telefono Movil : ")
        tTrabajo    = input("Telefono Trabajo : ")
        tFijo       = input("Telefono Fijo : ")

        contacto : Contacto = Contacto(correo)
        contacto.setCalle(calle)
        contacto.setPiso(piso)
        contacto.setCiudad(ciudad)
        contacto.setCodigoPostal(cPostal)
        contacto.setNombre(nombre)
        contacto.setApellido(apellido)
        contacto.setFNacimiento(fNacimiento)
        contacto.setTMovil(tMovil)
        contacto.setTTrabajo(tTrabajo)
        contacto.setTFijo(tFijo)

        self.__ListaContacto.append(contacto)

    def guardarContactos(self):

        # Crear Fichero
        try:

            f : BufferedWriter = open(self.__Path,"w+")

        except FileExistsError:

            print("ya esta creado")

        else:

            for contacto in self.__ListaContacto :

                contacto : Contacto = contacto

                linea  = contacto.getEmail() + ";" + contacto.getCalle() + ";" + contacto.getPiso() + ";" + contacto.getCiudad() + ";" + contacto.getCodigoPostal() + ";" + contacto.getNombre() + ";" + contacto.getApellido() + ";" + contacto.getFNacimiento() + ";" + contacto.getTMovil() + ";" + contacto.getTTrabajo() + ";" + contacto.getTFijo()

                f.write(linea)

            f.flush()

            f.close()

    def mostrarAgenda(self):

        for contacto in self.__ListaContacto :

            contacto : Contacto = contacto

            print("----------------CONTACTO--------------")

            print(contacto.mostrarContacto())

            print("--------------------------------------")

    def buscarContactoPorNombre(self, nombre):

        for contacto in self.__ListaContacto :

            if (contacto.getNombre().lower() == nombre.lower()):

                print("----------------CONTACTO--------------")

                print(contacto.mostrarContacto())

                print("--------------------------------------")

    def borrarContactoPorNombre(self, nombre):

        posicion = 0
        salir = False

        while (posicion < len(self.__ListaContacto) and not(salir)):

            contacto : Contacto = self.__ListaContacto[posicion]

            if (contacto.getNombre().lower() == nombre.lower()):

                salir = True
                print("Contacto a Borrar : " , nombre)
                self.__ListaContacto.pop(posicion)

            posicion += 1

        if (not(salir)):

            print("Contacto no encontrado")

    def buscarContactoPorNumero(self, telefono):

        for contacto in self.__ListaContacto :

            if (contacto.getTMovil().lower() == telefono.lower()):

                print("----------------CONTACTO--------------")

                print(contacto.mostrarContacto())

                print("--------------------------------------")

    def borrarContactoPorNumero(self, telefono):

        posicion = 0
        salir = False

        while (posicion < len(self.__ListaContacto) and not(salir)):

            contacto : Contacto = self.__ListaContacto[posicion]

            if (contacto.getTMovil().lower() == telefono.lower()):

                salir = True
                print("Contacto a Borrar : " , telefono)
                self.__ListaContacto.pop(posicion)

            posicion += 1

        if (not(salir)):

            print("Contacto no encontrado")


#!/usr/bin/python
# encoding:utf-8
"""
@author: lance
@version: 1.0.0
@license: Apache Licence
@file: bert_exporter.py
@time: 2021/6/9 20:52
"""
from importlib import import_module

import torch

from utils import build_iterator

PAD, CLS = '[PAD]', '[CLS]'  # padding符号, bert中综合信息符号

dataset = 'data'
x = import_module('models.bert')
config = x.Config(dataset)
model = x.Model(config).to(config.device)
model.load_state_dict(torch.load('data/saved_dict/bert_2021_4_15_cpu.ckpt'))

def read(s):
    pad_size = 32
    contents = []

    token = config.tokenizer.tokenize(s.strip())
    token = [CLS] + token
    seq_len = len(token)
    mask = []
    token_ids = config.tokenizer.convert_tokens_to_ids(token)

    if pad_size:
        if len(token) < pad_size:
            mask = [1] * len(token_ids) + [0] * (pad_size - len(token))
            token_ids += ([0] * (pad_size - len(token)))
        else:
            mask = [1] * pad_size
            token_ids = token_ids[:pad_size]
            seq_len = pad_size
    contents.append((token_ids, 0, seq_len, mask))
    return contents

def predict(data):
    data_ = build_iterator(data, config)
    for texts, labels in data_:
        outputs = model(texts)
    predict_ = torch.max(outputs.data, 1)[1].cpu().numpy()
    return predict_

if __name__ == '__main__':
    while True:
        print("neg" if predict(read(input())) else "pos")


from typing import List
import pdb

solution_json = {
    "date": "2021/4/29",
    "design": 0,
    "coding": 7,
    "runtime": "48 ms",
    "memory": "15.4 MB"
}

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
    	d = False
    	v = nums
    	n = len(v)

    	hash = {}
    	for i in range(n):
    		if v[i] not in hash:
    			hash[v[i]] = True

    	ls = [*hash.keys()]
    	ls.sort(reverse=True)
    	if d:
    		print(ls)

    	n = len(ls)
    	if n >= 3:
    		out = ls[2]
    	elif n in [1, 2]:
    		out = ls[0]
    	else:
    		out = None

    	return out


import redis
import hashlib
import time

pool = redis.ConnectionPool(host='localhost', port=6379)
redis_connection = redis.Redis(connection_pool=pool)

SESSION_EXPIRE = 600

class RedisSession:

    def __init__(self, session_id):
        if session_id and redis_connection.exists(session_id):
            self.session_id = session_id
        else:
            self.session_id = self._generate_random_str()
            redis_connection.hset(self.session_id, '', '')
            redis_connection.expire(self.session_id, SESSION_EXPIRE)

    def _generate_random_str(self):
        md5_obj = hashlib.md5()
        md5_obj.update(bytes(str(time.time()), encoding='utf-8'))
        return md5_obj.hexdigest()

    def __setitem__(self, key, value):
        redis_connection.hset(self.session_id, key, value)
        redis_connection.expire(self.session_id, SESSION_EXPIRE)

    def __getitem__(self, item):
        return redis_connection.hget(self.session_id, item)

    def __delitem__(self, key):
        redis_connection.hdel(self.session_id, key)
        redis_connection.expire(self.session_id, SESSION_EXPIRE)


#Associação é a capacidade de associarmos uma classe a outra

class filhos:
    nomes = ['josé', 'mario', 'duda']

class pessoa:
    nome = 'joao'
    idade = 40
    salario = 5200
    f = filhos()

p = pessoa()
nome = p.nome
idade = p.idade
salario = p.salario
f = p.f.nomes

print('informacoes pessoais')
print()
print(f'Nome: {nome}')
print(f'Idade: {idade} anos')
print(f'salario: R$ {salario}')
print()
print('Filhos:')
for filho in f:
    print(filho)


import os
import numpy as np
import torch
from torch.autograd import Variable
from torch.nn import functional as F
from logging import getLogger

from .utils import get_optimizer, clip_grad_norm, get_lambda, reload_model
from .model import get_attr_loss, flip_attributes

logger = getLogger()

class Trainer(object):

    def __init__(self, ae, lat_dis, ptc_dis, clf_dis, data, params):
        """
        Trainer initialization.
        """
        # data / parameters
        self.data = data
        self.params = params

        # modules
        self.ae = ae
        self.lat_dis = lat_dis
        self.ptc_dis = ptc_dis
        self.clf_dis = clf_dis

        # optimizers
        self.ae_optimizer = get_optimizer(ae, params.ae_optimizer)
        logger.info(ae)
        logger.info('%i parameters in the autoencoder. '
                    % sum([p.nelement() for p in ae.parameters()]))
        if params.n_lat_dis:
            logger.info(lat_dis)
            logger.info('%i parameters in the latent discriminator. '
                        % sum([p.nelement() for p in lat_dis.parameters()]))
            self.lat_dis_optimizer = get_optimizer(lat_dis, params.dis_optimizer)
        if params.n_ptc_dis:
            logger.info(ptc_dis)
            logger.info('%i parameters in the patch discriminator. '
                        % sum([p.nelement() for p in ptc_dis.parameters()]))
            self.ptc_dis_optimizer = get_optimizer(ptc_dis, params.dis_optimizer)
        if params.n_clf_dis:
            logger.info(clf_dis)
            logger.info('%i parameters in the classifier discriminator. '
                        % sum([p.nelement() for p in clf_dis.parameters()]))
            self.clf_dis_optimizer = get_optimizer(clf_dis, params.dis_optimizer)

        # reload pretrained models
        if params.ae_reload:
            reload_model(ae, params.ae_reload,
                         ['img_sz', 'img_fm', 'init_fm', 'n_layers', 'n_skip', 'attr', 'n_attr'])
        if params.lat_dis_reload:
            reload_model(lat_dis, params.lat_dis_reload,
                         ['enc_dim', 'attr', 'n_attr'])
        if params.ptc_dis_reload:
            reload_model(ptc_dis, params.ptc_dis_reload,
                         ['img_sz', 'img_fm', 'init_fm', 'max_fm', 'n_patch_dis_layers'])
        if params.clf_dis_reload:
            reload_model(clf_dis, params.clf_dis_reload,
                         ['img_sz', 'img_fm', 'init_fm', 'max_fm', 'hid_dim', 'attr', 'n_attr'])

        # training statistics
        self.stats = {}
        self.stats['rec_costs'] = []
        self.stats['lat_dis_costs'] = []
        self.stats['ptc_dis_costs'] = []
        self.stats['clf_dis_costs'] = []

        # best reconstruction loss / best accuracy
        self.best_loss = 1e12
        self.best_accu = -1e12
        self.params.n_total_iter = 0

    def lat_dis_step(self):
        """
        Train the latent discriminator.
        """
        data = self.data
        params = self.params
        self.ae.eval()
        self.lat_dis.train()
        bs = params.batch_size
        # batch / encode / discriminate
        batch_x, batch_y = data.train_batch(bs)
        enc_outputs = self.ae.encode(Variable(batch_x.data, volatile=True))
        preds = self.lat_dis(Variable(enc_outputs[-1 - params.n_skip].data))
        # loss / optimize
        loss = get_attr_loss(preds, batch_y, False, params)
        self.stats['lat_dis_costs'].append(loss.data[0])
        self.lat_dis_optimizer.zero_grad()
        loss.backward()
        if params.clip_grad_norm:
            clip_grad_norm(self.lat_dis.parameters(), params.clip_grad_norm)
        self.lat_dis_optimizer.step()

    def ptc_dis_step(self):
        """
        Train the patch discriminator.
        """
        data = self.data
        params = self.params
        self.ae.eval()
        self.ptc_dis.train()
        bs = params.batch_size
        # batch / encode / discriminate
        batch_x, batch_y = data.train_batch(bs)
        flipped = flip_attributes(batch_y, params, 'all')
        _, dec_outputs = self.ae(Variable(batch_x.data, volatile=True), flipped)
        real_preds = self.ptc_dis(batch_x)
        fake_preds = self.ptc_dis(Variable(dec_outputs[-1].data))
        y_fake = Variable(torch.FloatTensor(real_preds.size())
                               .fill_(params.smooth_label).cuda())
        # loss / optimize
        loss = F.binary_cross_entropy(real_preds, 1 - y_fake)
        loss += F.binary_cross_entropy(fake_preds, y_fake)
        self.stats['ptc_dis_costs'].append(loss.data[0])
        self.ptc_dis_optimizer.zero_grad()
        loss.backward()
        if params.clip_grad_norm:
            clip_grad_norm(self.ptc_dis.parameters(), params.clip_grad_norm)
        self.ptc_dis_optimizer.step()

    def clf_dis_step(self):
        """
        Train the classifier discriminator.
        """
        data = self.data
        params = self.params
        self.clf_dis.train()
        bs = params.batch_size
        # batch / predict
        batch_x, batch_y = data.train_batch(bs)
        preds = self.clf_dis(batch_x)
        # loss / optimize
        loss = get_attr_loss(preds, batch_y, False, params)
        self.stats['clf_dis_costs'].append(loss.data[0])
        self.clf_dis_optimizer.zero_grad()
        loss.backward()
        if params.clip_grad_norm:
            clip_grad_norm(self.clf_dis.parameters(), params.clip_grad_norm)
        self.clf_dis_optimizer.step()

    def autoencoder_step(self):
        """
        Train the autoencoder with cross-entropy loss.
        Train the encoder with discriminator loss.
        """
        data = self.data
        params = self.params
        self.ae.train()
        if params.n_lat_dis:
            self.lat_dis.eval()
        if params.n_ptc_dis:
            self.ptc_dis.eval()
        if params.n_clf_dis:
            self.clf_dis.eval()
        bs = params.batch_size
        # batch / encode / decode
        batch_x, batch_y = data.train_batch(bs)
        enc_outputs, dec_outputs = self.ae(batch_x, batch_y)
        # autoencoder loss from reconstruction
        loss = params.lambda_ae * ((batch_x - dec_outputs[-1]) ** 2).mean()
        self.stats['rec_costs'].append(loss.data[0])
        # encoder loss from the latent discriminator
        if params.lambda_lat_dis:
            lat_dis_preds = self.lat_dis(enc_outputs[-1 - params.n_skip])
            lat_dis_loss = get_attr_loss(lat_dis_preds, batch_y, True, params)
            loss = loss + get_lambda(params.lambda_lat_dis, params) * lat_dis_loss
        # decoding with random labels
        if params.lambda_ptc_dis + params.lambda_clf_dis > 0:
            flipped = flip_attributes(batch_y, params, 'all')
            dec_outputs_flipped = self.ae.decode(enc_outputs, flipped)
        # autoencoder loss from the patch discriminator
        if params.lambda_ptc_dis:
            ptc_dis_preds = self.ptc_dis(dec_outputs_flipped[-1])
            y_fake = Variable(torch.FloatTensor(ptc_dis_preds.size())
                                   .fill_(params.smooth_label).cuda())
            ptc_dis_loss = F.binary_cross_entropy(ptc_dis_preds, 1 - y_fake)
            loss = loss + get_lambda(params.lambda_ptc_dis, params) * ptc_dis_loss
        # autoencoder loss from the classifier discriminator
        if params.lambda_clf_dis:
            clf_dis_preds = self.clf_dis(dec_outputs_flipped[-1])
            clf_dis_loss = get_attr_loss(clf_dis_preds, flipped, False, params)
            loss = loss + get_lambda(params.lambda_clf_dis, params) * clf_dis_loss
        # check NaN
        if (loss != loss).data.any():
            logger.error("NaN detected")
            exit()
        # optimize
        self.ae_optimizer.zero_grad()
        loss.backward()
        if params.clip_grad_norm:
            clip_grad_norm(self.ae.parameters(), params.clip_grad_norm)
        self.ae_optimizer.step()

    def step(self, n_iter):
        """
        End training iteration / print training statistics.
        """
        # average loss
        if len(self.stats['rec_costs']) >= 25:
            mean_loss = [
                ('Latent discriminator', 'lat_dis_costs'),
                ('Patch discriminator', 'ptc_dis_costs'),
                ('Classifier discriminator', 'clf_dis_costs'),
                ('Reconstruction loss', 'rec_costs'),
            ]
            logger.info(('%06i - ' % n_iter) +
                        ' / '.join(['%s : %.5f' % (a, np.mean(self.stats[b]))
                                    for a, b in mean_loss if len(self.stats[b]) > 0]))
            del self.stats['rec_costs'][:]
            del self.stats['lat_dis_costs'][:]
            del self.stats['ptc_dis_costs'][:]
            del self.stats['clf_dis_costs'][:]

        self.params.n_total_iter += 1

    def save_model(self, name):
        """
        Save the model.
        """
        def save(model, filename):
            path = os.path.join(self.params.dump_path, '%s_%s.pth' % (name, filename))
            logger.info('Saving %s to %s ...' % (filename, path))
            torch.save(model, path)
        save(self.ae, 'ae')
        if self.params.n_lat_dis:
            save(self.lat_dis, 'lat_dis')
        if self.params.n_ptc_dis:
            save(self.ptc_dis, 'ptc_dis')
        if self.params.n_clf_dis:
            save(self.clf_dis, 'clf_dis')

    def save_best_periodic(self, to_log):
        """
        Save the best models / periodically save the models.
        """
        if to_log['ae_loss'] < self.best_loss:
            self.best_loss = to_log['ae_loss']
            logger.info('Best reconstruction loss: %.5f' % self.best_loss)
            self.save_model('best_rec')
        if self.params.eval_clf and np.mean(to_log['clf_accu']) > self.best_accu:
            self.best_accu = np.mean(to_log['clf_accu'])
            logger.info('Best evaluation accuracy: %.5f' % self.best_accu)
            self.save_model('best_accu')
        if to_log['n_epoch'] % 5 == 0 and to_log['n_epoch'] > 0:
            self.save_model('periodic-%i' % to_log['n_epoch'])

def classifier_step(classifier, optimizer, data, params, costs):
    """
    Train the classifier.
    """
    classifier.train()
    bs = params.batch_size

    # batch / classify
    batch_x, batch_y = data.train_batch(bs)
    preds = classifier(batch_x)
    # loss / optimize
    loss = get_attr_loss(preds, batch_y, False, params)
    costs.append(loss.data[0])
    optimizer.zero_grad()
    loss.backward()
    if params.clip_grad_norm:
        clip_grad_norm(classifier.parameters(), params.clip_grad_norm)
    optimizer.step()


from committee_combinations import committee

professors = int(input("Enter the number of professors in the department"))
prof_on_multiple_committees = input("Can a professor be on multiple committees? Enter y or n:")
free_profs = professors
total_combinations = 1

if prof_on_multiple_committees == 'y':
    bool_prof_on_multiple_committees = True
else:
    bool_prof_on_multiple_committees = False

while True:
    committee_name = input("Enter the name of the committee:")
    if committee_name == "":
        break
    committee_chair_person = input("Does the committee need a chair? Enter y or n:")
    if committee_chair_person == 'y':
        bool_chair = True
    else:
        bool_chair = False
    number_of_members = int(input("How many members?"))
    if number_of_members > free_profs:
        combos = committee(free_profs, free_profs, bool_chair)
        print("Assigning only", free_profs, "members to the", committee_name, "committee.")
        print("there are", combos, "ways to form the", committee_name, "commitee.")
        total_combinations = total_combinations * combos
        free_profs = 0
        break
    else:
        combos = committee(free_profs, number_of_members, bool_chair)
        print ("There are", combos, "ways to form the", committee_name, "committee.")
        total_combinations = total_combinations * combos
        if bool_prof_on_multiple_committees == False:
            free_profs = free_profs - number_of_members
    if bool_prof_on_multiple_committees == False and free_profs == 0:
        break

print ("There are", total_combinations, "ways to form all the committees")


import curses
import curses.textpad
import random
import time

board = [' '] * 10
# board[0] = "X"

z = 0  # for the 'playersymbol' function

def test(i, screen, dims):  # alternates between 'X' and 'O'
    global z
    if z == 0:
        s = 'X'
        board[i] = s
        z += 1
        # fills the list of moves with the players' corresponding symbols
        return "X"
    else:
        s = "O"
        board[i] = s
        z -= 1
        return "O"

def get_computer_move(screen, dims):
    i = random.randrange(1, 10)
    if i == 7:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6), int(dims[1]/6), test(i, screen, dims))
    elif i == 8:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6), int(dims[1]/2), test(i, screen, dims))
    elif i == 9:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6), int(dims[1]/6*5), test(i, screen, dims))
    elif i == 4:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*3), int(dims[1]/6), test(i, screen, dims))
    elif i == 5:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*3), int(dims[1]/2), test(i, screen, dims))
    elif i == 6:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*3), int(dims[1]/6*5), test(i, screen, dims))
    elif i == 1:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*5), int(dims[1]/6), test(i, screen, dims))
    elif i == 2:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*5), int(dims[1]/2), test(i, screen, dims))
    elif i == 3:
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*5), int(dims[1]/6*5), test(i, screen, dims))
    return()

def rewrite(i):  # to avoid overwriting existing steps
    global board
    global write
    global c
    if board[i] == " ":
        write = True
    else:
        write = False

def tie(screen, dims):
    check = 0
    for r in range(0, 10):
        if board[r] == "X":
            check += 1
    return(check > 4)

def getPlayerMove(c, screen, dims):
    # prints the players' symbols on the space associated with the num keys
    if c == ord('7'):
        i = 7
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6), int(dims[1]/6), test(i, screen, dims))
    elif c == ord('8'):
        i = 8
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6), int(dims[1]/2), test(i, screen, dims))
    elif c == ord('9'):
        i = 9
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6), int(dims[1]/6*5), test(i, screen, dims))
    elif c == ord('4'):
        i = 4
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*3), int(dims[1]/6), test(i, screen, dims))
    elif c == ord('5'):
        i = 5
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*3), int(dims[1]/2), test(i, screen, dims))
    elif c == ord('6'):
        i = 6
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*3), int(dims[1]/6*5), test(i, screen, dims))
    elif c == ord('1'):
        i = 1
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*5), int(dims[1]/6), test(i, screen, dims))
    elif c == ord('2'):
        i = 2
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*5), int(dims[1]/2), test(i, screen, dims))
    elif c == ord('3'):
        i = 3
        rewrite(i)
        if write:
            screen.addstr(int(dims[0]/6*5), int(dims[1]/6*5), test(i, screen, dims))
    return()

player1 = "X"
player2 = "O"

def winner1():  # returns true if player1 wins

    global player1
    global board
    return ((board[7] == player1 and board[8] == player1 and board[9] == player1) or  # horizontal
            (board[4] == player1 and board[5] == player1 and board[6] == player1) or  # horizontal
            (board[1] == player1 and board[2] == player1 and board[3] == player1) or  # horizontal
            (board[7] == player1 and board[4] == player1 and board[1] == player1) or  # vertical
            (board[8] == player1 and board[5] == player1 and board[2] == player1) or  # vertical
            (board[9] == player1 and board[6] == player1 and board[3] == player1) or  # vertical
            (board[7] == player1 and board[5] == player1 and board[3] == player1) or  # diagonal
            (board[9] == player1 and board[5] == player1 and board[1] == player1))  # diagonal

def winner2():  # returns true if player2 wins
    global player2
    global board
    return ((board[7] == player2 and board[8] == player2 and board[9] == player2) or  # horizontal
            (board[4] == player2 and board[5] == player2 and board[6] == player2) or  # horizontal
            (board[1] == player2 and board[2] == player2 and board[3] == player2) or  # horizontal
            (board[7] == player2 and board[4] == player2 and board[1] == player2) or  # vertical
            (board[8] == player2 and board[5] == player2 and board[2] == player2) or  # vertical
            (board[9] == player2 and board[6] == player2 and board[3] == player2) or  # vertical
            (board[7] == player2 and board[5] == player2 and board[3] == player2) or  # diagonal
            (board[9] == player2 and board[5] == player2 and board[1] == player2))  # diagonal

def winning(screen, dims, name1, name2):  # whether one of the players won, prints this text
    if winner1():
        screen.addstr(int(dims[0]/2-2), int(dims[1]/2-7), name1 + " won!")  # X
    elif winner2():
        screen.addstr(int(dims[0]/2-2), int(dims[1]/2-7), name2 + " won!")  # O
    return()

def one_player(screen, name1, name2):
    global z
    dims = screen.getmaxyx()
    screen = curses.newwin(int(dims[0]), int(dims[1]), 0, 0)
    screen.box()
    for i in range(0, int(dims[0])):
        screen.addstr(i, int(dims[1]/3), '|')  # vertical
        screen.addstr(i, int(dims[1]/3*2), '|')
    for i in range(0, int(dims[1])):
        screen.addstr(int(dims[0]/3), i, '_')  # horizontal
        screen.addstr(int(dims[0]/3*2), i, '_')
    screen.addstr(0, 1, "TIC-TAC-TOE ------ Use number keys to place 'X' and 'O', press 'q' to quit.")
    curses.noecho()
    curses.cbreak()
    screen.keypad(True)
    curses.curs_set(0)

    while True:
        if winner1() or winner2():  # if one of the players won
            winning(screen, dims, name1, name2)
            screen.refresh()
            c = screen.getch()
            if c == ord('q'):  # if 'q' pressed the game exits
                break  # Exit the while loop
        elif tie(screen, dims):
            screen.addstr(int(dims[0]/2-2), int(dims[1]/2-7), "It's tie!")
            c = screen.getch()
            if c == ord('q'):  # if 'q' pressed the game exits
                break  # Exit the while loop
        elif z == 0:
            c = screen.getch()
            if c == ord('q'):  # if 'q' pressed the game exits
                break  # Exit the while loop
            elif z == 0:  # if 'q' is not pressed the game continues
                getPlayerMove(c, screen, dims)
                screen.refresh()
        else:
            get_computer_move(screen, dims)
            time.sleep(1)
    curses.endwin()

def multi_player(screen, name1, name2):
    global z
    dims = screen.getmaxyx()
    screen = curses.newwin(int(dims[0]), int(dims[1]), 0, 0)
    screen.box()
    for i in range(0, int(dims[0])):
        screen.addstr(i, int(dims[1]/3), '|')  # vertical
        screen.addstr(i, int(dims[1]/3*2), '|')
    for i in range(0, int(dims[1])):
        screen.addstr(int(dims[0]/3), i, '_')  # horizontal
        screen.addstr(int(dims[0]/3*2), i, '_')
    screen.addstr(0, 1, "TIC-TAC-TOE ------ Use number keys to place 'X' and 'O', press 'q' to quit.")
    curses.noecho()
    curses.cbreak()
    screen.keypad(True)
    curses.curs_set(0)

    while True:
        if winner1() or winner2():  # if one of the players won
            winning(screen, dims, name1, name2)
            screen.refresh()
            c = screen.getch()
            if c == ord('q'):  # if 'q' pressed the game exits
                break  # Exit the while loop
        elif tie(screen, dims):
            screen.addstr(int(dims[0]/2-2), int(dims[1]/2-7), "It's tie!")
            c = screen.getch()
            if c == ord('q'):  # if 'q' pressed the game exits
                break  # Exit the while loop
        else:
            c = screen.getch()
            if c == ord('q'):  # if 'q' pressed the game exits
                break  # Exit the while loop
            else:  # if 'q' is not pressed the game continues
                getPlayerMove(c, screen, dims)
                screen.refresh()
    curses.endwin()

def menu(screen, name1, name2, multi_single):
    dims = screen.getmaxyx()
    screen = curses.newwin(int(dims[0]), int(dims[1]), 0, 0)
    screen.box()
    screen.addstr(0, int(dims[1]/2-4), "MENU")
    screen.addstr(5, 3, 'Welcome ' + name1 + " and " + name2 + ' in this TicTacToe Game!')
    screen.addstr(10, 3, 'If you need help, press "h" or press "s" to start a game!')
    while True:
        c = screen.getch()
        screen.refresh()
        if c == ord('h'):
            screen.addstr(15, 3, 'You can navigate the symbols with num keys.'
                          ' Goal is collecting 3 same symbols next to each other.')
        elif c == ord('s'):
            if multi_single == "1":
                one_player(screen, name1, name2)
            else:
                multi_player(screen, name1, name2)
            break
        elif c == ord('q'):  # if 'q' pressed the game exits
            break
        else:
            screen.addstr(12, 3, 'Please chose from "h" to help or "s" to start!')
            screen.refresh()
    curses.endwin()
    exit()

def main():

    name1 = input('Type your name! ')
    name2 = "Computer"
    multi_single = input(name1 + " ,if you want to play against computer press 1 or play multi press 2!")
    while True:
        if multi_single == "1":
            screen = curses.initscr()
            menu(screen, name1, name2, multi_single)
        elif multi_single == "2":
            name2 = input('Type your friend name! ')
            screen = curses.initscr()
            menu(screen, name1, name2, multi_single)
        else:
            multi_single = input(name1 + " ,if you want to play against computer press 1 or play multi press 2!")

main()


import xlrd
import collections

class CalculateJIRAStats(object):

    def __init__(self,type):
        # give JIRA dumps path
        if type == 'XL':
            path = 'C:\\Users\\sballary\\Documents\\Sanjay\\PycharmProjects\\JIRA-Stat-Automation\\dumps_Aug-20-2020.xlsx'
            # give resolved date
            resolved_date = ''
            jira_issue_list = []
            input_work_book = xlrd.open_workbook(path)
            input_work_sheet = input_work_book.sheet_by_index(1)
            self.start_reading(input_work_sheet)
    def start_reading(self,input_work_sheet):
        jira_issue_list = []
        for i in range(1, input_work_sheet.nrows):
            current_row = input_work_sheet.row_values(i, 0, 100)
            jira_issue_object = {'jira_id': int(input_work_sheet.cell_value(i, 2)), 'assigned_to': input_work_sheet.cell_value(i, 13),
                                 'priority': self.calculate_priority(current_row),
                                 'application': self.calculate_application(current_row),
                                 'isEnhancement': self.find_if_enhancement(current_row), 'status': input_work_sheet.cell_value(i, 4)}
            jira_issue_list.append(jira_issue_object)
        self.report(jira_issue_list)
    @staticmethod
    def report(jira_issue_list):
        jira_issues = []
        jira_enhancements = []
        for object in jira_issue_list:
            if object['isEnhancement']:
                jira_enhancements.append(object)
            else:
                jira_issues.append(object)

        all_jira = []
        all_jira.extend(jira_issues)
        all_jira.extend(jira_enhancements)
        print("Total Issue/Enhancements: {}".format(len(jira_issues)+len(jira_enhancements)))
        print(collections.Counter([jira['priority'] for jira in all_jira]))
        print("Issues : {}".format(len(jira_issues)))
        print("Enhancements : {}".format(len(jira_enhancements)))
        populate_stat_issues = PopulateStats('Issues', jira_issues)
        populate_stat_issues.print_report()
        populate_stat_enhancements = PopulateStats('Enhancements', jira_enhancements)
        populate_stat_enhancements.print_report()
        print("--------------------------------------------------------------------------------")
        # print("Issues")
        for ticket in jira_issues:
                # if ticket['application'] in ['UC4', 'uc4'] and ticket['priority']  in ['P1','p1']:
                print("{},{},{},{},{}".format(ticket['application'].upper(),ticket['jira_id'],ticket['priority'],ticket['status'],'Issue'))
        # print("Enhancements")
        for ticket in jira_enhancements:
                # if ticket['application'] in ['UC4', 'uc4'] and ticket['priority']  in ['P1','p1']:
                print("{},{},{},{},{}".format(ticket['application'].upper(), ticket['jira_id'], ticket['priority'],ticket['status'],'Enhancement'))

    @staticmethod
    def calculate_priority(excel_row_array):
        track_priority_occurrence = False
        priority = 'NA'
        for i in range(len(excel_row_array)):
            if excel_row_array[i] == 'P1' or excel_row_array[i] == 'P2' or excel_row_array[i] == 'P3':
                track_priority_occurrence = True
                priority = excel_row_array[i]
                if track_priority_occurrence:
                    return priority
        if not track_priority_occurrence:
            raise Exception('Jira Ticket {} does not have any Priority assigned. For correct report priority'
                            'needs to be assigned'.format(excel_row_array[1]))
        return priority

    @staticmethod
    def calculate_application(excel_row_array):
        track_application_occurrence = False
        application = 'NA'
        import re
        pattern = re.compile("UC\d",re.IGNORECASE)
        for i in range(len(excel_row_array)):
            if pattern.match(excel_row_array[i]):
                track_application_occurrence = True
                application = excel_row_array[i]
                if track_application_occurrence:
                    return application
        if not track_application_occurrence:
            raise Exception('Jira Ticket {} does not have application name against it.'.
                            format(excel_row_array[1]))
        return application

    @staticmethod
    def find_if_enhancement(excel_row_array):
        """
            To find an enhancement we need to look at below occurrence:
            'Issue_Type_Issue' return False
            'Issue_Type_Enhancements' return True
            'Issue_Type_Additional_Requirements' return True
             If nothing is found look for
             Return as Issue i.e. False
        """
        for i in range(len(excel_row_array)):
            if excel_row_array[i] in ['Issue_Type_Enhancements', 'Issue_Type_Additional_Requirements']:
                return True
            elif excel_row_array[i] == 'Issue_Type_Issue':
                return False
        return False

class PopulateStats(object):
    def __init__(self, defect_type, jira_object):
        self.defect_type = defect_type
        self.jira_object = jira_object

    def print_report(self):
        print('####################################################################################')
        print('##############################' + self.defect_type + '###############################')
        print('####################################################################################')
        print('-------------------------------------------------------------------------------------')
        print('---------------------------------------USE CASE 1------------------------------------')
        print('---------Blocked---------Not Started---------In Progress----------UAT----------Closed--------Total')
        self.user_case_specific_stat('UC1')
        print('-------------------------------------------------------------------------------------')
        print('---------------------------------------USE CASE 2------------------------------------')
        print('---------Blocked---------Not Started---------In Progress----------UAT----------Closed--------Total')
        self.user_case_specific_stat('UC2')
        print('-------------------------------------------------------------------------------------')
        print('---------------------------------------USE CASE 3------------------------------------')
        print('---------Blocked---------Not Started---------In Progress----------UAT----------Closed--------Total')
        self.user_case_specific_stat('UC3')
        print('-------------------------------------------------------------------------------------')
        print('---------------------------------------USE CASE 4------------------------------------')
        print('---------Blocked---------Not Started---------In Progress----------UAT----------Closed--------Total')
        self.user_case_specific_stat('UC4')
        print('-------------------------------------------------------------------------------------')
        print('---------------------------------------USE CASE 5------------------------------------')
        print('---------Blocked---------Not Started---------In Progress----------UAT----------Closed--------Total')
        self.user_case_specific_stat('UC5')
        print('-------------------------------------------------------------------------------------')
        print('---------------------------------------USE CASE 6------------------------------------')
        print('---------Blocked---------Not Started---------In Progress----------UAT----------Closed--------Total')
        self.user_case_specific_stat('UC6')

    def user_case_specific_stat(self, use_case):
        use_case_wise_jira_list = []
        for jiraobject in self.jira_object:
            if jiraobject['application'] == use_case:
                use_case_wise_jira_list.append(jiraobject)
        self.process_stat(use_case_wise_jira_list)

    def process_stat(self, usecase_jira_list):
        p1_jira_tickets = []
        p2_jira_tickets = []
        p3_jira_tickets = []
        for jiraobject in usecase_jira_list:
            if jiraobject['priority'] == 'P1':
                p1_jira_tickets.append(jiraobject)
            elif jiraobject['priority'] == 'P2':
                p2_jira_tickets.append(jiraobject)
            elif jiraobject['priority'] == 'P3':
                p3_jira_tickets.append(jiraobject)
            else:
                raise Exception('Stats cannot be generated as Jira Ticket {} does not have any priority'
                                .format(jiraobject['jira_id']))

        blocked = 0
        not_started = 0
        in_progress = 0
        uat = 0
        closed = 0
        for ticket in p1_jira_tickets:
            if ticket['status'] == 'New Requests':
                not_started = not_started + 1
            elif ticket['status'] == 'Done':
                closed = closed + 1
            elif ticket['status'] == 'Blocked':
                blocked = blocked + 1
            elif ticket['status'] == 'UAT':
                uat = uat + 1
            else:
                in_progress = in_progress + 1
        total = blocked + not_started + in_progress + uat + closed
        print('P1          ' + str(blocked) + '                    ' + str(not_started) + '                  '
              + str(in_progress) + '            ' + str(uat) + '             ' + str(closed) + '             '
              + str(total))
        blocked = 0
        not_started = 0
        in_progress = 0
        uat = 0
        closed = 0
        for ticket in p2_jira_tickets:
            if ticket['status'] == 'New Requests' or ticket['status'] == 'Backlog':
                not_started = not_started + 1
            elif ticket['status'] == 'Done':
                closed = closed + 1
            elif ticket['status'] == 'Blocked':
                blocked = blocked + 1
            elif ticket['status'] == 'UAT':
                uat = uat + 1
            else:
                in_progress = in_progress + 1
        total = blocked + not_started + in_progress + uat + closed
        print('P2          ' + str(blocked) + '                    ' + str(not_started) + '                  '
              + str(in_progress) + '            ' + str(uat) + '             ' + str(closed) + '             '
              + str(total))
        blocked = 0
        not_started = 0
        in_progress = 0
        uat = 0
        closed = 0

        for ticket in p3_jira_tickets:
            if ticket['status'] == 'New Requests' or ticket['status'] == 'Backlog':
                not_started = not_started + 1
            elif ticket['status'] == 'Done':
                closed = closed + 1
            elif ticket['status'] == 'Blocked':
                blocked = blocked + 1
            elif ticket['status'] == 'UAT':
                uat = uat + 1
            else:
                in_progress = in_progress + 1
        total = blocked + not_started + in_progress + uat + closed
        print('P3          ' + str(blocked) + '                    ' + str(not_started) + '                  '
              + str(in_progress) + '            ' + str(uat) + '             ' + str(closed) + '             '
              + str(total))

if __name__ == '__main__':
    CalculateJIRAStats('XL')


import numpy as np
import pandas as pd
import plotly.graph_objects as go
import dash
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input,Output
import plotly.express as px
import dash_table

# external CSS stylesheets
external_stylesheets = [
   {
       'href': 'https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css',
       'rel': 'stylesheet',
       'integrity': 'sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO',
       'crossorigin': 'anonymous'
   }
]

covid_19_data=pd.read_csv('covid_19_data.csv')
us_cities=pd.read_csv('time_series_covid_19_deaths_US.csv')
world_c=pd.read_csv('time_series_covid_19_confirmed.csv')
world_c1=world_c[['Country/Region','Lat','Long']]
world_c1.rename(columns={'Country/Region':'Country_Region'},inplace=True)
world_c_US=pd.read_csv('time_series_covid_19_confirmed_US.csv')
world_c_US2=world_c_US[['Country_Region','Lat','Long_']]
world_c_US2.rename(columns={'Long_':'Long'},inplace=True)
world=world_c1.append(world_c_US2)

fig2 = px.scatter_mapbox(world, lat=world["Lat"], lon=world["Long"], hover_name=world["Country_Region"],
                        color_discrete_sequence=["fuchsia"], zoom=.5, height=600)
fig2.update_layout(title='The corona virus affected Countries around the World : ',
    mapbox_style="white-bg",
    mapbox_layers=[
        {
            "below": 'traces',
            "sourcetype": "raster",
            "source": [
                "https://basemap.nationalmap.gov/arcgis/rest/services/USGSImageryOnly/MapServer/tile/{z}/{y}/{x}"
            ]
        }
      ])

fig = go.Figure(data=go.Scattergeo(
        locationmode = 'USA-states',
        lon=us_cities["Long_"],
        lat=us_cities["Lat"],
        text=us_cities["Province_State"],
        mode = 'markers',
        marker = dict(
            size = 8,
            opacity = 0.8,
            reversescale = True,
            autocolorscale = False,
            symbol = 'square',
            line = dict(
                width=1,
                color='rgba(102, 102, 102)'
            ),
            colorscale = 'Blues',
            cmin = 0,
            colorbar_title="The Deeper the colour the more affected the city is : "
        )))
fig.update_layout(
        title = 'The corona virus affected Cities in US -',
        geo = dict(
            scope='usa',
            projection_type='albers usa',
            showland = True,
            landcolor = "rgb(250, 250, 250)",
            subunitcolor = "rgb(217, 217, 217)",
            countrycolor = "rgb(217, 217, 217)",
            countrywidth = 0.5,
            subunitwidth = 0.5
        ),
    )

countries=covid_19_data['Country/Region'].unique().tolist()
total_c=[]
total_r=[]
total_d=[]
for i in countries:
    new_df=covid_19_data[covid_19_data['Country/Region']==i]
    if(new_df['Province/State'].count() == 0 ):
        count_c=new_df.drop_duplicates(subset='Country/Region',keep='last')['Confirmed'].sum()
        total_c.append(count_c)
        count_r=new_df.drop_duplicates(subset='Country/Region',keep='last')['Recovered'].sum()
        total_r.append(count_r)
        count_d=new_df.drop_duplicates(subset='Country/Region',keep='last')['Deaths'].sum()
        total_d.append(count_d)
    else:
        count_c=new_df.drop_duplicates(subset='Province/State',keep='last')['Confirmed'].sum()
        total_c.append(count_c)
        count_r=new_df.drop_duplicates(subset='Province/State',keep='last')['Recovered'].sum()
        total_r.append(count_r)
        count_d=new_df.drop_duplicates(subset='Province/State',keep='last')['Deaths'].sum()
        total_d.append(count_d)
total_confirmed=np.sum(total_c)
total_recovered=np.sum(total_r)
total_death=np.sum(total_d)
active_cases=total_confirmed-(total_recovered+total_death)
closed_cases=(total_recovered+total_death)

data11={'Countries': countries, 'Total cases' : total_c}
df11=pd.DataFrame(data11)
data22={'Countries': countries, 'Total cases' : total_r}
df22=pd.DataFrame(data22)
data33={'Countries': countries, 'Total cases' : total_d}
df33=pd.DataFrame(data33)

option=[
    {'label':'Infected', 'value':'Infected'},
    {'label':'Countries-Recovered','value':'total_recovered'}
]

options=[
   {'label':'All', 'value':'All'},
   {'label':'Total Recovered', 'value':'total_recovered'},
   {'label':'Total Confirmed', 'value':'total_confirmed'},
   {'label':'Total Death', 'value':'total_death'}
]

app2 = dash.Dash(__name__, external_stylesheets=external_stylesheets)
server=app2.server

app2.title='Corona Pandemic'

app2.layout=html.Div([
    html.H5("updated on : 06/04/2020, Time : 11:00 ", style={ 'text-align':'right', 'padding':'1%', 'color':'#FFFFFF'}),
    html.H1("Corona Virus Pandemic Analysis", style={'text-align': 'center'}, className='title'),
    html.Img(className='image', src='https://cdn.kalingatv.com/wp-content/uploads/2020/03/Coronavirus-COVID-19.jpg', alt='covid-19 image',
             style={
                 'height': '400px',
                 'float': 'center',
                 'position': 'relative',}

             ),
    html.H4('The structure of a COVID-19 Virus',className='structure', style= {
                    'color' : '#fc172e',
                    'text-align' : 'center',
                    'font-size' : '2rem',
                    'font-weight' : 'bold',
                    'padding' : '1%',
    }),
    html.A("Link to external site- World Health Organization reports", href='https://www.who.int/emergencies/diseases/novel-coronavirus-2019', target="_blank"),
    html.Hr(className='hrtag'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Img(className='title-image',
                             src="https://webassets.mongodb.com/_com_assets/cms/3D_medical_animation_coronavirus_structure-0kardto2r8.jpg",
                             alt='Picture of a covid 19 virus',
                             style={
                                 'height': '60%',
                                 'width': '60%',
                                 'float': 'left',
                                 'position': 'relative',
                                 'padding-top': 0,
                                 'padding-right': 0},
                             ),
                    html.P('People may be sick with the virus for 1 to 14 days before developing symptoms.'
                           ' The most common symptoms of coronavirus disease (COVID-19) are fever, tiredness, and dry cough. Most people (about 80%) '
                           'recover from the disease without needing special treatment.More rarely, the disease can be serious and even fatal. Older people, and people with other medical conditions '
                           '(such as asthma, diabetes, or heart disease), may be more vulnerable to becoming severely ill.', className='para'),
                    html.Hr(className='hrtag'),

                ],className='card-body')
            ],className='card')
        ],className='col-lg-12')
    ],className='row'),
    html.H3('Present Status Across the World :', className='title-bar', style= {
        'color':'#fc172e'
    }),
    html.Div([
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Total Cases", style={'font-size':'20px'}),
                    html.H4(total_confirmed, className='text-light')
                ], className='card-body')
            ], className='card bg-danger')
        ], className='col-md-2'),
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Active Cases",style={'font-size':'20px'}),
                    html.H4(active_cases, className='text-light')
                ], className='card-body')
            ], className='card bg-info')
        ], className='col-md-3'),
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Closed Cases", style={'font-size':'20px'}),
                    html.H4(closed_cases, className='text-light')
                ], className='card-body')
            ], className='card bg-success')
        ], className='col-md-2'),
        html.Div([
            html.Div([
                html.Div([

                    html.H3("Total Recovered", style={'font-size':'20px'}),
                    html.H4(total_recovered, className='text-light')
                ], className='card-body')
            ], className='card bg-danger')
        ], className='col-md-3'),
        html.Div([
            html.Div([
                html.Div([
                    html.H3("Total Death", style={'font-size':'20px'}),
                    html.H4(total_death, className='text-light')
                ], className='card-body')
            ], className='card bg-danger')
        ], className='col-md-2')
    ], className='row top-label'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('Graphical Information of collected data around the world  :', className='h3-first'),
                    dcc.Dropdown(id='picker',options=options,value='All'),
                    dcc.Graph(id='scatter')
                ],className='card-body')
            ],className='card')
        ],className='col-md-12')
    ],className='row first-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('Infected Vs Recovered :'),
                    dcc.Dropdown(id='pick',options=option,value='Infected'),
                    dcc.Graph(id='overview')
                ],className='card-body')
            ],className='card')
        ],className='col-md-12')
    ],className='row second-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('World Map of Infection Covid-19 :'),
                    dcc.Graph(figure=fig2)
                ],className='card-body')
            ],className='card')
        ],className='col-lg-12')
    ],className='row third-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.Hr(className='hrtag'),
                    html.H3('United States Map of Infection Covid-19 :'),
                    dcc.Graph(figure=fig)
                ],className='card-body')
            ],className='card')
        ],className='col-lg-12')
    ],className='row forth-graph'),
    html.Div([
        html.Div([
            html.Div([
                html.Div([
                    html.H2('Total Confirmed Cases :-'),
                    dash_table.DataTable(id='table1',columns=[{"name": i, "id": i} for i in df11.columns],
                    data=df11.to_dict('records'),
                    style_table={"overflowY":"scroll",'height': 500},style_cell={'textAlign': 'center'},
                                         style_cell_conditional=[
                                             {
                                                 'if': {'column_id': 'Countries'},
                                                 'textAlign': 'right'
                                             }
                                         ],style_header={
                                                     'fontWeight': 'bold',
                                             'backgroundColor': 'rgb(230, 230, 230)',
                                         },style_data_conditional=[ {
                                                     'if': {'row_index': 'odd'},
                                                     'backgroundColor': 'rgb(248, 248, 248)'
                                                                        }]
                                         )
                ],className='card-body table-format')
            ],className='card')
        ],className='col-lg-4'),
        html.Div([
            html.Div([
                html.Div([
                    html.H2('Total Recoved Cases :-'),
                    dash_table.DataTable(id='table2',columns=[{"name": j, "id": j} for j in df22.columns],
                    data=df22.to_dict('records'),style_table={"overflowY": "scroll",'height': 500},style_cell={'textAlign': 'center'},
                                         style_cell_conditional=[
                                             {
                                                 'if': {'column_id': 'Countries'},
                                                 'textAlign': 'right'
                                             }
                                         ],style_header={
                                                     'fontWeight': 'bold',
                                             'backgroundColor': 'rgb(230, 230, 230)',
                                         },style_data_conditional=[ {
                                                     'if': {'row_index': 'odd'},
                                                     'backgroundColor': 'rgb(248, 248, 248)'
                                                                        }]
                                         )
                ],className='card-body table-format')
            ],className='card')
        ],className='col-lg-4'),
        html.Div([
            html.Div([
                html.Div([
                    html.H2('Total Death cases :-'),
                    dash_table.DataTable(id='table3',columns=[{"name": k, "id": k} for k in df33.columns],
                    data=df33.to_dict('records'),style_table={"overflowY": "scroll",'height': 500},style_cell={'textAlign': 'center'},
                                         style_cell_conditional=[
                                             {
                                                 'if': {'column_id': 'Countries'},
                                                 'textAlign': 'right'
                                             }],style_header={
                                                     'fontWeight': 'bold',
                                             'backgroundColor': 'rgb(230, 230, 230)',
                                         },style_data_conditional=[ {
                                                     'if': {'row_index': 'odd'},
                                                     'backgroundColor': 'rgb(248, 248, 248)'
                                                                        }
                                         ])
                ],className='card-body table-format')
            ],className='card')
        ],className='col-lg-4')
    ],className='row'),
    html.Footer([
        html.Div(['© Copyright 2020 : ',
            html.A('Tuhin Mukherjee',href="https://whitexgod.github.io/cv/")
        ],className='footer-copyright text-center py-3',style={'color':'#fc172e'})
    ],className='page-footer font-small blue')
],className='container')

@app2.callback(Output('scatter','figure'), [Input('picker','value')])
def update_graph(type):

    if type=='All':

            pscat=covid_19_data.groupby('Last Update')['Confirmed'].sum().sort_values().reset_index()
            return {'data':[go.Scatter(x=pscat['Last Update'], y=pscat['Confirmed'], mode='markers', marker={'color':'#00a65a', 'size':8})],
               'layout':go.Layout(title='Line of Virus Spread per day', xaxis={'title':'By Date'}, yaxis={'title':'No. of cases'})}

    elif type=='total_confirmed':
            data1={'Countries': countries, 'Total cases' : total_c}
            df1=pd.DataFrame(data1)
            return {'data': [go.Bar(x=df1['Countries'], y=df1['Total cases'])],
               'layout': go.Layout(title='Total number of Confirmed cases across the world', xaxis={'title': 'Countries'}, yaxis = {'title': 'Number of Cases'})}

    elif type=='total_recovered':
            data2={'Countries': countries, 'Total cases' : total_r}
            df2=pd.DataFrame(data2)
            return {'data': [go.Bar(x=df2['Countries'], y=df2['Total cases'])],
               'layout': go.Layout(title='Total number of Recovered cases across the world',xaxis={'title': 'Countries'}, yaxis = {'title': 'Number of Cases'})}

    elif type=='total_death':
            data3={'Countries': countries, 'Total cases' : total_d}
            df3=pd.DataFrame(data3)
            return {'data': [go.Bar(x=df3['Countries'], y=df3['Total cases'])],
               'layout': go.Layout(title='Total number of Deaths cases across the world',xaxis={'title': 'Countries'}, yaxis = {'title': 'Number of Cases'})}

@app2.callback(Output('overview','figure'), [Input('pick','value')])
def update_graph(type):

    if type=='Infected':

        data4 = {'Countries': countries, 'Total cases': total_c}
        df4 = pd.DataFrame(data4)
        return {'data': [go.Pie(labels=df4['Countries'], values=df4['Total cases'])]}

    elif type=='total_recovered':

        data5 = {'Countries': countries, 'Total cases': total_r}
        df5 = pd.DataFrame(data5)
        return {'data': [go.Pie(labels=df5['Countries'], values=df5['Total cases'])]}

if __name__=="__main__":
   app2.run_server(debug=True)


import tornado.ioloop
import tornado.web
import tornado.escape

class CookieHandler(tornado.web.RequestHandler):
    def get(self):
        self.set_cookie("odn_cookie", tornado.escape.url_escape("未加密cookie串"))
        self.set_secure_cookie("src_cookie", "加密scure_cookie串")
        self.write("查看设置的cookie")

class ShcookHandler(tornado.web.RequestHandler):
    def get(self):
        odn_cookie = tornado.escape.url_escape(self.get_cookie("odn_cookie"))
        scr_cookie = self.get_secure_cookie("src_cookie").decode("utf-8")
        self.write(f"普通cookie:{odn_cookie}
 安全cookie: {scr_cookie}")

def make_app():
    app = tornado.web.Application(
    [(r"/sscookie", CookieHandler),
    (r"/shcook", ShcookHandler),
    ],
    cookie_secret="abc123",
    debug=True
    )
    return app

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.instance().start()