import os

from django.conf import settings
from django.contrib.auth.models import Permission
from django.contrib.humanize.templatetags.humanize import naturaltime
from django.dispatch import receiver
from django.template.defaultfilters import floatformat
from django.utils.safestring import mark_safe
from django.utils.translation import gettext_lazy as _

from ephios.core.dynamic_preferences_registry import LastRunPeriodicCall
from ephios.core.signals import register_healthchecks

# health checks are meant to monitor the health of the application while it is running
# in contrast there are django checks which are meant to check the configuration of the application

def run_healthchecks():
    for _, healthchecks in register_healthchecks.send(None):
        for HealthCheck in healthchecks:
            check = HealthCheck()
            status, message = check.check()
            yield check, status, message

class HealthCheckStatus:
    OK = "ok"
    WARNING = "warning"
    ERROR = "error"
    UNKNOWN = "unknown"

class AbstractHealthCheck:
    @property
    def slug(self):
        """
        Return a unique slug for this health check.
        """
        raise NotImplementedError

    @property
    def name(self):
        """
        Return a short name of this health check.
        """
        raise NotImplementedError

    @property
    def description(self):
        """
        Return a short description of this health check.
        """
        raise NotImplementedError

    @property
    def documentation_link(self):
        """
        Return a link to the documentation of this health check.
        """
        return None

    def check(self):
        """
        Return a tuple of (status, message) where status is one of HealthCheckStatus
        """
        raise NotImplementedError

class DBHealthCheck(AbstractHealthCheck):
    slug = "db"
    name = _("Database")
    description = _("The database is the central storage for all data.")
    documentation_link = "https://docs.djangoproject.com/en/stable/ref/databases/"

    def check(self):
        from django.db import connection

        try:
            connection.cursor()
            Permission.objects.exists()
        except Exception as e:
            return HealthCheckStatus.ERROR, str(e)

        if settings.DATABASES["default"]["ENGINE"] == "django.db.backends.sqlite3":
            return HealthCheckStatus.WARNING, _(
                "Using SQLite, which should not be used in production."
            )

        return HealthCheckStatus.OK, _("Database connection established.")

class CacheHealthCheck(AbstractHealthCheck):
    slug = "cache"
    name = _("Cache")
    description = _("The cache is used to store temporary data.")
    documentation_link = "https://docs.djangoproject.com/en/stable/topics/cache/"

    def check(self):
        from django.core import cache

        try:
            cache.cache.set("_healthcheck", "1")
            if not cache.cache.get("_healthcheck") == "1":
                raise Exception("Cache not available")
        except Exception as e:
            return HealthCheckStatus.ERROR, str(e)

        if (
            settings.CACHES.get("default", {}).get("BACKEND")
            == "django.core.cache.backends.locmem.LocMemCache"
        ):
            return HealthCheckStatus.WARNING, _(
                "Using LocMemCache, which should not be used in production."
            )

        return HealthCheckStatus.OK, _("Cache connection established.")

class CronJobHealthCheck(AbstractHealthCheck):
    slug = "cronjob"
    name = _("Cronjob")
    description = _(
        "A cron job must regularly call ephios to do recurring tasks like sending notifications."
    )
    documentation_link = (
        "https://docs.ephios.de/en/stable/admin/deployment/manual/index.html#setup-cron"
    )

    def check(self):
        last_call = LastRunPeriodicCall.get_last_call()
        if LastRunPeriodicCall.is_stuck():
            if last_call:
                return (
                    HealthCheckStatus.WARNING,
                    mark_safe(
                        _("Cronjob stuck, last run {last_call}.").format(
                            last_call=naturaltime(last_call),
                        )
                    ),
                )
            else:
                return (
                    HealthCheckStatus.ERROR,
                    mark_safe(_("Cronjob stuck, no last run.")),
                )
        else:
            return (
                HealthCheckStatus.OK,
                mark_safe(_("Last run {last_call}.").format(last_call=naturaltime(last_call))),
            )

class DiskSpaceHealthCheck(AbstractHealthCheck):
    slug = "disk_space"
    name = _("Disk space")
    description = _("Disk space needs to be available to store data.")
    documentation_link = (
        "https://docs.ephios.de/en/stable/admin/deployment/manual/index.html#data-directory"
    )

    def check(self):
        # if under 100 MB are available, we consider this an error
        # if under 1 GB are available, we consider this a warning
        # otherwise, we consider this ok
        try:
            disk_usage = os.statvfs(settings.MEDIA_ROOT)
        except AttributeError:
            # not available on windows
            return (
                HealthCheckStatus.UNKNOWN,
                mark_safe(_("Disk space check not available.")),
            )
        free_bytes = disk_usage.f_bavail * disk_usage.f_frsize
        MEGA = 1024 * 1024
        if free_bytes < 100 * MEGA:
            return (
                HealthCheckStatus.ERROR,
                mark_safe(
                    _(
                        "Less than 100 MB of disk space available. "
                        "Please free up some disk space."
                    )
                ),
            )
        if free_bytes < 1024 * MEGA:
            return (
                HealthCheckStatus.WARNING,
                mark_safe(
                    _("Less than 1 GB of disk space available. Please free up some disk space.")
                ),
            )
        return (
            HealthCheckStatus.OK,
            mark_safe(
                _("{disk_space} of disk space available.").format(
                    disk_space=f"{floatformat(free_bytes / MEGA / 1024,1)} GB"
                )
            ),
        )

@receiver(register_healthchecks, dispatch_uid="ephios.core.healthchecks.register_core_healthchecks")
def register_core_healthchecks(sender, **kwargs):
    yield DBHealthCheck
    yield CacheHealthCheck
    yield CronJobHealthCheck
    yield DiskSpaceHealthCheck


n=int(input("enter the num :"))
a=str(n)
b=len(a)
c=0
for i in range(b):
    d=(int(a[i]))**b
    c=c+d
if c==n:
    print(n,"is armstrong number")
else:
    print(n,"is not a armstrong")


from  tkinter import *
from procesos.procesosGui import *
from vistas.dialogo import *
from dao.crud import *
from archivos.archivosD import *
from dominio.entidades2 import *
class Registro:

    def __init__(self,titulo = None):
        self.crud = CrudUsuario()
        self.dlg= Dialogo()
        self.ovC = ProcesosGui()
        self.getWindow(titulo)
        self.getFrame()
        self.getLabels()
        self.getInputs()
        self.getButtons()

    def getWindow(self,titulo = None):
        self.ven = Toplevel()
        self.ven.title(titulo)
        self.ven.config(bg="navyblue")
        self.ovC.getCenter(self.ven,400,570)
        self.ven.iconbitmap(r"C:/Users/Lenovo/PycharmProjects/pythonProject1/pythonProject/Examen/descarga-_4_.ico")
        self.ven.resizable(0,0)
        #self.ven.mainloop()

    def getFrame(self):
        self.marco = Frame(self.ven, bd=10, bg="#8DA6CE")
        self.marco.pack(fill="both", expand=1)
        self.marco.config(cursor="pirate")
        self.marco.config(bd=40)
        self.marco.config(relief="sunken")

    def getLabels(self):
        posX = 120
        tam = 15
        eti1 = Label(self.marco, fg="black",
                     bg="white", text="Registro de Estudiantes",
                     font=("Tahoma", 18)).place(x=200, y=30)
        eti2 = Label(self.marco, fg="black",
                     bg="white", text="Id_Usuario:",
                     font=("Tahoma", tam)).place(x=70, y=100)

        eti3 = Label(self.marco, fg="black",
                     bg="white", text="Numero de Matricula:",
                     font=("Tahoma", tam)).place(x=70, y=150)

        eti4 = Label(self.marco, fg="black",
                     bg="white", text="Nombre:",
                     font=("Tahoma", tam)).place(x=70, y=200)

        eti5 = Label(self.marco, fg="black",
                     bg="white", text="Apellido:",
                     font=("Tahoma", tam)).place(x=70, y=250)

    def getInputs(self):
        posX = 350
        self.id_usuarioo = Entry(self.marco, font=("Tahoma", 16),bg="lightgray")
        self.id_usuarioo.place(x=280, y=100, width=180, height=25)

        self.numero_matricula = Entry(self.marco, font=("Tahoma", 16),bg="lightgray")
        self.numero_matricula.place(x=280, y=150, width=180, height=25)
        #self.numero_matricula.config(show="")

        self.nombre = Entry(self.marco, font=("Tahoma", 16),bg="lightgray")
        self.nombre.place(x=280, y=200, width=180, height=25)

        self.apellido = Entry(self.marco, font=("Tahoma", 16),bg="lightgray")
        self.apellido.place(x=280, y=250, width=180, height=25)

    def getButtons(self):
        self.btn0 = Button(self.marco,
                           relief="flat",
                           text="Vaciar campos",
                           bg="white",
                           fg="black",
                           cursor="hand1",
                           command=self.vaciar
                           ).place(x=80, y=30, width=90)

        self.aceptar = Button(self.marco, relief="flat",
                              text="Aceptar", bg="white",
                              font=("Arial", 16), fg="black",
                              cursor="hand1",
                              command=self.grabar
                              ).place(x=150, y=290,
                                      width=110)
        self.cancelar = Button(self.marco, relief="flat",
                               text="Cancelar", bg="white",
                               font=("Arial", 16), fg="black",
                               cursor="hand1",
                               command=self.ven.destroy).place(x=300, y=290,
                                                                width=110, height=40)

    def grabar(self):
        datos=(self.id_usuarioo.get(),
               self.numero_matricula.get(),
               self.nombre.get(),
               self.apellido.get())
        msg = self.crud.insertUser("sistemaa_academico",datos)

        self.dlg.setValues("Mensaje",150,320)
        self.dlg.setMensaje(msg)
        self.dlg.getDialogo()
        self.vaciar()

    def vaciar(self):
        self.id_usuarioo.delete(0, END)
        self.numero_matricula.delete(0, END)
        self.nombre.delete(0, END)
        self.apellido.delete(0, END)


import ast
import sys
from importlib.machinery import ModuleSpec
from inspect import stack
from pathlib import Path
from re import match
from types import ModuleType
from urllib.parse import urlparse

import nbformat
from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell

from cells import CellDeleter
from node import GitNode, PathNode

# Injects an `Importer`!
from gists import importer

import opts
from rgxs import maybe

def merge(l, r, *keys):
    l = l or {}
    n = l.copy()
    if not keys:
        keys = r.keys()
    for k in keys:
        if not k in r:
            continue
        rv = r[k]
        if k in l:
            lv = l[k]
            if lv != rv:
                raise Exception(f'Conflicting elem: {k} -> ({lv}, {rv})')
        else:
            n[k] = rv
    return n

class URLLoader:

    def __init__(self, path=None):
        self.shell = InteractiveShell.instance()
        self.path = path
        self._print = print

    def print(self, *args, **kwargs):
        if opts.verbose:
            self._print(*args, **kwargs)

    def url_mod(self, url, path):
        node = PathNode(path)
        self.print(f'Forwarding URL {url} to path {path}')
        spec = importer.spec(str(url), node, origin=path, pkg=False)
        mod = importer.create_module(spec, install=False)
        mod = importer.exec_path(node, mod)
        return mod

    def main(
        self,
        path=None,
        *names,
        run_nbinit=True,
        all=False,
        **kwargs,
    ):
        log = self.print
        log(f'URLLoader.main({self}, path={path}, names={names}, all={all}, **{kwargs}')
        gist = kwargs.get('gist')
        github = kwargs.get('github')
        gitlab = kwargs.get('gitlab')
        pkg = kwargs.get('pkg')

        url = urlparse(path)
        if url.scheme or gist or github or gitlab:
            domain = url.netloc

            from _gist import Commit, File, Gist, chars

            gist_attrs = Gist.parse_url(path, throw=False)
            if gist_attrs or gist:
                assert not github
                assert not gitlab
                assert not pkg

                gist_attrs = merge(gist_attrs, kwargs, 'user', 'commit', 'file')
                if gist:
                    maybe_user = maybe(f'(?P<user>{chars})/')
                    id_re = f'(?P<id>{chars})'
                    m = match(f'^{maybe_user}{id_re}$', gist)
                    if not m: raise Exception(f'Unrecognized gist: {gist}')

                    user = m.group('user')
                    id = m.group('id')

                    gist_attrs = merge(gist_attrs, dict(id=id, user=user))

                log(f'gist_attrs: {gist_attrs}')
                obj = Gist.from_dict(skip_cache=opts.skip_cache, **gist_attrs)
                if isinstance(obj, Commit):
                    commit = obj
                    log(f'Parsed commit: {commit}')
                    gist = commit.gist
                    name = gist.module_name
                elif isinstance(obj, File):
                    file = obj
                    commit = file.commit
                    log(f'Parsed commit: {commit} (file {file})')
                    name = file.module_fullname
                else:
                    raise Exception(f'Unrecognized gist object: {obj}')

                if name in sys.modules:
                    mod = sys.modules[name]
                    log(f'Found loaded gist module: {mod}')
                else:
                    log(f'Loading gist module {name} (commit {commit})')
                    node = GitNode(commit)
                    with importer.tmp_path(node):
                        [ top, *pieces ] = name.split('.')
                        mod_path = [top]
                        fullname = top
                        while True:
                            spec = importer.find_spec(name)
                            if not spec:
                                raise Exception(f'Failed to find spec for {name} (commit {commit})')

                            mod = importer.create_module(spec)
                            importer.exec_module(mod)

                            if not pieces: break
                            basename = pieces.pop(0)
                            mod_path += [basename]
                            fullname += f'.{basename}'

            elif domain == 'github.com':
                raise NotImplementedError
            elif domain == 'gitlab.com':
                raise NotImplementedError
            elif match(r'https?', url.scheme):
                from url import URL
                url = URL(path)
                # Force materialization of the URL's content to the on-disk cache
                url.content
                path = url._dir / 'content'
                mod = self.url_mod(url, path)
        else:
            mod = self.url_mod(url, path)

        if not names and not all: return mod

        dct = mod.__dict__

        if hasattr(mod, '__all__'):
            members = mod.__all__
        else:
            members = [ name for name in dct if not name.startswith('_') ]

        import_all = '*' in names or all is True or all == '*'
        if import_all:
            names = [ name for name in names if not name == '*' ]

        not_found = list(set(names).difference(members))
        if not_found:
            raise Exception('Names not found: %s' % ','.join(not_found))

        if not import_all:
            members = names

        log(f'Bubbling up {members}')
        update = { name: dct[name] for name in members }
        stk = stack()
        cur_file = stk[0].filename
        cur_dir = Path(cur_file).parent
        frame_info = next(frame for frame in stk if Path(frame.filename).parent != cur_dir)
        log(f'Frame: {frame_info}, {frame_info.filename}')
        frame_info.frame.f_globals.update(update)
        return mod


import logging

import pandas as pd
import numpy as np

def get_val(nested_dict, key):
    """
    Get the value to the key from the (possibly) nested dict values
    NOTE: this only works for the context we currently have, as it only descends down
    the first subdict in each dictionary recursively, so that it is possible that the key
    is in one of the dictionaiers, that gets never visited
    """
    if not key in nested_dict:
        for subdict in nested_dict.values():
            if not hasattr(subdict, '__iter__'):
                continue
            return get_val(subdict, key)
    else:
        return nested_dict[key]

    # the recursion has fallen through here, the key was nowhere to be found in
    # the nested dict (resp. not in the ones we looked at)
    return None

def flat_list_tuple(tup_list):
    """
    From a list of tuples containing two elements, return a list of
    tuples, where the first elements is the tuple containing all first
    elemnts of the input list and the second contains one of all
    possible combinations of the items in the second elements of the
    tuple.
    """
    from itertools import product
    fix_funcs, fix_vals = zip(*tup_list) # split apart the fix_funcs and the values

    val_comb_gen = product(*[vals.tolist() for vals in fix_vals])
    return ((fix_funcs, val_comb) for val_comb in val_comb_gen)

def get_bin_centers(x_min, x_max, n_bins):
    """Get the values for the evaluation of the parameters in the bin centers"""
    bin_bounds = np.linspace(x_min, x_max, n_bins + 1)
    return 0.5 * (bin_bounds[1:] + bin_bounds[:-1])

def get_n_scan_points(scan_params):
    """Get the total number of scanning points to scan."""
    n = 1
    for _, vals in scan_params:
        # print(vals)
        n *= vals.shape[0]

    return n

def scan_chi2_params(hist, fit_func, scan_params, par_names):
    """
    Calculate the chisquare value between a histogram and a function
    for specific parameter sets.

    Args:
        hist (ROOT.TH1): The histogram containing the data to be fitted
        func (ROOT.TF1): The function to be fitted to the data.
        scan_params: A list of tuples, where each tuple corresponds to
        one paramter of func. Each tuple has to hold the following
        entries:
            [0] - A function taking a TF1 and a numeric value x, that
            is used to fixed the given parameter to the value x
            (e.g. func.FixParameter(x))
            [1] - All the values that should be tested for this
            parameter as a np.array
        par_names: A dictionary mapping integers to parameter
        names. Must have the same length as scan_params and start at
        0. The names will be used as column names for the returned
        DataFrame
    Returns:
        pandas.DataFrame: A DataFrame containing the values of all
        parameters and the corresponding chi2 value for each possible
        combination of parameter values in the input
    """
    from tqdm import tqdm

    n_params, n_names = len(scan_params), len(par_names)
    if n_params != n_names:
        if n_params < n_names:
            logging.warning('Got {} scan_params but {} par_names. Will ignore '
                           'the superfluous par_names'.format(n_params, n_names))
        else:
            logging.error('Got {} scan_params but only {} par_names. Need the '
                         'same number!'.format(n_params, n_names))

    n_total = get_n_scan_points(scan_params)
    logging.debug('Allocating results array of size {}'.format(n_total))

    # define the maximum number of scan point for which the (faster)
    # list of list approach is used before switching to a more memory
    # efficient numpy.array
    n_max_size = 30 * 1000**2
    if n_total < n_max_size:
        logging.debug('Using list of lists since size is smaller than {}'
                      .format(n_max_size))
        results = [[-1,-1,-1,-1] for _ in xrange(n_total)]
    else:
        logging.debug('Using numpy array, since size is greater than {}'
                      .format(n_max_size))
        results = np.zeros((n_total, 4), dtype=np.float64)

    logging.debug('Scanning {} points in total'.format(n_total))
    for j, (fix_funcs, val_comb) in enumerate(tqdm(flat_list_tuple(scan_params),
                                                   total=n_total, ncols=80)):
        for (i, func) in enumerate(fix_funcs):
            func(fit_func, val_comb[i])
            results[j][i] = val_comb[i]

        results[j][3] = hist.Chisquare(fit_func)

    logging.debug('Scanning done. Creating DataFrame')
    return pd.DataFrame(results, columns=par_names.values() + ['chi2'])


#import serial as sr
from serial import Serial
import matplotlib.pyplot as plt
import numpy as np

s = Serial('COM5',9600)
plt.close()
plt.figure()
plt.ion()
plt.show()

data = np.array([])
i = 0
while i<10000:
    a = s.readline()
    a.decode()
    b = float(a[0:4]);
    data = np.append(data,b)
    plt.cla()
    plt.plot(data)
    plt.pause(0.01)
    i = i+1


import os
from os.path import abspath, join, exists
from sys import argv
from typing import List, Tuple

from constants import *
from database import Database
from task1a import normalize_all_gestures
from task1b import quantize_all_gestures
from task1c import wordify_all_gestures

def parse_inputs(arguments: List) -> Tuple[str, int, int, int]:
    if len(arguments) != 5:
        raise Exception("Run the program as: python3 task1.py dir=<db-dir> w=3 s=2 r=3")
    database_directory = abspath(arguments[1][4:])
    window_length = int(arguments[2][2:])
    shift_length = int(arguments[3][2:])
    resolution = int(arguments[4][2:])
    return database_directory, window_length, shift_length, resolution

if __name__ == "__main__":
    DATABASE_DIRECTORY, WINDOW_LENGTH, SHIFT_LENGTH, RESOLUTION = parse_inputs(argv)
    EXTRA_DIRECTORY = join(DATABASE_DIRECTORY, "extra")
    if not exists(EXTRA_DIRECTORY):
        os.mkdir(EXTRA_DIRECTORY)

    # Task 1a
    raw_gesture_database = Database(DATABASE_DIRECTORY, filenames_ending_with=".csv")
    normalize_all_gestures(raw_gesture_database, extra_directory=EXTRA_DIRECTORY)

    # Task 1b
    normalized_gesture_database = Database(EXTRA_DIRECTORY, filenames_ending_with=NORMALIZED_GESTURE_FILE_SUFFIX)
    quantize_all_gestures(normalized_gesture_database, res=RESOLUTION, mu=MU, sigma=SIGMA,
                          extra_directory=EXTRA_DIRECTORY)

    # Task 1c
    quantized_gesture_database = Database(EXTRA_DIRECTORY, filenames_ending_with=QUANTIZED_GESTURE_FILE_SUFFIX)
    wordify_all_gestures(quantized_gesture_database, window_length=WINDOW_LENGTH, shift_length=SHIFT_LENGTH,
                         output_directory=DATABASE_DIRECTORY, extra_directory=EXTRA_DIRECTORY)


# -*- coding: utf-8 -*-
from datetime import date, datetime, timedelta
from freezegun import freeze_time

from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged

@tagged('post_install', '-at_install')
class TestAccountPaymentItems(AccountTestInvoicingCommon):

    @classmethod
    def setUpClass(cls):
        super().setUpClass()
        cls.bill = cls.create_bill(due_date='2023-03-20')
        cls.late_bill = cls.create_bill(due_date='2023-03-01')
        cls.discount_bill = cls.create_bill(due_date='2023-03-20', discount_days=19)
        cls.late_discount_bill = cls.create_bill(due_date='2023-04-20', discount_days=9)

    @classmethod
    def create_bill(cls, due_date, discount_days=None):
        payment_term = cls.create_payment_term(due_date, discount_days)
        bill = cls.env['account.move'].create({
            'move_type': 'in_invoice',
            'journal_id': cls.company_data['default_journal_purchase'].id,
            'partner_id': cls.partner_a.id,
            'date': '2023-03-15',
            'invoice_date': '2023-03-01',
            'invoice_date_due': due_date,
            'invoice_payment_term_id': payment_term.id,
            'invoice_line_ids': [(0, 0, {
                'product_id': cls.product_a.id,
                'quantity': 1,
                'name': 'product_a',
                'discount': 10.00,
                'price_unit': 100,
                'tax_ids': [],
                'discount_date': date(2023, 3, 1) + timedelta(days=discount_days) if discount_days else False,
                'date_maturity': due_date,
            })]
        })
        bill.action_post()
        return bill

    @classmethod
    def create_payment_term(cls, due_date, discount_days=None):
        due_days = (datetime.strptime(due_date, '%Y-%m-%d').date() - date(2023, 3, 1)).days
        payment_term = cls.env['account.payment.term'].create({
            'name': 'Payment Term For Testing',
            'early_discount': bool(discount_days),
            'discount_days': discount_days if discount_days else False,
            'discount_percentage': 5,
            'line_ids': [
                (0, 0, {
                    'value': 'percent',
                    'value_amount': 100,
                    'delay_type': 'days_after',
                    'nb_days': due_days,
                }),
            ],
        })
        return payment_term

    @freeze_time("2023-03-15")
    def test_payment_date(self):
        self.assertEqual(str(self.bill.line_ids[0].payment_date), '2023-03-20')
        self.assertEqual(str(self.late_bill.line_ids[0].payment_date), '2023-03-01')
        self.assertEqual(str(self.discount_bill.line_ids[0].payment_date), '2023-03-20')
        self.assertEqual(str(self.late_discount_bill.line_ids[0].payment_date), '2023-04-20')

    def test_search_payment_date(self):
        for today, search, expected in [
            ('2023-03-05', '2023-03-01', self.late_bill),
            ('2023-03-05', '2023-03-30', self.bill + self.late_bill + self.discount_bill + self.late_discount_bill),
            ('2023-03-15', '2023-03-01', self.late_bill),
            ('2023-03-15', '2023-03-30', self.bill + self.late_bill + self.discount_bill),
            ('2023-03-25', '2023-03-01', self.late_bill),
            ('2023-03-25', '2023-03-30', self.bill + self.late_bill + self.discount_bill),
            ('2023-03-25', '2023-06-30', self.bill + self.late_bill + self.discount_bill + self.late_discount_bill),
        ]:
            with freeze_time(today):
                self.assertEqual(self.env['account.move.line'].search([
                    ('payment_date', '=', search),
                    ('partner_id', '=', self.partner_a.id),
                ]).move_id, expected)


import uuid
import time

from django.conf import settings

import paho.mqtt.client as mqtt

from device import ampq

def get_id_from_spec_topic(topic):
    matches, args = match_topic(settings.MQTT_DEVICE_SPEC_TOPIC, topic)
    raise_if(
        len(args) != 1,
        'Spec should have a single parameter which is the device id')

    return args[0]

def raise_if(cond, msg=None, exception=ValueError):
    if bool(cond):
        params = [msg] if msg else []
        raise ValueError(*params)

def match_topic(raw_topic, to_match):
    '''
    Matches a topic to a raw topic
    Returns a a boolean that indicates if the topics match and a list
    with all the arguments that were send (instead of +)
    '''
    if '+' not in raw_topic:
        return raw_topic == to_match

    raw_topic_split = raw_topic.split('/')
    to_match_split = to_match.split('/')

    if len(raw_topic_split) != len(to_match_split):
        return False, []

    args = []
    for raw, match in zip(raw_topic_split, to_match_split):
        if raw == '+':
            args.append(match)
        elif raw != match:
            return False, []

    return True, args

def build_topic(raw_topic, args):
    raise_if(
        raw_topic.count('+') != len(args),
        'Different number of args than topic has')

    if '+' not in raw_topic:
        return raw_topic

    return raw_topic.replace('+', '{}').format(*args)

def get_ack_token(client_id, mid):
    return '{}-{}'.format(client_id, mid)

def send_message_from_api(topic, args, payload, timeout=0.7,
                          wait_for_received=True):
    '''
    Not the best implementation of this buut...it will do for now, I guess

    This has to be modified to be making use of QoS or some unique  identifier
    Concurrent messages to the same device may receive ack from one another.
    '''
    was_published = []
    was_recv = []

    def on_publish(client, userdata, mid):
        was_published.append(True)

    def on_msg(client, userdata, msg):
        if msg.payload == '+':
            was_recv.append(True)

    def ack_done():
        return (
            was_published and
            was_recv or not wait_for_received
        )

    mqtt_client = mqtt.Client(str(uuid.uuid4())[:16])
    mqtt_client.on_publish = on_publish
    mqtt_client.on_message = on_msg
    mqtt_client.connect(
        settings.MQTT_SERVER, settings.MQTT_PORT, settings.MQTT_KEEPALIVE)
    mqtt_client.subscribe(settings.MQTT_DEVICE_ACK_TOPIC)

    result, mid = mqtt_client.publish(build_topic(topic, args), payload)

    if result:
        return False

    counter = 0
    while not ack_done() and counter < timeout:
        mqtt_client.loop(timeout=0.07)
        counter += 0.07

    mqtt_client.disconnect()

    return (
        (was_published and was_published[0]) and
        (was_recv or not wait_for_received))


import logging
import werkzeug

from odoo import http
from odoo.http import request
from odoo.tools.translate import _
from odoo.tools.misc import get_lang

_logger = logging.getLogger(__name__)

MAPPED_RATES = {
    1: 1,
    5: 3,
    10: 5,
}

class Rating(http.Controller):

    @http.route('/rate/<string:token>/<int:rate>', type='http', auth="public", website=True)
    def action_open_rating(self, token, rate, **kwargs):
        if rate not in (1, 3, 5):
            raise ValueError(_("Incorrect rating: should be 1, 3 or 5 (received %d)"), rate)

        rating, record_sudo = self._get_rating_and_record(token)

        record_sudo.rating_apply(
            rate,
            rating=rating,
            feedback=_('Customer rated %r.', record_sudo.display_name),
            subtype_xmlid=None,
            notify_delay_send=True,
        )

        lang = rating.partner_id.lang or get_lang(request.env).code
        return request.env['ir.ui.view'].with_context(lang=lang)._render_template('rating.rating_external_page_submit', {
            'rating': rating,
            'token': token,
            'rate_names': {
                5: _("Satisfied"),
                3: _("Okay"),
                1: _("Dissatisfied"),
            },
            'rate': rate,
        })

    @http.route(['/rate/<string:token>/submit_feedback'], type="http", auth="public", methods=['post', 'get'], website=True)
    def action_submit_rating(self, token, rate=0, **kwargs):

        rating, record_sudo = self._get_rating_and_record(token)
        if request.httprequest.method == "POST":
            rate = int(rate)
            if rate not in (1, 3, 5):
                raise ValueError(_("Incorrect rating: should be 1, 3 or 5 (received %d)"), rate)
            record_sudo.rating_apply(
                rate,
                rating=rating,
                feedback=kwargs.get('feedback'),
                subtype_xmlid=None,  # force default subtype choice
            )

        lang = rating.partner_id.lang or get_lang(request.env).code
        return request.env['ir.ui.view'].with_context(lang=lang)._render_template('rating.rating_external_page_view', {
            'web_base_url': rating.get_base_url(),
            'rating': rating,
        })

    def _get_rating_and_record(self, token):
        rating_sudo = request.env['rating.rating'].sudo().search([('access_token', '=', token)])
        if not rating_sudo:
            raise werkzeug.exceptions.NotFound()

        record_sudo = request.env[rating_sudo.res_model].sudo().browse(rating_sudo.res_id)
        if not record_sudo.exists():
            raise werkzeug.exceptions.NotFound()
        return rating_sudo, record_sudo


import sys

def is_palindrome(n):
	n_str=str(n)
	flag = True
	_len = len(n_str)
	for i in range(_len/2):
		if n_str[i]!=n_str[_len-i-1]:
			flag = False
			break
	return flag

def main():
	r=filter(is_palindrome,range(1,1000))
	for i in r:
		print(i)
if __name__ == '__main__':
	main()


#import modules
from turtle import title
from bs4 import BeautifulSoup
import csv

#Importing report file (HTML)
html = open(r"C:\Users\sjak3\Desktop\JAKK3LAB\DEV\BIM\4D\1_ClashDetectiveSelector\0-2_ReportFile\1_레이커-보+기둥.html", 'r', encoding='UTF8')

#Set the CSV File form. File should not have any blank rows(newline='').
csvFile = open('Report.csv', "w", newline='',encoding="utf-8-sig")

#Set object as 'soup'
soup = BeautifulSoup(html, "html.parser")

#Every clash is divided by 'div' tag, whose class value is 'viewpoint'
div_clash = soup.find_all('div', class_='viewpoint')

#For counting the number of loop
list_count =len(div_clash)
clashSets = []

for i in range(0, list_count):
    #Between 'div' tags, 'span' tags contain the information of each elements.
    clashTags = div_clash[i].find_all('span', class_='value')

    #In my case, clash number is on the index '0', first object's ID on '6', second object on '13'
    clashSets.append([clashTags[0].get_text(), clashTags[6].get_text(), clashTags[13].get_text()])

#Write on CSV File
csvFileW = csv.writer(csvFile)

#Set the field at the first row.
csvFileW.writerow(["간섭번호", "개체1", "개체2"])

#Add all clash informations.
for i in range(0, len(clashSets)):
    csvFileW.writerow(clashSets[i])

csvFile.close()


import matplotlib.pyplot as plt
import mxnet as mx
import numpy as np
import cv2
import sys
import re
import mxnet.ndarray as nd
from config import cfg
# from guided_filter.core import filters
from mxnet.ndarray import NDArray, zeros, clip, sqrt
import math
import os

def flow2color(flow):
    """
        plot optical flow
        optical flow have 2 channel : u ,v indicate displacement
    """
    hsv = np.zeros(flow.shape[:2]+(3,)).astype(np.uint8)
    hsv[..., 1] = 255
    mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])
    hsv[..., 0] = ang*180/np.pi/2
    hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX)
    rgb = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR)

    plt.figure()
    plt.imshow(rgb)
    plt.title('optical flow')

def estimate_label_size(net, batch_shape):
    """
        estimate label shape given by input shape
    """
    args = dict(zip(net.list_outputs(), net.infer_shape(img1=batch_shape, img2=batch_shape)[1]))
    shapes = []
    for key in args:
        shapes.append(args[key][2:])
    shapes = sorted(shapes, key=lambda t: t[0], reverse=True)
    return shapes

def init_param(scale, args):
    """
        initialize parameters
    """
    init = mx.initializer.Normal(sigma=scale)
    for key in args:
        if 'img1' not in key and 'img2' not in key and 'flow' not in key and 'stereo' not in key:
            if 'bias' in key:
                args[key][:] = 0.0
            else:
                init(key,args[key])

def load_checkpoint(prefix, epoch, net, batchsize):

    save_dict = nd.load('%s-%04d.params' % (prefix, epoch))
    names_arg = net.list_arguments()
    names_aux = net.list_auxiliary_states()

    shapes = net.infer_shape(img1left_data = batchsize, img1right_data=batchsize,
                            img2left_data = batchsize, img2right_data=batchsize)
    args = dict(zip(names_arg, shapes[0]))
    auxs = dict(zip(names_aux, shapes[2]))
    arg_params = {}
    aux_params = {}

    for k, v in save_dict.items():
        tp, name = k.split(':', 1)
        if tp == 'arg' and name in names_arg:
            arg_params[name] = v
        if tp == 'aux' and name in names_aux:
            aux_params[name] = v

    init = mx.init.Xavier(rnd_type='gaussian',factor_type='in',magnitude=4)
    for name in names_arg:
        if 'data' not in name and 'label' not in name:
            if name not in arg_params:
                arg_params[name] = nd.zeros(args[name])
                init(name,arg_params[name])
    for name in names_aux:
        if name not in aux_params:
            aux_params[name] = nd.zeros(auxs[name])

    return arg_params,aux_params

def load_model(name, epoch, net, batch_shape, ctx, network_type='write'):
    """
        load parameter trained before and simple bind
        return executor
    """
    data_sym = ['img1', 'img2']
    args,aux = load_checkpoint(name, epoch)

    executor = net.simple_bind(ctx=ctx, grad_req=network_type, img1=batch_shape, img2=batch_shape)
    init = mx.init.Orthogonal(scale=cfg.MODEL.weight_init_scale, rand_type='normal')

    for key in executor.arg_dict:
        if key in data_sym or 'stereo' in key or 'flow' in key:
            executor.arg_dict[key][:] = mx.nd.zeros((executor.arg_dict[key].shape), ctx)
        else:
            if key in args:
                executor.arg_dict[key][:] = args[key]
            else:
                init(key, executor.arg_dict[key])

    for key in executor.aux_dict:
        executor.aux_dict[key][:] = aux[key]

    return executor

def readPFM(file):
    """
        read .PFM file
    """

    file = open(file, 'rb')

    color = None
    width = None
    height = None
    scale = None
    endian = None

    header = file.readline().rstrip()
    if header == 'PF':
        color = True
    elif header == 'Pf':
        color = False
    else:
        raise Exception('Not a PFM file.')

    dim_match = re.match(r'^(\d+)\s(\d+)\s$', file.readline())
    if dim_match:
        width, height = map(int, dim_match.groups())
    else:
        raise Exception('Malformed PFM header.')

    scale = float(file.readline().rstrip())
    if scale < 0:  # little-endian
        endian = '<'
        scale = -scale
    else:
        endian = '>'  # big-endian

    data = np.fromfile(file, endian + 'f')
    shape = (height, width, 3) if color else (height, width)

    data = np.reshape(data, shape)
    data = np.flipud(data)

    return data, scale

def writePFM(file, image, scale=1):
    """
        write .PFM file
    """
    file = open(file, 'wb')
    color = None
    if image.dtype.name != 'float32':
        raise Exception('Image dtype must be float32.')
    image = np.flipud(image)
    if len(image.shape) == 3 and image.shape[2] == 3:  # color image
        color = True
    elif len(image.shape) == 2 or len(image.shape) == 3 and image.shape[2] == 1: # greyscale
        color = False
    else:
        raise Exception('Image must have H x W x 3, H x W x 1 or H x W dimensions.')
    file.write('PF\n' if color else 'Pf\n')
    file.write('%d %d\n' % (image.shape[1], image.shape[0]))
    endian = image.dtype.byteorder
    if endian == '<' or endian == '=' and sys.byteorder == 'little':
        scale = -scale
    file.write('%f\n' % scale)
    image.tofile(file)

def outlier_sum(pred,gt,tau=3):
    """
        residual > 3  and   residual / gt > 0.05   (defined by kitti)
    """
    outlier = np.zeros(gt.shape)
    mask = gt > 0
    gt = np.round(gt[mask])
    pred = pred[mask]
    err = np.abs(pred-gt)
    outlier[mask] = err

    return (err[err>tau]/(gt[err>tau].astype(np.float32)+1) > 0.05).sum()/float(mask.sum()),outlier

def plot_velocity_vector(flow):

    img = np.ones(flow.shape[:2]+(3,))
    for i in range(0,img.shape[0]-20,30):
        for j in range(0,img.shape[1]-20,30):
            try:
                # opencv 3.1.0
                if flow.shape[-1] == 2:
                    cv2.arrowedLine(img,(j,i),(j+int(round(flow[i,j,0])),i+int(round(flow[i,j,1]))),(150,0,0),2)
                else:
                    cv2.arrowedLine(img, (j, i), (j + int(round(flow[i, j, 0])), i ), (150, 0, 0), 2)

            except AttributeError:
                # opencv 2.4.8
                if flow.shape[-1] == 2:
                    cv2.line(img, (j, i), (j + int(round(flow[i, j, 0])), i + int(round(flow[i, j, 1]))), (150, 0, 0), 2)
                else:
                    cv2.line(img,pt1 =  (j, i),pt2= (j + int(round(flow[i, j])), i), color = (150, 0, 0),thickness =  1)

    plt.figure()
    plt.imshow(img)
    plt.title('velocity vector')

def weight_median_filter(i, left, radius, epsilon, mask):
    """
       Constant Time Weighted Median Filtering for Stereo Matching and Beyond
    """
    dispin  = i.copy()
    dispout = dispin.copy()
    dispout[mask] = 0
    vecdisp = np.unique(dispin)

    tot = np.zeros(i.shape)
    imgaccum = np.zeros(i.shape)

    gf = filters.GuidedFilterColor(left.copy(), radius, epsilon)

    for d in vecdisp:
        if d<=0:
            continue
        ab = gf._computeCoefficients((dispin==d).astype(float))
        weight = gf._computeOutput(ab, gf._I)
        tot = tot + weight

    for d in vecdisp:
        if d<=0:
            continue
        ab = gf._computeCoefficients((dispin==d).astype(float))
        weight = gf._computeOutput(ab, gf._I)
        imgaccum = imgaccum + weight
        musk =  (imgaccum > 0.5*tot) & (dispout==0) & (mask) & (tot> 0.0001)
        dispout[musk] = d

    return dispout

def get_imageRecord(dataset,batchsize,prefetch_buffer):

    data_type = dataset.data_type

    if data_type == 'flow':
        raise ValueError('do not support flow data')

    records = []
    for index,i in  enumerate(['img1','img2','label']):

        if not os.path.exists(cfg.record_prefix+'{}_{}_{}.rec'.format(dataset.name(),data_type,i)):

            df = pd.DataFrame(dataset.dirs)
            df[index].to_csv(cfg.record_prefix + '{}_{}_{}.lst'.format(dataset.name(),data_type,i),sep='\t',header=False)
            args = ['python','im2rec.py',cfg.record_prefix +'{}_{}_{}'.format(dataset.name(),data_type,i) ,\
                        '--root','','--resize','0','--quality','0','--num_thread','1','--encoding', '.png']
            subprocess.call(args)

        records.append(mx.io.ImageRecordIter(
                      path_imgrec = cfg.record_prefix+'{}_{}_{}.rec'.format(dataset.name(),data_type,i),
                      data_shape = dataset.shapes(),
                      batch_size = batchsize,
                      preprocess_threads = 3,
                      prefetch_buffer = prefetch_buffer,
                      shuffle = False))
    return records

def get_gradreq(net):

    grad_req = {}
    for key in net.list_arguments():
        if 'data' in key or 'label' in key:
            grad_req[key] = 'null'
        else:
            grad_req[key] = 'write'
    return grad_req

class Adam(mx.optimizer.Optimizer):

    def __init__(self, learning_rate=0.001, beta1=0.9, beta2=0.999, epsilon=1e-8,
                 decay_factor=(1 - 1e-8), **kwargs):
        super(Adam, self).__init__(learning_rate=learning_rate, **kwargs)
        self.beta1 = beta1
        self.beta2 = beta2
        self.epsilon = epsilon
        self.decay_factor = decay_factor

    def create_state(self, index, weight):

        return (zeros(weight.shape, weight.context, dtype=weight.dtype),  # mean
                zeros(weight.shape, weight.context, dtype=weight.dtype))  # variance

    def update(self, index, weight, grad, state):

        assert(isinstance(weight, NDArray))
        assert(isinstance(grad, NDArray))
        lr = self._get_lr(index)
        self._update_count(index)

        t = self._index_update_count[index]
        mean, variance = state

        grad *= self.rescale_grad
        if self.clip_gradient is not None:
            clip(grad, -self.clip_gradient, self.clip_gradient, out=grad)

        mean[:] = self.beta1 * mean + (1. - self.beta1) * grad
        variance[:] = self.beta2 * variance + (1. - self.beta2) * grad * grad

        coef1 = 1. - self.beta1**t
        coef2 = 1. - self.beta2**t
        lr *= math.sqrt(coef2)/coef1

        weight[:] -= lr*mean/(sqrt(variance) + self.epsilon)

        wd = self._get_wd(index)
        if wd > 0.:
            weight[:] -= (lr * wd) * weight

def get_idx2name(net):
    """
        get gradiant requirement
    """
    idx2name = {}
    arg_name = net.list_arguments()
    param_name = [key for key in arg_name if 'data' not in key and 'label' not in key]
    for i,name in enumerate(param_name):
        idx2name[i] = name

    return idx2name


import networkx as nx
import matplotlib.pyplot as plt

def visualize_graph(graph):
    G = nx.Graph()

    # Add vertices to the graph
    for vertex in graph.get_vertices():
        G.add_node(vertex)

    # Add edges to the graph
    for src, dest in graph.get_edges():
        G.add_edge(src, dest)

    # Position nodes using spring layout
    pos = nx.spring_layout(G, seed=42)

    # Draw the graph with labels and edge weights (if any)
    nx.draw(G, pos, with_labels=True, node_size=1000, node_color='skyblue', font_size=10, font_weight='bold')

    # Add edge labels if the graph is weighted
    edge_labels = {(src, dest): f"{src}-{dest}" for src, dest in graph.get_edges()}
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)

    # Show the graph
    plt.title("Graph Visualization")
    plt.show()

# Example usage:
if __name__ == "__main__":
    graph = Graph()
    graph.add_edge("A", "B")
    graph.add_edge("A", "C")
    graph.add_edge("B", "C")
    graph.add_edge("C", "D")

    visualize_graph(graph)


# if 语句基本案例
# @Time    : 2020/7/19 11:18
# @Author  : yhqian
# @File    : IfBasics.py

# 单向判断: 将两个数 num1 和 num2 按降序排列
num1, num2 = 1, 9
if num1 < num2:
    # t = num1
    # num1 = num2
    # num2 = t
    num1, num2 = num2, num1
print(num1, num2)

# 双向判断: 判断一个数的奇偶性
number = 8
if number % 2 == 0:
    print(number, "是偶数")
else:
    print(number, "是奇数")

# 多重判断：将百分制成绩转换为A,B,C,D,F五个等级
score = 87
if score >= 90:
    grade = 'A'
elif score >= 80:
    grade = 'B'
elif score >= 70:
    grade = 'C'
elif score >= 60:
    grade = 'D'
else:
    grade = 'F'
print(score, " grade is " + grade)


import numpy as np
from Common import fft
from Common import fourier_transform

def zero_padding(x, h):
    """
    Function that zero pads the smallest input signal.

    Attributes:
    x(numpy array): Array of numbers representing an input signal.
    h(numpy array): Array of numbers representing an input signal.

    Returns:
    x_pad(numpy array): Array of numbers representing an input signal x padded with zeros.
    h_pad(numpy array): Array of numbers representing an input signal h padded with zeros.
    """
    N = x.shape[0]
    M = h.shape[0]

    if(M<N):
        h_pad = np.append(h,np.zeros((N-M,1)), axis=0)
        x_pad = x
    elif(M>N):
        x_pad = np.append(x,np.zeros((N-M,1)), axis=0)
        h_pad = h
    else:
        x_pad = x
        h_pad = h

    return x_pad, h_pad

def zero_pad_fourier(x, M, method='FFT', L=1024):
    """
    Function to zero pad and calculate the Fourier Transform of a given signal. This function gives a "better
    resolution" when plotting our Fourier Transformations.
    :param x: (numpy array)  input signal to perform it's Fourier Transform.
    :param M: (int) Length of the filter kernel. Usually M = 4/BW, where BW is the filter
            bandwidth of the transition band.
    :param method: (string) method to use for calculating the Fourier Transform, can be 'FFT'
            for Fast Fourier Transform or 'DFT' for Discrete Fourier Transform.
    :param L: (int) new size of signal x.
    :return: X: (numpy array) Fourier Transform of input signal x.
             f: (numpy array) normalized frequency between 0 and 0.5.
    """

    return None

def zero_pad(x, M, L=1024):
    """
    Function to zero pad a signal x to have a size of L.
    :param x: (numpy array)  input signal to perform pad with zeros.
    :param M: (int) Length of the filter kernel. Usually M = 4/BW, where BW is the filter
            bandwidth of the transition band.
    :param L: (int) new size of signal x.
    :return: (numpy array) input signal padded with zeros. Number of padded zeros is L-M.
    """

    return None


import mybme680
import time
import csv

# Declare Filename
EXPERIMENT_NOMENCLATURE = 'BME_calibration'
# Declare CSV Header
CSV_HEADER = ['TIME', 'TEMPERATURE_IN_BME', 'TEMPERATURE_OUT_BME', 'TEMPERATURE_C_BME', 'PRESSURE_IN_BME ', 'PRESSURE_OUT_BME', 'PRESSURE_C_BME', 'HUMIDITY_IN_BME', 'HUMIDITY_OUT_BME', 'HUMIDITY_C_BME']

# Data is only written in mode 'a', so that file cannot be overwritten
with open('/home/shojsepter/dev/log/%s.csv' %EXPERIMENT_NOMENCLATURE , 'a') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    writer.writerow(CSV_HEADER)

while True:

    bme680_IN_t, bme680_IN_p, bme680_IN_h = mybme680.get_bme680_values("BME_IN")
    bme680_OUT_t, bme680_OUT_p, bme680_OUT_h = mybme680.get_bme680_values("BME_OUT")
    bme680_C_t, bme680_C_p, bme680_C_h = mybme680.get_bme680_values("BME_CHAMBER")

    with open('/home/shojsepter/dev/log/%s.csv' %EXPERIMENT_NOMENCLATURE , 'a') as csvfile:
        # create the csv writer
        writer = csv.writer(csvfile, delimiter=',')
        # write a row to the csv file
        # Compare with header: CSV_HEADER = ['TIME', 'TEMPERATURE_IN_BME', 'TEMPERATURE_OUT_BME', 'PRESSURE_IN_BME ', 'PRESSURE_OUT_BME', 'HUMIDITY_IN_BME', 'HUMIDITY_OUT_BME','HUMIDITY_OUT_SCD', 'AIRFLOW_OUT_SFM', 'CO2_OUT_SCD']
        writer.writerow([time.ctime(), bme680_IN_t, bme680_OUT_t, bme680_C_t, bme680_IN_p, bme680_OUT_p, bme680_C_p, bme680_IN_h, bme680_OUT_h, bme680_C_h])
        print("wrote to file...")
        time.sleep(1)


#!/usr/bin/env python3
"""Smart MarketData

Usage:
    ./smart_md.py <IP> <PORT> <INTERVAL> <INSTRUMENTS>

"""

import asyncio
import datetime as dt
import docopt
import logbook
import time
from convex.market_data import Subscriber as MDSubscriber
from convex.common.instrument import instruments_lookup
from convex.strategy_utils.utils import weighted_midpoint

import aiohttp
import aiohttp.web
import json
from pprint import pprint

from convex.strategy_utils.utils import json_serial
from convex.exchanges import gdax

log = logbook.Logger('SmartMD')

class WebServer:
    def __init__(self, message_cb):
        self.cb = message_cb
        pass

    async def init(self, loop, ip, port):
        self._app = aiohttp.web.Application(loop=loop)
        self._app['sockets'] = set()
        self._app.router.add_get('/ws', self.socket_handler)
        self._handler = self._app.make_handler()

        self._srv = await loop.create_server(self._handler, ip, port)
        self._session = aiohttp.ClientSession()

        log.info('Running web server at {}:{}', ip, port)

    async def add_handler(self, instrument, topic):
        if instrument not in self._app:
            self._app[instrument] = {}
            if topic not in self._app[instrument]:
                self._app[instrument][topic] = set()

    async def broadcast_msg(self, name, msg_type, msg):
        resp = {name: {'type': msg_type, 'msg': msg}}
        await self.send_str(json.dumps(resp))

    async def broadcast(self, instrument, msg_type, value):
        json_msg = json.dumps(value,
                              separators=(',', ': '),
                              default=json_serial)

        for ws in self._app[instrument][msg_type]:
            await ws.send_str(json_msg)

    async def send_str(self, data):
        for ws in self._app['sockets']:
            await ws.send_str(data)

    def _on_request(self, ws, req, subscriptions):
        try:
            req_type = req['type']
            value = req['value']
            instrument = req['instrument']
            name = req['name']

            if req_type == 'subscribe':
                log.info('{} subscribing to {} for instrument {}'.format(
                    name, value, instrument))
                self._subscribe(ws, instrument, value)
                subscriptions.add((instrument, value))
            elif req_type == 'unsubscribe':
                log.info('{} unsubscribing to {} for instrument {}'.format(
                    name, value, instrument))
                self._unsubscribe(ws, instrument, value)
                subscriptions.discard((instrument, value))
            else:
                log.warning(
                    'Unhandled type: {}, val: {}, instr: {}, name: {}.'.format(
                        req_type, value, instrument, name))
        except Exception as e:
            log.exception('Msg missing required fields: {}'.format(req))

    def _subscribe(self, ws, instrument, value):
        if value == 'weighted_mid':
            try:
                self._app[instrument][value].add(ws)
                ws.send_str(json.dumps({'type': 'ack', 'value': 'succeeded'}))
            except KeyError:
                ws.send_str(
                    json.dumps({'type': 'ack', 'value': 'unsupported'}))
        else:
            ws.send_str(
                json.dumps({'type': 'ack', 'value': 'topic_not_available'}))

    def _unsubscribe(self, ws, instrument, value):
        if instrument in self._app:
            if value in self._app[instrument]:
                self._app[instrument][value].discard(ws)
                ws.send_str(json.dumps({'type': 'ack', 'value': 'succeeded'}))
                return
            ws.send_str(
                json.dumps({'type': 'ack', 'value': 'topic_not_available'}))

    async def socket_handler(self, request):
        ws = aiohttp.web.WebSocketResponse()
        ok, protocol = ws.can_prepare(request)
        if not ok:
            return aiohttp.web.Response(text='Somthing went wrong')

        await ws.prepare(request)

        request.app['sockets'].add(ws)

        subscriptions = set()
        try:
            async for msg in ws:
                if msg.type == aiohttp.WSMsgType.TEXT:
                    try:
                        req = json.loads(msg.data)
                        self._on_request(ws, req, subscriptions)

                    except Exception as e:
                        log.exception('Unexpected Error: {}', e)
                        await ws.close()
                elif msg.type == aiohttp.WSMsgType.ERROR:
                    log.info('Conn closed w/ exception: {}', ws.exception())
                    await ws.close()
        finally:
            request.app['sockets'].discard(ws)
            for sub in subscriptions:
                self._app[sub[0]][sub[1]].discard(ws)

        return ws

class SmartMD:
    def __init__(self, loop=None):
        if loop:
            self._loop = loop
        else:
            self._loop = asyncio.get_event_loop()

        self._interval = 1
        self._instrument = None

    async def _launch_market_data(self, md):
        await md.launch()
        await md.request_shutdown()

    async def _start_web_server(self):
        self._web_server = WebServer(self._on_web_msg)

    async def run(self, params):
        await self._start_web_server()

        self._interval = int(params['interval'])
        self._instruments = [
            instruments_lookup[instrument]
            for instrument in params['instruments']
        ]

        self._instr_str = str(self._instrument)

        await self._web_server.init(self._loop,
                                    params['web']['ip'],
                                    params['web']['port'])

        # Start Market Data
        md_gateways = set()
        subscribers = set()
        for instrument in self._instruments:
            md_gw = gdax.MDGateway(loop=self._loop)
            md_gateways.add(md_gw)

            subscribers.add(
                MDSubscriber(instrument, gateway=md_gw))

            await self._web_server.add_handler(str(instrument), 'weighted_mid')

        tasks = []
        for md_gw in md_gateways:
            tasks.append(
                asyncio.ensure_future(self._launch_market_data(md_gw)))

        for sub in subscribers:
            tasks.append(
                asyncio.ensure_future(
                    self._poll_sub(sub, self._web_server)))

        self._future_tasks = asyncio.ensure_future(
                asyncio.gather(*tasks, loop=self._loop))

        try:
            await self._future_tasks
        except asyncio.CancelledError:
            pass

    async def _poll_sub(self, sub, web_server):
        instrument = str(sub.instrument)

        log.info('Starting polling for instrument: {}'.format(instrument))
        await asyncio.sleep(3)

        while True:
            update = await sub.fetch()
            await self._on_market_data(instrument, update)
            await asyncio.sleep(self._interval)

    async def _on_market_data(self, instrument, update):
        await self._broadcast(instrument, 'weighted_mid', {
                'ts': int(time.mktime(update.timestamp.timetuple())*1000),
                'instr': instrument,
                'price': weighted_midpoint(update.book)
            }
        )

    async def _broadcast(self, instrument, msg_type, value):
        await self._web_server.broadcast(instrument, msg_type, value)

    async def _on_web_msg(self, msg):
        pass

def main(args):
    loop = asyncio.get_event_loop()
    smart_md = SmartMD(loop)

    instruments = args['<INSTRUMENTS>'].split(',')
    params = {
                'web': {
                    'ip': args['<IP>'],
                    'port': args['<PORT>']
                },
                'instruments': instruments,
                'interval': args['<INTERVAL>']
            }

    log.info(
        'Starting Smart MarketData for {} with interval.',
        instruments, params['interval'])

    try:
        loop.run_until_complete(smart_md.run(params))
    except KeyboardInterrupt:
        log.info('Keybaord Interrupt - Shutting down Smart Market Data')

        # Cancel all running tasks
        for t in asyncio.Task.all_tasks():
            try:
                t.exception()
            except Exception:
                log.exception('Exception during shutdown: {}', t)
    finally:
        loop.close()

if __name__ == '__main__':
    with logbook.FileHandler(
            'logs/smart_md.log'.format(
                dt.datetime.today()), level=logbook.INFO).applicationbound():
        args = docopt.docopt(__doc__)
        main(args)


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

# In[1]:

import numpy as np
import pandas as pd
import cv2
from matplotlib import pyplot as plt

# In[2]:

def load_images(train):

    # This function loads the images, resizes them and puts them into an array

    img_size = 448
    train_image = []
    counter = 0
    for name in train['image_id']:
        counter += 1
        if (counter % 100 == 0):
            print('we have loaded', counter , 'images')
        path = directory + 'images/' + name + '.jpg'
        img = cv2.imread(path)
        image = cv2.resize(img, (img_size, img_size))
        train_image.append(image)
    train_image_array = np.array(train_image)

    return train_image_array

# In[3]:

def show_distribution():
    n_healthy = sum(df_train['healthy'])
    n_multiple = sum(df_train['multiple_diseases'])
    n_rust = sum(df_train['rust'])
    n_scab = sum(df_train['scab'])

    print('Number of Healthy images:', n_healthy)
    print('Number of Multiple_diseases images:', n_multiple)
    print('Number of Rust images:', n_rust)
    print('Number of Scab images:', n_scab)

    distribution_dictionary = {'healthy' : n_healthy,
                               'multiple_diseases' : n_multiple,
                               'rust' : n_rust,
                               'scab' : n_scab}

    return distribution_dictionary

# In[4]:

def append_dataframe(df_train, name, train_add):
    # This functions append to the dataframe the new image's labels

    max_len = len(df_train)

    for i in range(0, len(train_add)):
        data = {'image_id' : 'Train_' + str(max_len + i),
                'healthy' : [0],
                'multiple_diseases' : [0],
                'rust' : [0],
                'scab' : [0]}
        df_new = pd.DataFrame(data)
        df_new[name] = 1
        df_train = df_train.append(df_new)

    return df_train

# In[5]:

def append_images(name, add_images):

    train_add = train_img.copy()

    if name == 'rust': # Don't add anything
        print('rust')

    elif name == 'multiple_diseases': # Add 4 times the amount of images and more
        for i in range(0,4):
            train_add = np.concatenate((train_add, train_img))
        train_add = np.concatenate((train_add, train_img[0:76]))

    else: # Add the needed amount.
        train_add = train_img[0:add_images]

    return train_add

# In[6]:

def write_images(train_img, len_previous):

    for i in range(0, len(train_img)):
        img_name = 'Train_' + str(len_previous + i) + '.jpg'
        cv2.imwrite(directory + 'images/' + img_name, train_img[i])

# In[7]:

directory = ''
df_train = pd.read_csv(directory + 'train.csv')

# ## Multiple_diseases augmentation

# In[9]:

names = ['healthy', 'multiple_diseases', 'rust', 'scab']
distr_dict = show_distribution()
print()

for name in names:
    if name == 'rust':
        print('Russt!')

    else:
        df_len_previous = len(df_train)

        train_img = load_images(df_train)
        print()
        train_img = train_img[df_train[name] == 1] # Takes the images of the label
        n_samples = distr_dict[name] # Takes the number of samples of that images

        add_images = distr_dict['rust'] - n_samples # The amount of images we have to add
        print('images we have to add:', add_images)

        train_add = append_images(name, add_images)

        df_train = append_dataframe(df_train, name, train_add)

        write_images(train_add, df_len_previous)

df_train

# In[10]:

df_train.to_csv(directory + 'train_modified.csv')


import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from sklearn import neighbors

def training():
	n_train = 150
	validation_error = [0] * 151
	trainingG = list()
	testG 	= list()
	latlon1 = list()
	latlon2 = list()
	zone1 	= list()
	zone2 	= list()
	with open('data/2006/zones_random_60.csv', 'r') as training_group:
		with open('data/2006/zones_random_40.csv', 'r') as test_group:
			for aux_train in training_group:
				chain1 = aux_train.split(";")
				trainingG = [chain1[0],chain1[1],chain1[2]]
				data_latlon1=[chain1[0],chain1[1]]
				data_zone1=[chain1[2].replace("\n", "")]
				latlon1.append(data_latlon1)
				zone1.append(data_zone1)
			for aux_test in test_group:
				chain2 = aux_test.split(";")
				testG = [chain2[0],chain2[1],chain2[2]]
				data_latlon2 = [chain2[0],chain2[1]]
				data_zone2=[chain2[2].replace("\n", "")]
				latlon2.append(data_latlon2)
				zone2.append(data_zone2)

	for n_neighbors in range(1,151):
		clf = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
		clf.fit(latlon1, zone1)
		Z = clf.predict(latlon2)
		aux = 0
		for i in range(len(zone2)):
			if(zone2[i] != Z[i]):
				aux += 1

		error = aux / len(zone2)

		validation_error[n_neighbors] += error
		temp = list(map(lambda x : x / n_train, validation_error))
		validation_error=temp

	plt.title('Selection of best K (distance)')
	plt.ylabel('Error')
	plt.xlabel('K')
	plt.xlim(1, 200)
	plt.ylim(-0.002,0.002)
	plt.plot(validation_error)
	plt.show()

	K = len(validation_error) - list(reversed(validation_error)).index(min(validation_error[1:])) - 1
	print ('Best K is: %d' % K)

	latitudes = list()
	longitudes = list()
	latitude_longitude = list()
	zone = list()

	with open('data/2006/zones.csv', 'r') as latlonzon:
		for aux in latlonzon:
			cad = aux.split(";")
			latitudeAux = [cad[0]]
			longitudeAux = [cad[1]]
			latitude_longitudeAux = [cad[0],cad[1]]
			zoneAux = [cad[2].replace("\n", "")]
			latitudes.append(latitudeAux)
			longitudes.append(longitudeAux)
			latitude_longitude.append(latitude_longitudeAux)
			zone.append(zoneAux)

	latitudes2 = list()
	longitudes2 = list()
	for line in open('out/datos2007_latlon.csv').readlines():
		line_split = line.split(";")
		latitudes2.append(line_split[0])
		longitudes2.append(line_split[1])

	clf_works = neighbors.KNeighborsClassifier(K, weights='distance')
	clf_works.fit(latitude_longitude, zone)
	Z = clf_works.predict(np.c_[latitudes2, longitudes2])

	Z_vector = [x for x in Z]

	with open('out/datos2007_latlon.csv', 'r') as works_in:
		with open('out/datos2007_with_zones.csv','w') as works_out:

			counter = 0
			works_out.write("Latitude;Longitude;Zone\n")
			for line in works_in:
				line_out = line[:-1] + ';' + Z_vector[counter] + "\n"
				works_out.write(line_out)
				counter += 1

	# Generar un CSV con los datos de 2007 + las zonas calculadas en el knn
	with open('data/datos2007filt.csv', 'r') as works_in:
	    with open('data/datos2007filt_with_zones.csv','w') as works_out:
	        counter = 0
	        for line in works_in:
	            line_out = line[:-1] + ';' + Z_vector[counter] + "\n"
	            works_out.write(line_out)
	            counter += 1

training()

Milestone8 - workroads analysis/src/knn.py


def common_ele(list1, list2):
    res = False

    # traverse in the 1st list
    for x in list1:

        # traverse in the 2nd list
        for y in list2:

            # if one common
            if x == y:
                res = True
                return res

    return res

a = [1, 2, 3, 4, 5]
b = [6, 7, 8, 9, 5]
print(common_ele(a, b))


from manim import *

class Equations(Scene):
    def construct(self):

        eq1 = MathTex("\cos^2(x) - \cos(x) - 1 = 1")
        eq2 = MathTex("\cos^2(x) - \cos(x) - 2 = 0")
        eq3 = MathTex("t^2 = \cos^2(x)")
        eq3 = MathTex("t = \cos(x)")
        eq4 = MathTex("t^2 - t - 2 = 0")
        eq5 = MathTex("t = -1, \quad t = 2")
        eq6 = MathTex("\cos(x) = -1")
        eq7 = MathTex("\cos(x) = 2")
        eq8 = MathTex("x = \cos^{-1}(-1)")
        eq9 = MathTex("x = \pi")
        eq10 = MathTex("x = \cos^{-1}(2)")
        eq11 = MathTex("x = \\text{Está fuera del dominio del coseno}")

        self.play(Write(eq11))
        self.wait()


import sys

import matplotlib.pyplot as plt
import numpy as np
from instagramy import InstagramUser

try:
    filename = sys.argv[1]
    print("Extracting...")
except (IndexError, KeyError):
    print("List of username as textfile in argvment")
    sys.exit()

usernames = []
file = open(filename, "r")
for line in file:
    if line != "\n":
        usernames.append(str(line).strip())
followers = []
following = []
posts = []

for username in usernames:
    user = InstagramUser(username)
    followers.append(user.number_of_followers)
    following.append(user.number_of_followings)
    posts.append(user.number_of_posts)

x = np.arange(len(usernames))  # the label locations
width = 0.25  # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x + 0.2, followers, width, label="Followers")
rects2 = ax.bar(x, following, width, label="Following")
rects3 = ax.bar(x - 0.2, posts, width, label="Posts")

# Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_ylabel("Popularity")
ax.yaxis.set_visible(True)
ax.set_title("Username")
ax.set_xticks(x)
ax.set_xticklabels(usernames)
ax.legend()

def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate(
            "{}".format(height),
            xy=(rect.get_x() + rect.get_width() / 2, height),
            xytext=(0, 3),  # 3 points vertical offset
            textcoords="offset points",
            ha="center",
            va="bottom",
        )

autolabel(rects1)
autolabel(rects2)
autolabel(rects3)
fig.tight_layout()
plt.show()


import argparse

from context import api

def _start_spamming(node_http_endpoint, spam_interval):
    response = API_CLIENT.start_spamming(node_http_endpoint, spam_interval)
    print(response)

if __name__ == '__main__':
    API_CLIENT = api.BaseHelixAPI()

    PARSER = argparse.ArgumentParser(description='Get info from a node.')
    PARSER.add_argument('-host',
        metavar='host', type=str, default='79.193.43.206',
        help='Public IP of the host'
    )
    PARSER.add_argument('-port',
        metavar='port', type=str, default='8085',
        help='HTTP port of the host public IP'
    )
    PARSER.add_argument('-ms',
        metavar='port', type=int, default=1000,
        help='Interval between spam in ms'
    )
    PARSER.add_argument('-ssl',
        metavar='http or https', type=str, default=None,
        help='http or https'
    )
    ARGS = PARSER.parse_args()

    if not (ARGS.ssl is None):
        NODE_HTTP_ENDPOINT = "https://{}:{}".format(ARGS.host, ARGS.port)
    else:
        NODE_HTTP_ENDPOINT = "http://{}:{}".format(ARGS.host, ARGS.port)

    _start_spamming(NODE_HTTP_ENDPOINT, ARGS.ms)


order = [
    {"skolko": 5.0, "poroda": "тунец", "sred_razmer": 300},
    {"skolko": 15.0, "poroda": "окунь", "sred_razmer": 250},
    {"skolko": 20.0, "poroda": "щука", "sred_razmer": 460},
]
order_converted = []

for itm in order:
    order_converted.append(dict(count=round(itm['skolko']),
                                specie=str(itm['poroda']).capitalize(),
                                avg_size=round(int(itm['sred_razmer']) / 10)))

# Не удаляйте текст ниже, он нужен для проверки

for item in order_converted:
    for key, value in item.items():
        print(key, value)


#!/usr/bin/env ipython
# -*- coding: utf-8 -*-
from pylab import figure, close, show, find
import numpy as np
from h5py import File as h5
import funcs as ff
import igraph, argparse

#--- retrieve args
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
'-inp_txt', '--fname_inp_txt',
type=str,
default='../data/yeast_LIT.txt',
help='ASCII input',
)
parser.add_argument(
'-inp_h5', '--fname_inp_h5',
type=str,
default='./LIT.h5',
help='HDF5 input',
)
parser.add_argument(
'-fig', '--fname_fig',
type=str,
default='test.png',
help='figure filename.'
)
pa = parser.parse_args()

# ------- Cargo la informacion del problema ------------- #
fname_ess   = '../data/Essential_ORFs_paperHe.txt'
fname_graph = pa.fname_inp_txt #'../data/yeast_LIT.txt'
graph = igraph.Graph.Read_Ncol(fname_graph, directed=False)
graph.simplify(multiple=True, loops=False) # remover enlaces repetidos

n_nodes = len(graph.vs) # nro total de nodos del grafo

#--- leamos los fiteos de la distribucion de IBEPs
with h5(pa.fname_inp_h5, 'r') as f:
    #fit_A  = f['fit/A'].value
    fit_mu = f['fit/mu'].value   # valor medio
    fit_sigma = f['fit/sigma'].value  # sigma de la gaussiana
    ne = f['ne'][...]

#--- histograma
hc, hx_ = np.histogram(ne, bins=50, density=True)
hx = 0.5*(hx_[:-1] + hx_[1:])  # `hx` son los valores centrados de c/bin

#--- parametros de la red real
#N_e  = ff.count_essential_nodes(fname_graph, fname_ess) # nodos esenciales
N_ie = ff.calc_ne(g=graph, fname_ess=fname_ess)  # interacc esenciales

alpha_mean = (N_ie - fit_mu)/n_nodes
alpha_err  = fit_sigma/n_nodes

fig = figure(1, figsize=(6,4))
ax  = fig.add_subplot(111)

ax.plot(hx, hc, '-ob', label='realizaciones')
ax.plot(hx, ff.gauss(hx, 1., fit_mu, fit_sigma), '-r', lw=3, alpha=0.6, label='ajuste')
ax.axvline(N_ie, ls='--', c='black', lw=3, label='real')

ax.grid(True)
ax.legend(loc='best')

ax.set_xlabel('numero de interacciones entre proteinas esenciales')
ax.set_ylabel('densidad de probabilidad')

fig.savefig(pa.fname_fig, format='png', dpi=200, bbox_inches='tight')
close(fig)

print('alpha: %3.2f +- %3.2f'%(100.*alpha_mean, 100.*alpha_err))

#EOF


#Extracts the path to one or more sequences from an UShER sample-paths file

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("-p", help = "Sample-paths file")
    parser.add_argument("-s", nargs = "+", help = "One or more sample names to be extracted")
    args = parser.parse_args()

    #Sample names to be extracted
    sn = args.s

    #Iterate through the sample-paths, check if the line contains any of the samples of interest and print if so
    with open(args.p) as f:
        for l in f:
            if any(s in l for s in sn):
                print(l.strip())


#!/usr/bin/env python2.6
import sys
import subprocess
from multiprocessing import Process, Queue

def say(line):
    say = '(SayText "%s")' % line
    echo = subprocess.Popen(['echo', say], stdout=subprocess.PIPE)
    subprocess.call(['festival'], stdin=echo.stdout)

def listen_to_lines(queue):
    line = 'I am Log Reader 3000.  The world is beautiful.'
    while True:
        while not queue.empty():
            line = queue.get()
        say(line)

queue = Queue()
p = Process(target=listen_to_lines, args=(queue,))
p.start()

while True:
    line = sys.stdin.readline()
    sys.stdout.write(line)
    queue.put(line)


import sys

sys.exit()
### 1

# Base class
class Publication:
    def __init__(self, name):
        self.name = name

# Subclass 1
class Book(Publication):
    def __init__(self, name, author, page_count):
        self.author = author
        self.page_count = page_count
        super().__init__(name)

    def print_information(self):
        print(f"Book: {self.name}\nAuthor: {self.author}\nPage Count: {self.page_count}\n")

# Subclass 2
class Magazine(Publication):
    def __init__(self, name, chief_editor):
        self.chief_editor = chief_editor
        super().__init__(name)

    def print_information(self):
        print(f"Magazine: {self.name}\nChief Editor: {self.chief_editor}\n")

# main program
publications = []
publications.append(Magazine("Donald Duck", "Aki Hyyppä"))
publications.append(Book("Compartment No. 6", "Rosa Liksom", 192))

for p in publications:
    p.print_information()

### 2

from tabulate import tabulate
import random

# Base class
class Car:
    def __init__(self, registration_number, maximum_speed, current_speed=0, travelled_distance=0):
        self.registration_number = registration_number
        self.maximum_speed = maximum_speed
        self.current_speed = current_speed
        self.travelled_distance = travelled_distance

    def accelerate(self, speed_change):
        self.current_speed += speed_change
        if self.current_speed > self.maximum_speed:
            self.current_speed = self.maximum_speed
        if self.current_speed < 0:
            self.current_speed = 0

    def drive(self, no_of_hrs):
        self.travelled_distance += no_of_hrs * self.current_speed

class Race:
    distance_covered = 0
    hour = 1
    index = None

    def __init__(self, name, distance, cars_list):
        self.name = name
        self.distance = distance
        self.car_list = cars_list
        self.total_cars = len(cars_list)

    def hour_passes(self):
        while not self.race_finished():
            for i in range(self.total_cars):
                speed_change = random.randint(-10, 15)
                self.car_list[i].accelerate(speed_change)
                self.car_list[i].drive(10)
            self.print_status()

    def print_status(self):
        table = [["Car no.", "Reg no.", "Max Speed(km/h)", "Current Speed(km/h)", "Distance Travelled(km)"]]
        for i in range(no_of_cars):
            table.append(
                [i + 1, cars_list[i].registration_number, cars_list[i].maximum_speed, cars_list[i].current_speed,
                 cars_list[i].travelled_distance])

        print(tabulate(table, headers="firstrow", tablefmt="fancy_grid"))

    def race_finished(self):
        for i in range(self.total_cars):
            if self.distance_covered < self.car_list[i].travelled_distance:
                self.distance_covered = self.car_list[i].travelled_distance
                index = i
                if self.distance_covered > self.distance:
                    return True

# Subclass 1
class ElectricCar(Car):
    def __init__(self, registration_number, maximum_speed, battery_capacity):
        self.battery_capacity = battery_capacity
        super().__init__(registration_number, maximum_speed)

# Subclass 2
class GasolineCar(Car):
    def __init__(self, registration_number, maximum_speed, tank_volume):
        self.tank_volume = tank_volume
        super().__init__(registration_number, maximum_speed)

# main program
cars_list = []
cars_list.append(ElectricCar("ABC-15", 180, 52.5))
cars_list.append(GasolineCar("ACD-123", 165, 32.3))
for c in cars_list:
    c.accelerate(random.randint(30, 60))
    c.drive(3)
    print(f"Car: {c.registration_number}\nDistance Travelled: {c.travelled_distance}\n")


from local_properties import *
from itertools import islice
from jyoti_content_service.payloads.ReportPayload import ReportPayload
from repository.models import ReportTable

class LoadTwitterFeedService:

    def load_file(self):
        try:
            with open(TWITTER_FILE_PATH, 'rb') as f:
                for n_lines in iter(lambda: tuple(islice(f, BATCH_NUM_LINES)), ()):
                    self.create_payload(n_lines)
        except Exception as e:
            raise e

    def create_payload(self, n_lines):
        payloads = []
        try:
            for line in n_lines:
                column_values = line.split(',')
                if len(column_values) <= 5 and len(column_values) > 7:
                    continue
                report_payload = ReportPayload(column_values[1], column_values[2], column_values[3], column_values[4], column_values[5], evidence=column_values[6], name=column_values[0])
                payloads.append(report_payload)
                ReportTable.objects.bulk_create(payloads)
            return payloads
        except Exception as e:
            raise e


import structlog
import json

from gem_port import GemPort
from twisted.internet.defer import inlineCallbacks, returnValue

log = structlog.get_logger()

class OltGemPort(GemPort):
    """
    Adtran OLT specific implementation
    """
    def __init__(self, gem_id, alloc_id,
                 encryption=False,
                 omci_transport=False,
                 multicast=False,
                 tcont_ref=None,
                 traffic_class=None,
                 intf_ref=None,
                 untagged=False,
                 name=None,
                 handler=None,
                 is_mock=False):
        super(OltGemPort, self).__init__(gem_id, alloc_id,
                                         encryption=encryption,
                                         omci_transport=omci_transport,
                                         multicast=multicast,
                                         tcont_ref=tcont_ref,
                                         traffic_class=traffic_class,
                                         intf_ref=intf_ref,
                                         untagged=untagged,
                                         name=name,
                                         handler=handler)
        self._is_mock = is_mock

    @staticmethod
    def create(handler, gem_port):
        mcast = gem_port['gemport-id'] in [4095]    # TODO: Perform proper lookup
        untagged = 'untagged' in gem_port['name'].lower()
        # TODO: Use next once real BBF mcast available.
        # port_ref = 'channel-pair-ref 'if mcast else 'venet-ref'
        port_ref = 'venet-ref 'if mcast else 'venet-ref'

        return OltGemPort(gem_port['gemport-id'],
                          None,
                          encryption=gem_port['encryption'],  # aes_indicator,
                          tcont_ref=gem_port['tcont-ref'],
                          name=gem_port['name'],
                          traffic_class=gem_port['traffic-class'],
                          intf_ref=gem_port.get(port_ref),
                          handler=handler,
                          multicast=mcast,
                          untagged=untagged)

    @property
    def encryption(self):
        return self._encryption

    @encryption.setter
    def encryption(self, value):
        assert isinstance(value, bool), 'encryption is a boolean'

        if self._encryption != value:
            self._encryption = value
            self.set_config(self._handler.rest_client, 'encryption', value)

    @inlineCallbacks
    def add_to_hardware(self, session, pon_id, onu_id, operation='POST'):
        from ..adtran_olt_handler import AdtranOltHandler
        log.info('add-gem-port-2-hw', pon_id=pon_id, onu_id=onu_id,
                 operation=operation, gem_port=self)
        uri = AdtranOltHandler.GPON_GEM_CONFIG_LIST_URI.format(pon_id, onu_id)
        data = json.dumps(self.to_dict())
        name = 'gem-port-create-{}-{}: {}/{}'.format(pon_id, onu_id,
                                                     self.gem_id,
                                                     self.alloc_id)
        try:
            results = yield session.request(operation, uri, data=data, name=name)

        except Exception as e:
            if operation == 'POST':
                returnValue(self.add_to_hardware(session, pon_id, onu_id,
                                                 operation='PATCH'))
            else:
                log.exception('add-2-hw', gem=self, e=e)
                raise

        returnValue(results)

    def remove_from_hardware(self, session, pon_id, onu_id):
        from ..adtran_olt_handler import AdtranOltHandler

        uri = AdtranOltHandler.GPON_GEM_CONFIG_URI.format(pon_id, onu_id, self.gem_id)
        name = 'gem-port-delete-{}-{}: {}'.format(pon_id, onu_id, self.gem_id)
        return session.request('DELETE', uri, name=name)

    def set_config(self, session, leaf, value):
        from ..adtran_olt_handler import AdtranOltHandler

        data = json.dumps({leaf: value})
        uri = AdtranOltHandler.GPON_GEM_CONFIG_URI.format(self.pon_id,
                                                          self.onu_id,
                                                          self.gem_id)
        name = 'onu-set-config-{}-{}-{}'.format(self._pon_id, leaf, str(value))
        return session.request('PATCH', uri, data=data, name=name)


"""
The model of Aria2 Instance
"""
from __future__ import annotations

import logging
import subprocess
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Iterable, Optional
from urllib.parse import ParseResult, urlunparse
from xmlrpc.client import ServerProxy

from django.apps import apps
from django.db import models
from django.utils.functional import cached_property

from ..exceptions import CommandExecutionFailed, CommandNotFound

if TYPE_CHECKING:
    from .argument import Argument as TArgument
    from .binary import Binary as TBinary
    from .profile import ArgumentPair as TArgumentPair
    from .profile import Profile as TProfile

logger = logging.getLogger(__name__)

class QuerySet(models.QuerySet):
    """
    custom QuerySet to fit aria2c
    """

    def create_from_pid(self, pid: int | str) -> Instance:
        """

        :param pid:
        :type pid: int | str
        :return:
        :rtype: Instance
        """
        Binary: TBinary = apps.get_model("aria2", "Binary")
        command = Binary.get_command(pid)
        binary, _ = Binary.objects.get_or_create(path=command.split(maxsplit=1)[0])
        return self.create(pid=pid, command=command, binary=binary)

    def create_all_from_aria2c(self, binary: TBinary) -> tuple[Instance, ...]:
        """

        :param binary:
        :type binary: TBinary
        :return:
        :rtype: tuple[Aria2cInstance, ...]
        """
        return tuple(
            self.create(pid=pid, command=binary.get_command(pid), binary=binary)
            for pid in binary.get_pids()
        )

    def create_from_profile(self, profile: TProfile) -> Instance:
        """

        :param profile:
        :type profile: Profile
        :return:
        :rtype: Instance
        """
        command = " ".join(profile.command)
        try:
            return self.get(command=command)
        except Instance.DoesNotExist:
            with subprocess.Popen(profile.command):
                start = datetime.now()
                while True:
                    try:
                        pid = profile.binary.get_pid(command)
                    except CommandNotFound as exc:
                        if (datetime.now() - start) > timedelta(seconds=30):
                            raise CommandExecutionFailed from exc
                        continue
                    return self.create(
                        pid=pid, command=command, binary=profile.binary, profile=profile
                    )

Manager = models.Manager.from_queryset(QuerySet)

class Instance(models.Model):
    """
    The model of Aria2 instance
    """

    pid = models.IntegerField(primary_key=True)
    command = models.CharField(max_length=256, unique=True)

    binary = models.ForeignKey("Binary", on_delete=models.CASCADE)
    profile = models.OneToOneField(
        "Profile", blank=True, null=True, on_delete=models.CASCADE
    )

    effective_user_name = models.CharField(blank=True, max_length=256, null=True)
    version = models.CharField(blank=True, max_length=256, null=True)
    session_id = models.CharField(blank=True, max_length=256, null=True)
    objects = Manager()

    class Meta:
        verbose_name = "Instance"

    def delete(
        self, using: Any = None, keep_parents: bool = False
    ) -> tuple[int, dict[str, int]]:
        """

        :param using:
        :type using: Any
        :param keep_parents:
        :type keep_parents: bool
        :return:
        :rtype: tuple[int, dict[str, int]]
        """
        try:
            self.rpc_server_proxy.aria2.shutdown()
        except ConnectionRefusedError as exc:
            logger.exception(exc)
        return super().delete(using, keep_parents)

    def save(
        self,
        force_insert: bool = False,
        force_update: bool = False,
        using: Optional[str] = None,
        update_fields: Optional[Iterable[str]] = None,
    ) -> None:
        """

        :param force_insert:
        :type force_insert: bool
        :param force_update:
        :type force_update: bool
        :param using:
        :type using: Optional[str]
        :param update_fields:
        :type update_fields: Optional[Iterable[str]]
        :return:
        :rtype: None
        """
        Profile: TProfile = apps.get_model("aria2", "Profile")
        if not self.profile:
            self.profile = Profile.objects.get(args=self.command.split(maxsplit=1)[-1])
        if not self.effective_user_name:
            self.effective_user_name = (
                subprocess.check_output(
                    ["ps", "-p", str(self.pid), "-o", "euser", "--no-headers"]
                )
                .decode()
                .strip()
            )
        if not self.version:
            self.version = self.rpc_server_proxy.aria2.getVersion()["version"]
        if not self.session_id:
            self.session_id = self.rpc_server_proxy.aria2.getSessionInfo()["sessionId"]
        return super().save(force_insert, force_update, using, update_fields)

    @cached_property
    def rpc_server_address(self) -> str:
        """

        :return:
        :rtype: str
        """
        Argument: TArgument = apps.get_model("aria2", "Argument")
        rpc_listen_port = Argument.objects.get(long_argument="--rpc-listen-port")
        ArgumentPair: TArgumentPair = self.profile.arguments.through
        port = ArgumentPair.objects.get(argument=rpc_listen_port).value
        url = ParseResult(
            scheme="http",
            netloc=f"localhost:{port}",
            path="rpc",
            params="",
            query="",
            fragment="",
        )
        return urlunparse(url)

    @cached_property
    def rpc_server_proxy(self) -> ServerProxy:
        """
        find all methods of aria2 rpc methods
        * https://aria2.github.io/manual/en/html/aria2c.html#methods
        :return:
        :rtype: ServerProxy
        """
        return ServerProxy(self.rpc_server_address)

    @property
    def cpu(self) -> Optional[float]:
        """

        :return:
        :rtype: Optional[float]
        """
        try:
            return float(
                subprocess.check_output(
                    ["ps", "-p", str(self.pid), "-o", "%cpu", "--no-headers"]
                )
                .decode()
                .strip()
            )
        except subprocess.CalledProcessError as exc:
            logger.exception(exc)

    @property
    def mem(self) -> Optional[str]:
        """

        :return:
        :rtype: Optional[str]
        """
        try:
            return (
                subprocess.check_output(
                    ["ps", "-p", str(self.pid), "-o", "%mem", "--no-headers"]
                )
                .decode()
                .strip()
            )
        except subprocess.CalledProcessError as exc:
            logger.exception(exc)

    @property
    def elapsed_time(self) -> Optional[timedelta]:
        """

        :return:
        :rtype: Optional[timedelta]
        """
        try:
            return timedelta(
                seconds=int(
                    subprocess.check_output(
                        ["ps", "-p", str(self.pid), "-o", "etimes", "--no-headers"]
                    )
                    .decode()
                    .strip()
                )
            )
        except subprocess.CalledProcessError as exc:
            logger.exception(exc)

    @property
    def cumulative_cpu_times(self) -> Optional[timedelta]:
        """

        :return:
        :rtype: Optional[timedelta]
        """
        try:
            return timedelta(
                seconds=int(
                    subprocess.check_output(
                        ["ps", "-p", str(self.pid), "-o", "cputimes", "--no-headers"]
                    )
                    .decode()
                    .strip()
                )
            )
        except subprocess.CalledProcessError as exc:
            logger.exception(exc)


import mpi4py
mpi4py.rc.recv_mprobe = False
mpi4py.rc.threads = False
from mpi4py import MPI

import numpy as np
import sys
import h5py
import time
import os
import json

from scipy.signal import butter
import sys
sys.path.append('/home/camp/warnert')
import cupy
import cusignal

from chimpy.ramfile import RamFile

MASTER_PROCESS = 0
SETUP_TAG = 71
AMPS_TAG = 72
DATA_TAG = 73
RESULT_TAG = 74
TEST_TAG = 76
DIE_SIGNAL = -1

# Load filter parameters

with open('params.json') as json_file:
    params = json.load(json_file)

sample_chunk_size=params['sample_chunk_size']
channels=np.array(params['channels'])
n_samples=params['n_samples']
order=params['order']
low_cutoff=params['low_cutoff']
high_cutoff=params['high_cutoff']
scales=np.array(params['scales'])
in_filepath=params['in_filepath']
out_filepath=params['out_filepath']
connected_pixels=params['connected_pixels']
ram_copy=params['ram_copy']

# Create dictionary of channel scales
channel_scales=dict(zip(channels,scales))
n_channels=len(connected_pixels)

# # Initialize MPI
comm = MPI.COMM_WORLD
nproc = comm.Get_size()
iproc = comm.Get_rank()
inode = MPI.Get_processor_name()
status = MPI.Status()

# Calculate filter
sos = butter(order, [low_cutoff/10000, high_cutoff/10000], 'bandpass', output='sos')

if iproc == MASTER_PROCESS:
    #     Optionally save file into a tmpfs partition for processing
    if ram_copy:
        in_ramfile=RamFile(in_filepath, 'r')
        in_filepath=in_ramfile.ram_filepath
        out_ramfile=RamFile(out_filepath, 'w')
        out_filepath=out_ramfile.ram_filepath
     #     Load input file
    in_fid = h5py.File(in_filepath, 'r')
    if n_samples==-1:
        n_samples=in_fid['sig'].shape[1]

    #     Create output file
    out_fid=h5py.File(out_filepath, 'w')
    out_fid['mapping']=in_fid['mapping'][connected_in_mapping]
    in_fid.copy('/message_0', out_fid)
    in_fid.copy('/proc0', out_fid)
    in_fid.copy('/settings', out_fid)
    in_fid.copy('/time', out_fid)
    in_fid.copy('/version', out_fid)
    if 'bits' in in_fid.keys():
        in_fid.copy('/bits', out_fid)
    out_fid.create_dataset("sig", (len(connected_pixels), n_samples), dtype='float32')

    #     Create data chunks (channels and samples) for each MPI process
    in_channel_chunks=np.array_split(channels[connected_pixels], nproc-1)
    out_channel_chunks=np.array_split(list(range(n_channels)), nproc-1)
    n_sample_chunks=n_samples/sample_chunk_size
    sample_chunk_borders=np.hstack((np.arange(n_sample_chunks, dtype=int)*sample_chunk_size,n_samples))
    sample_chunks=dict(zip(np.arange(nproc-1),[np.array([sample_chunk_borders[i:i+2].copy() for i in range(len(sample_chunk_borders)-1)])]*(nproc-1)))
    # Dictionary for holding currently processed chunks for each process
    current_chunks=dict(zip(np.arange(nproc-1),[None]*(nproc-1)))
    n_total_chunks=sum([sample_chunks[i].shape[0] for i in np.arange(nproc-1)])
    n_remaining_chunks=n_total_chunks
    n_current_chunks=0

    #     Master process main loop
    while (n_remaining_chunks+n_current_chunks)>0:
        #         Checking for idle processes, and delegating chunks
        for i, _ in enumerate(current_chunks):
            if current_chunks[i] is None and sample_chunks[i].shape[0]>0:
                current_chunks[i]=sample_chunks[i][0]
                data_shape=(in_channel_chunks[i].shape[0], sample_chunk_size+current_chunks[i][1]-current_chunks[i][0])
                comm.send(data_shape, dest=i+1, tag=SETUP_TAG)
                comm.send([channel_scales[channel] for channel in in_channel_chunks[i]], dest=i+1, tag=AMPS_TAG)
                chunk=np.empty((in_channel_chunks[i].shape[0],sample_chunk_size+current_chunks[i][1]-current_chunks[i][0]))
                if current_chunks[i][0]==0:
                    chunk[:,:sample_chunk_size]=np.array([in_fid['sig'][in_channel_chunks[i],0],]*sample_chunk_size).transpose()
                else:
                    chunk[:,:sample_chunk_size]=in_fid['sig'][in_channel_chunks[i],(current_chunks[i][0]-sample_chunk_size):current_chunks[i][0]]
                sample_chunks[i]=np.delete(sample_chunks[i], (0), axis=0)
                chunk[:,sample_chunk_size:]=in_fid['sig'][in_channel_chunks[i],current_chunks[i][0]:current_chunks[i][1]]
                comm.send(chunk, dest=i+1, tag=DATA_TAG)

        #         Waiting for next ready chunk
        data=comm.recv(source=MPI.ANY_SOURCE, tag=RESULT_TAG, status=status)
        rnk = status.Get_source()

        #         Writing results to output file
        out_fid['sig'][out_channel_chunks[rnk-1],current_chunks[rnk-1][0]:current_chunks[rnk-1][1]]=data
        current_chunks[rnk-1]=None
        n_current_chunks=sum([current_chunks[cc] is not None for cc in current_chunks])
        n_remaining_chunks=sum([sample_chunks[i].shape[0] for i in np.arange(nproc-1)])

        #         Reportint progress
        print((1-n_remaining_chunks/n_total_chunks)*990, flush=True)

    #     After finishing the main loop, killing processes
    for proc in range(nproc-1):
        comm.send(DIE_SIGNAL, proc+1, tag=SETUP_TAG)
#     Slave process main loop
else:
    while True:
    #         Waiting for data from master process
        chunk_shape=comm.recv(source=MASTER_PROCESS, tag=SETUP_TAG)
        if chunk_shape==-1:
            break
        else:
            amps=comm.recv(source=MASTER_PROCESS, tag=AMPS_TAG)
            chunk=comm.recv(source=MASTER_PROCESS, tag=DATA_TAG, status=status)
            tag = status.Get_tag()
            cusig=cupy.asarray(chunk, dtype=cupy.float32)
            cusig=cusig-cupy.mean(cusig)
            cusig=cusignal.sosfilt(sos,cusig)
            cusig=cupy.flipud(cusig)
            cusig=cusignal.sosfilt(sos,cusig)
            cusig=cupy.flipud(cusig)
            proc_channel_scales=cupy.asarray(chunk[:,-1], dtype=cupy.float32)[:,None]
#             cusig=cusig*proc_channel_scales
            result_array=cupy.asnumpy(cusig[:,-(chunk.shape[1]-sample_chunk_size):])
            comm.send(result_array, dest=MASTER_PROCESS, tag=RESULT_TAG)

if iproc == MASTER_PROCESS:
    in_fid.close()
    out_fid.close()
    if ram_copy:
        out_ramfile.save()
        del in_ramfile, out_ramfile
    print('DONE', flush=True)


import sys
from collections import Counter

class Task1b:
    def __init__(self):
        self.x = 0

    def find_last_words_count(self):
        a = (1, [1, 2])
        print(a)
        b = [1, 2, 3]
        print(b)
        extra = (b,)
        z = a + extra
        print(z)

if __name__ == '__main__':
    my_task = Task1b()
    print("This is task 1b:")
    # print("Enter the word combination:")
    # my_task.x = int(input())
    my_task.find_last_words_count()
    input()
    sys.exit(1)