# -*- coding: utf-8 -*-
import time
import logging

from .asyncache import Defer, REGET, CancelledError
from .base import BaseCacheClient, NONE

from chorde.mq import coherence

class CoherentDefer(Defer):
    """
    Wrap a callable in this, and pass it as a value to an AsyncWriteCacheClient,
    and the evaluation of the given callable will happen asynchronously. The cache
    will return stale entries until the callable is finished computing a new value.
    Computation will be aborted if the coherence protocol shows someone else already
    computing, or if the shared cache is re-validated somehow when this method is
    called.
    """

    def __init__(self, callable_, *args, **kwargs):
        """
        Params
            callable_, args, kwargs: see Defer. All others must be passed by keyword.

            manager: A CoherenceManager instance that coordinates the corresponding cache clients.

            expired: A callable of the sort CoherenceManager takes, to re-check expiration status
                against the shared cache.

            expire_private: An optional callable that will be called with the given key (see below)
                right before receiving an OOB update. It should mark any privately held value for
                that key as expired, since a fresher one will be coming OOB. Usually the expire
                method of the private cache client works for this purpose.

            key: The key associated with this computation, to be provided to the CoherenceManager.

            timeout: Coherence protocol timeout, in ms, if the peers don't answer in this time,
                detached operation will be assumed and computation will proceed.
                Default: whatever the heartbeat timeout is on the underlying IPSub channel

            wait_time: Whether and how long to wait for other node's computation to be done.
                Normally, the default value of 0, which means "no wait", is preferrable so as not
                to stall deferred computation workers. However, in quick computations, it may be
                beneficial to provide a small wait time, to decrease latency in case some node
                goes down. This deferred would then take it upon him to start computing, and the
                whole group could be spared a whole cycle (versus just waiting for the value to
                be needed again), trading thoughput for latency. A value of None will cause
                infinite waits.
        """
        self.manager = kwargs.pop('manager')
        self.expired = kwargs.pop('expired')
        self.expire_private = kwargs.pop('expire_private', None)
        self.fetch = kwargs.pop('fetch', None)
        self.key = kwargs.pop('key')
        self.timeout = kwargs.pop('timeout', None)
        if self.timeout is None:
            self.timeout = self.manager.ipsub.heartbeat_push_timeout
        self.wait_time = kwargs.pop('wait_time', 0)
        self.computed = False
        self.aborted = False
        super(CoherentDefer, self).__init__(callable_, *args, **kwargs)

    def undefer(self):
        logger = logging.getLogger('chorde.coherence')
        while True:
            if not self.expired():
                logger.debug("Not computing because already fresh, key=%r", self.key)
                if hasattr(self, 'future'):
                    if self.expire_private is not None:
                        self.expire_private(self.key)
                    return REGET
                else:
                    return NONE
            else:
                computer = self.manager.query_pending(self.key, self.expired, self.timeout, True)
                if computer is None:
                    # My turn
                    logger.debug("Acquired computer duty on key=%r", self.key)
                    try:
                        rv = super(CoherentDefer, self).undefer()
                        if rv is not NONE:
                            logger.debug("Computing done on key=%r", self.key)
                            self.computed = True
                        else:
                            logger.debug("Computing skipped on key=%r", self.key)
                            self.aborted = True
                    except:
                        logger.debug("Computing aborted on key=%r due to exception", self.key, exc_info=True)
                        self.aborted = True
                        raise
                    return rv
                elif computer is coherence.OOB_UPDATE and not self.expired():
                    # Skip, tiered caches will read it from the shared cache and push it downstream
                    logger.debug("Fresh value available OOB on key=%r", self.key)
                    if hasattr(self, 'future'):
                        if self.expire_private is not None:
                            self.expire_private(self.key)
                        return REGET
                    else:
                        return NONE
                elif self.wait_time != 0:
                    logger.debug("Waiting for computation on node %r on key=%r", computer, self.key)
                    if self.manager.wait_done(self.key, timeout = self.wait_time):
                        logger.debug("Computation done (was waiting on node %r) on key=%r", computer, self.key)
                        if hasattr(self, 'future'):
                            if self.expire_private is not None:
                                self.expire_private(self.key)
                            return REGET
                        else:
                            return NONE
                    else:
                        # retry
                        logger.debug("Computation still in progress (waiting on node %r) on key=%r", computer, self.key)
                        continue
                else:
                    logger.debug("Computation in progress on node %r key=%r, not waiting", computer, self.key)
                    if hasattr(self, 'future'):
                        # Must cancel it if we're not going to wait
                        self.future.cancel()
                        self.future.set_exception(CancelledError())
                    return NONE

    def done(self):
        if self.computed:
            self.manager.mark_done(self.key)
        elif self.aborted:
            self.manager.mark_aborted(self.key)
        super(CoherentDefer, self).done()

class CoherentWrapperClient(BaseCacheClient):
    """
    Client wrapper that publishes cache activity with the coherence protocol.
    Given a manager, it will invoke its methods to make sure other instances
    on that manager are notified of invalidations.

    It adds another method of putting, put_coherently, that will additionally
    ensure that only one node is working on computing the result (thust taking
    a callable rather than a value, as defers do).

    The regular put method will publish being done, if the manager is configured
    in quick refresh mode, but will not attempt to obtain a computation lock,
    resulting in less overhead, decent consistency, but some duplication of
    effort. Therefore, put_coherently should be applied to expensive computations.

    If the underlying client isn't asynchronous, put_coherently will implicitly
    undefer the values, executing the coherence protocol in the calling thread.
    """

    def __init__(self, client, manager, timeout = 2000):
        self.client = client
        self.manager = manager
        self.timeout = timeout

    @property
    def is_async(self):
        return self.client.is_async

    @property
    def capacity(self):
        return self.client.capacity

    @property
    def usage(self):
        return self.client.usage

    def wait(self, key, timeout = None):
        # Hey, look at that. Since locally it it all happens on a Defer,
        # we can just wait on the wrapped client first to wait for ourselves
        if timeout is not None:
            deadline = time.time() + timeout
        else:
            deadline = None
        self.client.wait(key, timeout)

        # But in the end we'll have to ask the manager to talk to the other nodes
        if deadline is not None:
            timeout = int(max(0, deadline - time().time()) * 1000)
        else:
            timeout = None
        self.manager.wait_done(key, timeout=timeout)

    def put(self, key, value, ttl, coherence_timeout = None, **kw):
        manager = self.manager
        if manager.quick_refresh:
            # In quick refresh mode, we publish all puts
            if self.is_async and isinstance(value, Defer) and not isinstance(value, CoherentDefer):
                callable_ = value.callable_
                def done_after(*p, **kw):
                    rv = callable_(*p, **kw)
                    if rv is not NONE:
                        manager.fire_done([key])
                    return rv
                value.callable_ = done_after
                self.client.put(key, value, ttl, **kw)
            else:
                self.client.put(key, value, ttl, **kw)
                manager.fire_done([key], timeout = coherence_timeout)
        else:
            self.client.put(key, value, ttl, **kw)

    def put_coherently(self, key, ttl, expired, future, callable_, *args, **kwargs):
        """
        Another method of putting, that will additionally ensure that only one node
        is working on computing the result. As such, it takes  a callable rather
        than a value, as defers do.

        If the underlying client isn't asynchronous, put_coherently will implicitly
        undefer the value, executing the coherence protocol in the calling thread.

        Params
            key, ttl: See put
            expired: A callable that will re-check expiration status of the key on
                a shared cache. If this function returns False at mid-execution of
                the coherence protocol, the protocol and the computation will be
                aborted (assuming the underlying client will now instead fetch
                values from the shared cache).
            future: (optional) A future to be associated with the deferred
                computation.
            callable_, args, kwargs: See Defer. In contrast to normal puts, the
                callable may not be invoked if some other node has the computation
                lock.
        """
        wait_time = kwargs.pop('wait_time', 0)
        put_kwargs = kwargs.pop('put_kwargs', None) or None
        value = CoherentDefer(
            callable_,
            key = key,
            manager = self.manager,
            expired = expired,
            timeout = self.timeout,
            wait_time = wait_time,
            *args, **kwargs )
        if future is not None:
            value.future = future
        deferred = None
        try:
            if not self.is_async:
                # cannot put Defer s, so undefer right now
                deferred = value
                value = value.undefer()
                if value is NONE:
                    # Abort
                    return
            self.client.put(key, value, ttl, **(put_kwargs or {}))
        finally:
            if deferred is not None:
                deferred.done()

    def renew(self, key, ttl):
        self.client.renew(key, ttl)

    def delete(self, key, coherence_timeout = None):
        self.client.delete(key)

        # Warn others
        self.manager.fire_deletion(key, timeout = coherence_timeout)

    def expire(self, key):
        self.client.expire(key)

    def clear(self, coherence_timeout = None):
        self.client.clear()

        # Warn others
        self.manager.fire_deletion(coherence.CLEAR, timeout = coherence_timeout)

    def purge(self, *p, **kw):
        self.client.purge(*p, **kw)

    def getTtl(self, key, default = NONE, **kw):
        return self.client.getTtl(key, default, **kw)

    def get(self, key, default = NONE, **kw):
        return self.client.get(key, default, **kw)

    def getTtlMulti(self, keys, default = NONE, **kw):
        return self.client.getTtlMulti(keys, default, **kw)

    def getMulti(self, keys, default = NONE, **kw):
        return self.client.getMulti(keys, default, **kw)

    def contains(self, key, ttl = None, **kw):
        return self.client.contains(key, ttl, **kw)

    def promote(self, key, *p, **kw):
        return self.client.promote(key, *p, **kw)


# Because ctypes is new from Python 2.5, so pytransform doesn't work
# before Python 2.5
#
import os
import platform
import struct
import sys
from ctypes import cdll, c_char, c_char_p, c_int, c_void_p, \
    pythonapi, py_object, PYFUNCTYPE
from ctypes.util import find_library

#
# Global
#
_pytransform = None
_get_error_msg = None

#
# Options
#

# How to show error message return from dynamic library _pytransform.
#
# Each time call a dll function, if something is wrong, _get_error_msg
# will return the reason.
#
# Enable _verbose_mode will print the details got from _get_error_msg.
# Disable this options will print only a short message.
_verbose_mode = 1

# In debug mode, print trace stack when raise exception.
# Otherwise only show a short message.
#
# Run python with command option "-d", or set environment variable
# PYTHONDEBUG. For example
#
#   python -d pyarmor.py xxxx
#
_debug_mode = sys.flags.debug

class PytransformError(Exception):
    def __init__(self, *args, **kwargs):
        super(Exception, self).__init__(*args, **kwargs)
        if _debug_mode:
            self._print_stack()

    @classmethod
    def _print_stack(self):
        try:
            from traceback import print_stack
        except Exception:
            _debug_mode = 0
            sys.stderr.write('Disabled debug mode.\n')
        else:
            print_stack()

def dllmethod(func):
    def format_message(msg, *args, **kwargs):
        if _verbose_mode:
            s1 = str(args)[:-1]
            s2 = ', '.join(['%s=%s' % (k, repr(v)) for k, v in kwargs.items()])
            sep = ', ' if (s1 and s2) else ''
            line = 'Call with arguments: %s%s%s)' % (s1, sep, s2)
            return msg
        return msg.split('\n')[-1]

    def wrap(*args, **kwargs):
        args = [(s.encode() if isinstance(s, str) else s) for s in args]
        result = func(*args, **kwargs)
        errmsg = _get_error_msg()
        if errmsg:
            raise PytransformError(format_message(errmsg, *args, **kwargs))
        return result

    return wrap

@dllmethod
def init_pytransform():
    major, minor = sys.version_info[0:2]
    # Python2.5 no sys.maxsize but sys.maxint
    # bitness = 64 if sys.maxsize > 2**32 else 32
    prototype = PYFUNCTYPE(c_int, c_int, c_int, c_void_p)
    init_module = prototype(('init_module', _pytransform))
    init_module(major, minor, pythonapi._handle)

@dllmethod
def init_runtime(systrace=0, sysprofile=1, threadtrace=0, threadprofile=1):
    pyarmor_init()
    prototype = PYFUNCTYPE(c_int, c_int, c_int, c_int, c_int)
    _init_runtime = prototype(('init_runtime', _pytransform))
    _init_runtime(systrace, sysprofile, threadtrace, threadprofile)

@dllmethod
def import_module(modname, filename):
    global _import_module
    if _import_module is None:
        prototype = PYFUNCTYPE(py_object, c_char_p, c_char_p)
        _import_module = prototype(('import_module', _pytransform))
    return _import_module(modname, filename)

_import_module = None

@dllmethod
def exec_file(filename):
    global _exec_file
    if _exec_file is None:
        prototype = PYFUNCTYPE(c_int, c_char_p)
        _exec_file = prototype(('exec_file', _pytransform))
    return _exec_file(filename)

_exec_file = None

@dllmethod
def encrypt_project_files(proname, filelist, mode=0):
    prototype = PYFUNCTYPE(c_int, c_char_p, py_object, c_int)
    dlfunc = prototype(('encrypt_project_files', _pytransform))
    return dlfunc(proname, filelist, mode)

@dllmethod
def encrypt_files(key, filelist, mode=0):
    t_key = c_char * 32
    prototype = PYFUNCTYPE(c_int, t_key, py_object, c_int)
    dlfunc = prototype(('encrypt_files', _pytransform))
    return dlfunc(t_key(*key), filelist, mode)

def generate_project_capsule(licfile):
    prikey, pubkey, prolic = _generate_project_capsule()
    capkey = _encode_capsule_key_file(licfile)
    return prikey, pubkey, capkey, prolic

@dllmethod
def _generate_project_capsule():
    prototype = PYFUNCTYPE(py_object)
    dlfunc = prototype(('generate_project_capsule', _pytransform))
    return dlfunc()

@dllmethod
def _encode_capsule_key_file(licfile):
    prototype = PYFUNCTYPE(py_object, c_char_p, c_char_p)
    dlfunc = prototype(('encode_capsule_key_file', _pytransform))
    return dlfunc(licfile, None)

@dllmethod
def generate_module_key(pubname, key):
    t_key = c_char * 32
    prototype = PYFUNCTYPE(py_object, c_char_p, t_key, c_char_p)
    dlfunc = prototype(('generate_module_key', _pytransform))
    return dlfunc(pubname, t_key(*key), None)

@dllmethod
def generate_license_file(filename, priname, rcode, start=-1, count=1):
    prototype = PYFUNCTYPE(c_int, c_char_p, c_char_p, c_char_p, c_int, c_int)
    dlfunc = prototype(('generate_project_license_files', _pytransform))
    return dlfunc(filename, priname, rcode, start, count)

@dllmethod
def get_registration_code():
    prototype = PYFUNCTYPE(py_object)
    dlfunc = prototype(('get_registration_code', _pytransform))
    return dlfunc()

@dllmethod
def get_expired_days():
    prototype = PYFUNCTYPE(py_object)
    dlfunc = prototype(('get_expired_days', _pytransform))
    return dlfunc()

@dllmethod
def get_trial_days():
    prototype = PYFUNCTYPE(py_object)
    dlfunc = prototype(('get_trial_days', _pytransform))
    return dlfunc()

@dllmethod
def version_info():
    prototype = PYFUNCTYPE(py_object)
    dlfunc = prototype(('version_info', _pytransform))
    return dlfunc()

def get_hd_sn():
    size = 256
    t_sn = c_char * size
    sn = t_sn()
    if (_pytransform.get_hd_sn(sn, size) == -1):
        return ''
    return sn.value.decode()

def show_hd_info():
    return _pytransform.show_hd_info()

def get_license_info():
    info = {
        'expired': 'Never',
        'restrict_mode': 'Enabled',
        'HARDDISK': 'Any',
        'IFMAC': 'Any',
        'IFIPV4': 'Any',
        'DOMAIN': 'Any',
        'CODE': '',
    }
    rcode = get_registration_code().decode()
    index = 0
    if rcode.startswith('*TIME:'):
        from time import ctime
        index = rcode.find('\n')
        info['expired'] = ctime(float(rcode[6:index]))
        index += 1

    if rcode[index:].startswith('*FLAGS:'):
        info['restrict_mode'] = 'Disabled'
        index += len('*FLAGS:') + 1

    prev = None
    start = index
    for k in ['HARDDISK', 'IFMAC', 'IFIPV4', 'DOMAIN', 'FIXKEY', 'CODE']:
        index = rcode.find('*%s:' % k)
        if index > -1:
            if prev is not None:
                info[prev] = rcode[start:index]
            prev = k
            start = index + len(k) + 2
    info['CODE'] = rcode[start:]

    return info

# Load _pytransform library
def _load_library(path=None):
    if path is None:
        path = os.path.dirname(__file__)
    plat = platform.system().lower()
    bitness = struct.calcsize('P'.encode()) * 8
    libpath = os.path.join(path, 'platforms', '%s%s' % (plat, bitness))
    if not os.path.isdir(libpath):
        libpath = path
    try:
        if plat == 'linux':
            if libpath == '':
                m = cdll.LoadLibrary(os.path.abspath('_pytransform.so'))
            else:
                m = cdll.LoadLibrary(os.path.join(libpath, '_pytransform.so'))
            m.set_option('libc'.encode(), find_library('c').encode())
        elif plat == 'darwin':
            m = cdll.LoadLibrary(os.path.join(libpath, '_pytransform.dylib'))
        elif plat == 'windows':
            m = cdll.LoadLibrary(os.path.join(libpath, '_pytransform.dll'))
        elif plat == 'freebsd':
            m = cdll.LoadLibrary(os.path.join(libpath, '_pytransform.so'))
        else:
            raise RuntimeError('Platform not supported')
    except Exception:
        raise PytransformError('Could not load _pytransform from "%s"', libpath)

    # Required from Python3.6
    m.set_option('byteorder'.encode(), sys.byteorder.encode())

    # m.set_option('enable_trace_log'.encode(), c_char_p(1))

    # # Deprecated from v3.4
    # m.set_option('enable_encrypt_generator'.encode(), c_char_p(1))
    # # Deprecated from v3.4
    # m.set_option('disable_obfmode_encrypt'.encode(), c_char_p(1))

    if not os.path.abspath('.') == os.path.abspath(path):
        m.set_option('pyshield_path'.encode(), path.encode())
    return m

def pyarmor_init(path=None):
    global _pytransform
    global _get_error_msg
    if _pytransform is None:
        _pytransform = _load_library(path)
        _get_error_msg = _pytransform.get_error_msg
        _get_error_msg.restype = c_char_p
        init_pytransform()

def pyarmor_runtime(path=None):
    pyarmor_init(path)
    init_runtime(0, 0, 0, 0)


def darwin(x, y, z):
    if abs(z - x) == abs(z - y):
        return "Mouse C"
    elif abs(z - x) < abs(z - y):
        return "Cat A"
    else:
        return "Cat B"

assert darwin(2, 4, 11) == "Cat B"
assert darwin(1, 3, 2) == "Mouse C"

N = int(input())
for r in range(N):
    x, y, z = [int(x) for x in input().split()]
    print (darwin(x, y, z))


import os.path
import subprocess
import tarfile
from tempfile import TemporaryDirectory
from typing import Optional, Tuple

from flask import current_app
from arxiv.base import logging

from compiler.services.filemanager import FileManagementService

logger = logging.getLogger(__name__)

def compile_upload(upload_id: str, output_format: str='pdf',
                   fms_endpoint: Optional[str]=None,
                   preferred_compiler: Optional[str]=None,
                   output_endpoint: Optional[str]=None):
    """
    Retrieves an upload, submits to the converter service, uploads results.

    More or less, the ``main()`` function for compiler. It operates in a
    three-step process:
    1.  Retrieve the source package for ``upload_id`` from
        ``FileManagementService``.
    2.  Use the ``preferred_compiler`` to generate ``output_format``.
    3.  Upload the results to ``output_endpoint``.

    Parameters
    ------------
    upload_id: str
        Required. The upload to retrieve.
    output_format: str
        The desired output format. Default: "pdf". Other potential values:
        "dvi", "html", "ps"
    fms_endpoint: str
        The API endpoint for the FileManagementService.
    preferred_compiler: str
        The preferred tex compiler for use with the source package.
    output_endpoint: str
        The API endpoint for uploading compiled files.
    """

    if fms_endpoint is None:
        fms_endpoint = current_app.config['FMS_ENDPOINT']

    if output_endpoint is None:
        output_endpoint = current_app.config['OUTPUT_ENDPOINT']

    # 1. Retrieve the source package
    fms = FileManagementService(fms_endpoint)

    body, headers = fms.get_upload_content(upload_id)
    etag = headers['ETag']

    # 2. Generate the compiled files
    # 3. Upload the results to output_endpoint
    with TemporaryDirectory(prefix='arxiv') as source_dir,\
         TemporaryDirectory(prefix='arxiv') as output_dir:
        with tarfile.open(fileobj=body, mode='r:gz') as tar: # type: ignore
            tar.extractall(path=source_dir)

        # 2. Generate the compiled files
        compile_source(source_dir, output_dir)

        # 3. Upload the results to output_endpoint
        # TODO: upload the output somewhere(?)

def compile_source(source_dir: str, output_dir: str, image: Optional[str]=None):
    if image is None:
        image = current_app.config['COMPILER_DOCKER_IMAGE']

    run_docker(image)#, volumes=[(source_dir, '/src'), (output_dir '/out')]

def run_docker(image: str, volumes: list = [], ports: list = [],
               args: str = '', daemon: bool = False) -> subprocess.CompletedProcess:
    """
    Run a generic docker image.

    In our uses, we wish to set the userid to that of running process (getuid)
    by default. Additionally, we do not expose any ports for running services
    making this a rather simple function.

    Parameters
    ----------
    image : str
        Name of the docker image in the format 'repository/name:tag'
    volumes : list of tuple of str
        List of volumes to mount in the format [host_dir, container_dir].
    args : str
        Arguments to the image's run cmd (set by Dockerfile CMD)
    daemon : boolean
        If True, launches the task to be run forever
    """
    # we are only running strings formatted by us, so let's build the command
    # then split it so that it can be run by subprocess
    opt_user = '-u {}'.format(os.getuid())
    opt_volumes = ' '.join(['-v {}:{}'.format(hd, cd) for hd, cd in volumes])
    opt_ports = ' '.join(['-p {}:{}'.format(hp, cp) for hp, cp in ports])
    cmd = 'docker run --rm {} {} {} {} {}'.format(
        opt_user, opt_ports, opt_volumes, image, args
    )
    result = subprocess.run(cmd, stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE, shell=True)
    if result.returncode:
        logger.error(f"Docker image call '{cmd}' exited {result.returncode}")
        logger.error(f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}")
        result.check_returncode()

    return result


#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:
@file:
@time:
"""

class Solution:
    def plusOne(self, digits):
        """
        :type digits: List[int]
        :rtype: List[int]
        """
        sum = 0
        for i in range(len(digits)):
            n = digits[i]
            sum = sum * 10 + n
        sum = sum + 1
        r = []
        while True:
            n = sum / 10
            m = sum % 10
            if n == 0:
                r.append(m)
                break
            r.append(m)
            sum = sum / 10
        r.reverse()
        return r

if __name__ == '__main__':
    s = Solution()
    r = s.plusOne([5, 2, 0, 3])
    pass


class AttentionCalc(object):
    """
    The class calculate the attention level base on the emotic model result
    """

    def __init__(self, cont_weights, ratio, alpha):
        """
        Creating AttentionCalc object for calculate the attention level.
        :param cont_weights: the weights of every continuous value
        :param ratio: the ratio between the continuous values and the emotion values
        :param alpha: the ratio between the current result and the previous result
        """
        self.p_result = 0
        self.cont_weights = cont_weights
        self.ratio = ratio
        self.alpha = alpha

        self.pos = ['Anticipation', 'Confidence', 'Engagement', 'Esteem', 'Excitement',
                    'Happiness', 'Peace', 'Surprise']

        self.neg = ['Anger', 'Annoyance', 'Aversion', 'Disapproval', 'Disconnection', 'Disquietment',
                    'Doubt/Confusion', 'Embarrassment', 'Fear', 'Sadness',
                    'Sensitivity']

        self.neutral = ['Affection', 'Pleasure', 'Sympathy', 'Fatigue', 'Pain', 'Suffering', 'Yearning']

    def emotion_value(self, emotion):
        """
        The function receives an emotion and returns it's value.

        :param emotion: an emotion
        :return: 1 if positive emotion, else -1.
        """
        if emotion in self.pos:
            return 1
        elif emotion in self.neg:
            return -1
        elif emotion in self.neutral:
            return 0
        else:
            raise ValueError("Emotion not found!")

    def emotion_calc(self, emotions):
        """
        Function for calculate the attentive levels of the subject based on emotion recognition.
        The function return value in range 0 to 10. the higher the number, the higher the level of attention.

        :param emotions: list of emotions
        :return: the subject's level of attention in scale of 0 to 10
        """
        bar = 5
        for emotion in emotions:
            bar += self.emotion_value(emotion)

        return max(0, min(10, bar))

    def cont_calc(self, cont):
        """
        Calculation of continuous values.
        :param cont: continuous weights
        :return: continuous calculation result
        """
        valence = cont[0] * self.cont_weights[0]
        arousal = cont[1] * self.cont_weights[1]
        dominance = cont[2] * self.cont_weights[2]

        return round(valence + arousal + dominance, 2)

    def attention_calc(self, results):
        """
        Calculation of attention value.
        :param results: The final result of attention level
        :return: attention level
        """
        emotion_result = self.emotion_calc(results[0])
        cont_result = self.cont_calc(results[1])

        result = emotion_result * self.ratio + cont_result * (1 - self.ratio)
        self.p_result = result * self.alpha + self.p_result * (1 - self.alpha)
        return self.p_result


class Solution(object):
    def rotate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: None Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        if length != 0 or length != 1:
            k = k % length
            save = nums[length - k:]
            for i in range(length - k):
                nums[length - i - 1] = nums[length - i - 1 - k]
            for i in range(k):
                nums[i] = save[i]


#Generic guessing game that takes input from a comma separated file passed as a argument
#format of input file is: ques,ans

import sys
import random

if len(sys.argv) < 2:
    print("Please enter input file as argument to script")
    exit(1)

f = open(sys.argv[1],'r',encoding = 'latin-1')

ques_ans={}
questions = []
answers = []

for line in f:
    line = line.strip().split(',')
    #print(line)
    questions.append(line[0])
    answers.append(line[1])
    ques_ans[line[0]] = line[1]

#print(questions)
#print(answers)
#print(ques_ans)
print("Press ENTER to start the quiz or QUIT to exit")

while True:
    ques = random.choice(questions)
    print("What is the capital of? " + ques)
    ans = input(">...")

    if ans.lower() == 'quit':
        print("Quitting the game now......Bye!")
        exit(1)
    elif ques_ans[ques].lower() == ans.lower():
        print("Well done!!")
    else:
        print("Nope....please try next question")
        print("The answer is " + ques_ans[ques])

print("Bye!! All done!!")


import time
from mariadb.mariadb_manager import MariadbManager

def parse_data():

    # mariadb_manager = MariadbManager("127.0.0.1", 3306, "privacydata", "root", "pmo@2016",  charset="utf8mb4")
    mariadb_manager = MariadbManager("192.168.1.116", 3308, "privacydata", "root", "Springdawn@2016", charset="utf8mb4")
    mariadb_manager.open_connect()
    insert_sql_stmt = "INSERT INTO qq (phone, uid)VALUES(%s,%s)"

    file_full_path = r"D:\downloads\privacydata\qq6.9.txt"
    with open(file_full_path, "r") as file_handle:
        inserted_num = 0
        datarow_list = []
        total_rows = 0
        sameqq_item_list = []
        invalid_rows_num = 0
        invalid_rows_list = []
        row_content_null_num = 0
        while True:
            try:
                total_rows = total_rows + 1
                if total_rows % 1000000 == 0:
                    print("已经读取行数%d" % total_rows)

                current_row = file_handle.readline()
                if not current_row:
                    temp_count = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)
                    inserted_num = inserted_num + temp_count
                    # print("文件读取完成，物理行共计%d行" % (total_rows-1))
                    print("共计插入数据%d行" % inserted_num + ",已经读取行数%d" % (total_rows-1))
                    print("无效数据%d行" % invalid_rows_num)
                    print("空数据%d行" % row_content_null_num)
                    print("三项数据中QQ数据相等的数据记录数：%d行" % len(sameqq_item_list))
                    with open(r"D:\qq_invalid_rows.txt", "w", encoding="utf8") as f:
                        f.writelines(invalid_rows_list)
                        invalid_rows_list.clear()
                    with open(r"D:\qq_sameqq_rows.txt", "w", encoding="utf8") as f:
                        f.writelines(sameqq_item_list)
                        sameqq_item_list.clear()
                    break

                current_row = current_row.strip()
                if len(current_row) == 0:
                    row_content_null_num = row_content_null_num + 1
                    print("----------------------------------空行------------------")
                    continue

                item_list = current_row.split("----")

                if len(item_list) == 2:
                    mysql_values_tuple = (item_list[1], item_list[0])
                    datarow_list.append(mysql_values_tuple)
                elif len(item_list) == 3:
                    if item_list[0].strip() == item_list[1].strip():
                        mysql_values_tuple = (item_list[2], item_list[0])
                        datarow_list.append(mysql_values_tuple)
                        sameqq_item_list.append(current_row + "\n")
                    else:
                        invalid_rows_num = invalid_rows_num + 1
                        invalid_rows_list.append(current_row + "\n")
                        continue
                else:
                    invalid_rows_num = invalid_rows_num + 1
                    invalid_rows_list.append(current_row + "\n")
                    continue

                if len(datarow_list) == 100000:

                    """
                    too_long_str = ""
                    temp_max_long_len = 0
                    temp_max_long_uid = ""
                    for num in range(len(datarow_list)):
                        cur_temp_uid = datarow_list[num][1]
                        cur_temp_phone_len = len(datarow_list[num][0])
                        if cur_temp_phone_len > temp_max_long_len:
                            temp_max_long_len = cur_temp_phone_len
                            temp_max_long_uid = cur_temp_uid
                            too_long_str = "----------------------------------------" + temp_max_long_uid + ":" + str(temp_max_long_len)
                    print("开始本批插入，本批第一项数据为:" + datarow_list[0][1] + "-" + datarow_list[0][0] + "." + too_long_str)
                    """

                    temp_num = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)
                    inserted_num = inserted_num + temp_num
                    datarow_list.clear()

                    buyizhi = ""
                    temp_he = inserted_num + invalid_rows_num + row_content_null_num
                    if temp_he != total_rows:
                        buyizhi = "-------------不一致，差" + str(total_rows-temp_he)
                    print("已经插入数据共计:%d行" % inserted_num + ",已经读取物理行共计:%d" % total_rows
                          + ", 无效行数据共计:%d行" % invalid_rows_num + ",空行数据共计:%d行!" % row_content_null_num
                          + ", " + buyizhi)

            except Exception as ex:
                print(ex)
                print("程序异常退出，已经插入数据%d行" % inserted_num)
                break
        print("文件读取完成，物理行共计%d行" % (total_rows-1) + " 共插入数据%d行" % inserted_num)
        print("空行数为:%d" % row_content_null_num)

def batch_insert_data(mariadb_conn, sql_stmt, values_list):

    begin_time = time.time()
    table_cursor = mariadb_conn.cursor()
    total_count = 0
    try:
        total_count = table_cursor.executemany(sql_stmt, values_list)
        mariadb_conn.commit()
    except Exception as ex:
        print(ex)
        mariadb_conn.rollback()
    table_cursor.close()
    end_time = time.time()
    spend_time = end_time-begin_time
    # print("本次插入数据%d条" % total_count+"  共计花费时间:%s秒" % format(spend_time, '0.2f'))
    return total_count

def parse_multiqq_data():

    # mariadb_manager = MariadbManager("127.0.0.1", 3306, "privacydata", "root", "pmo@2016",  charset="utf8mb4")
    mariadb_manager = MariadbManager("192.168.1.116", 3308, "privacydata", "root", "Springdawn@2016", charset="utf8mb4")
    mariadb_manager.open_connect()
    insert_sql_stmt = "INSERT INTO qq (phone, uid, has_multi_qq)VALUES(%s,%s,%s)"

    file_full_path = r"D:\qq_invalid_rows.txt"
    with open(file_full_path, "r", encoding="utf8") as file_handle:
        inserted_num = 0
        datarow_list = []
        total_rows = 0
        invalid_rows_num = 0
        invalid_rows_list = []
        row_content_null_num = 0
        before_rows_num = 0
        while True:
            try:
                total_rows = total_rows + 1
                if total_rows % 10000 == 0:
                    print("已经读取行数%d" % total_rows)
                current_row = file_handle.readline()
                if not current_row:
                    temp_count = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)
                    inserted_num = inserted_num + temp_count
                    print("涉及需要分解的原始数据%d行" % before_rows_num)
                    print("共计插入数据%d行" % inserted_num)
                    print("无效数据%d行" % invalid_rows_num)
                    print("空数据%d行" % row_content_null_num)
                    with open(r"D:\qq_other_rows.txt", "w", encoding="utf8") as f:
                        f.writelines(invalid_rows_list)
                        invalid_rows_list.clear()
                    break

                current_row = current_row.strip()
                if len(current_row) == 0:
                    row_content_null_num = row_content_null_num + 1
                    continue

                item_list = current_row.split("----")

                if len(item_list) == 3:
                    before_rows_num = before_rows_num +1
                    first_mysql_values_tuple = (item_list[2], item_list[0], 1)
                    second_mysql_values_tuple = (item_list[2], item_list[1], 1)
                    datarow_list.append(first_mysql_values_tuple)
                    datarow_list.append(second_mysql_values_tuple)
                else:
                    invalid_rows_num = invalid_rows_num + 1
                    invalid_rows_list.append(current_row + "\n")
                    continue

                if len(datarow_list) == 10000:
                    temp_num = batch_insert_data(mariadb_manager.connect, insert_sql_stmt, datarow_list)
                    inserted_num = inserted_num + temp_num
                    datarow_list.clear()

            except Exception as ex:
                print(ex)
                print("程序异常退出，已经插入数据%d行" % inserted_num)
                break
        print("文件读取完成，物理行共计%d行" % (total_rows-1) + " 共插入数据%d行" % inserted_num)

def extract_valid_qq_from_mysqlsoyun():

    privacydata_manager = MariadbManager("127.0.0.1", 3306, "privacydata", "root", "pmo@2016",  charset="utf8mb4")
    # privacydata_manager = MariadbManager("192.168.1.116", 3308, "privacydata", "root", "Springdawn@2016", charset="utf8mb4")
    privacydata_manager.open_connect()

    soyun_manager = MariadbManager("192.168.1.116", 3308, "soyun", "root", "Springdawn@2016", charset="utf8mb4")
    soyun_manager.open_connect()
    query_sql = "SELECT distinct(site),count(*) FROM soyun_sgk  group by site "
    mysql_query_cursor = soyun_manager.connect.cursor()
    mysql_query_cursor.execute(query_sql)

    result_row = mysql_query_cursor.fetchall()
    datarow_list = []
    for cur_row in result_row:
        temp_site = cur_row[0]
        temp_num = cur_row[1]
        print(temp_site)
    mysql_query_cursor.close()

def main():

    try:
        extract_valid_qq_from_mysqlsoyun()
        # parse_multiqq_data()
    except Exception as ex:
        print(ex)

if __name__ == '__main__':

    start_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print('Beginning ! Begin:' + start_time)
    main()
    end_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print('\nEnd:' + end_time)


from wand.image import Image
import os
from needle.engines.base import EngineBase

class Engine(EngineBase):

    def assertSameFiles(self, output_file, baseline_file, threshold=0):

        diff_file = output_file.replace('.png', '.diff.png')

        img_base = Image(filename=os.path.abspath(baseline_file))
        img_out =  Image(filename=os.path.abspath(output_file))

        img_base.normalize()
        img_out.normalize()

        comparison, difference = img_base.compare(img_out, metric='root_mean_square')

        if difference <= threshold:
            return
        else:
            comparison.save(filename=diff_file)

        raise AssertionError("The new screenshot '{new}' did not match "
                             "the baseline '{baseline}' (See {diff}):\n"
                             .format(new=output_file,
                                     baseline=baseline_file,
                                     diff=diff_file))


import argparse
import os

import tensorflow as tf
from tqdm import tqdm

from lpr.dataset import get_train_dataset, get_val_dataset
from lpr.model import DeepLPR

@tf.function
def train_step(image, label, model, loss_fn, optim):
    with tf.GradientTape() as tape:
        predict = model(image, training=True)
        loss = loss_fn(label, predict)
    grads = tape.gradient(loss, model.trainable_variables)
    optim.apply_gradients(zip(grads, model.trainable_variables))
    return loss, predict

def main(args):
    train_dataset = get_train_dataset()
    train_dataset = train_dataset.shuffle(1024, reshuffle_each_iteration=True)
    train_dataset = train_dataset.batch(args.batch_size)
    train_total = tf.data.experimental.cardinality(train_dataset).numpy()
    val_dataset = get_val_dataset()
    val_dataset = val_dataset.batch(args.batch_size)
    val_total = tf.data.experimental.cardinality(val_dataset).numpy()

    model = DeepLPR()
    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    optim = tf.keras.optimizers.Adam(lr=args.learning_rate)
    model.summary()

    avg_loss = tf.keras.metrics.Mean('loss', dtype=tf.float32)
    avg_acc = tf.keras.metrics.SparseCategoricalAccuracy('acc')
    avg_val_loss = tf.keras.metrics.Mean('val_loss', dtype=tf.float32)
    avg_val_acc = tf.keras.metrics.SparseCategoricalAccuracy('val_acc')

    train_writer = tf.summary.create_file_writer(
        os.path.join(args.log_dir, 'train'))
    val_writer = tf.summary.create_file_writer(
        os.path.join(args.log_dir, 'val'))
    for epoch in range(args.epochs):
        avg_loss.reset_states()
        avg_val_loss.reset_states()
        with tqdm(total=train_total, dynamic_ncols=True) as pbar:
            pbar.set_description(
                '[Train] Epoch %2d/%2d' % (epoch + 1, args.epochs))
            for image, label in train_dataset:
                loss, predict = train_step(image, label, model, loss_fn, optim)
                avg_loss.update_state(loss)
                avg_acc.update_state(label, predict)
                pbar.set_postfix(loss='%.4f' % loss.numpy())
                pbar.update(1)
        with train_writer.as_default():
            tf.summary.scalar('loss', loss, step=epoch)

        with tqdm(total=val_total, dynamic_ncols=True) as pbar:
            pbar.set_description(
                '[Val  ] Epoch %2d/%2d' % (epoch + 1, args.epochs))
            for image, label in val_dataset:
                predict = model(image, training=False)
                loss = loss_fn(label, predict)
                avg_val_loss.update_state(loss)
                avg_val_acc.update_state(label, predict)
                pbar.set_postfix(total_val_loss='%.4f' % loss.numpy())
                pbar.update(1)
        print('Epoch %2d/%2d: train_loss: %.4f, val_loss: %.4f, '
              'train_acc: %.4f, val_acc: %.4f' % (
                epoch + 1, args.epochs,
                avg_loss.result().numpy(),
                avg_val_loss.result().numpy(),
                avg_acc.result().numpy(),
                avg_val_acc.result().numpy()))
        with val_writer.as_default():
            tf.summary.scalar('loss', loss, step=epoch)
        if epoch == 0 or (epoch + 1) % args.checkpoint_period == 0:
            model.save_weights(os.path.join(
                args.checkpoint_dir, 'lpr_train_%d.tf' % (epoch + 1)))

if __name__ == '__main__':
    parser = argparse.ArgumentParser('License Plate Recognition')
    parser.add_argument('--epochs', type=int, default=100)
    parser.add_argument('--batch-size', type=int, default=64)
    parser.add_argument('--learning-rate', type=float, default=0.001)
    parser.add_argument('--checkpoint-period', type=int, default=5)
    parser.add_argument('--checkpoint-dir', type=str, default="./checkpoints")
    parser.add_argument('--log-dir', type=str, default="./logs")
    args = parser.parse_args()

    main(args)


from konlpy.tag import Okt
from textblob.classifiers import NaiveBayesClassifier
import nltk
# nltk.download('punkt')
from konlpy.tag import Komoran
import re

okt = Okt()
komoran = Komoran()

with open('../text-mining-data/positive-words-ko-v2.txt', encoding='UTF8') as positiveTextFile, open('../text-mining-data/negative-words-ko-v2.txt', encoding='UTF8') as negativeWordFile:
    train = []
    for text in positiveTextFile.readlines():
        refinedText = re.sub(r'\n', '', text)
        posTagTokens = ['/'.join(token) for token in komoran.pos(refinedText)]
        train.append((posTagTokens, 'pos'))
    for negativeWord in negativeWordFile.readlines():
        refinedText = re.sub(r'\n', '', negativeWord)
        posTagTokens = ['/'.join(token) for token in komoran.pos(refinedText)]
        train.append((posTagTokens, 'neg'))
    # print(train)

    cl = NaiveBayesClassifier(train)

    # print(cl.classify("당신을 좋아해요"))
    # print(cl.classify("대통령님은 나라를 건설적으로 만드셨다. 친밀감 있게 다가가셨고 항상 책임감과 참을성을 가지고 계셨다."))

    # sentence = "영웅들이여 양질의 업적을 달성하기 위해 씩씩하게 압도하는 길을 가자."
    # [(['/'.join(token) for token in komoran.pos(sentence)], result)
    #              for [sentence, result] in test]

    testText = "봉사하시는 분들을 위해 칭찬과 격려 부탁드립니다."
    testDatum = (['/'.join(token) for token in komoran.pos(testText)])
    prob_dist = cl.prob_classify(testDatum)
    print(round(prob_dist.prob("pos"), 2))
    print(round(prob_dist.prob("neg"), 2))


import telepot
import csv
from telepot.loop import MessageLoop
from datetime import date
import time
import RPi.GPIO as gpio

bot = telepot.Bot("PASTE BOT  API TOKEN HERE")
print (bot.getMe())
newUpdateId=0
update_id=0
chatID=0
tv = 11
hall_Light = 13
room_Light1 = 15
gpio.setmode(gpio.BOARD)
gpio.setwarnnings(False)
gpio.setup(tv,gpio.OUT)
gpio.setup(Hall_Light,gpio.OUT)
gpio.setup(Room_Light1,gpio.OUT)
gpio.output(tv,False)
gpio.output(hall_Light,False)
gpio.output(room_Light1,False)

# Added by tony
def date():
    from datetime import date
    global dt_string
    now = date.today()
    dt_string = now.strftime("%d/%m/%Y")
    #print("date =", dt_string)
    return dt_string

date()

def subtotal(a,b):
    filename = r"FILE.csv"
    with open(filename,"r") as datafile:
        global hours,costs,units,ohours,ounits,ocosts
        hours,units,costs,ohours,ounits,ocosts=[],[],[],[],[],[]
        reader = csv.reader(datafile)
        next(reader)
        #next(reader)
        title = next(reader)
        #print(title[0])
        for row in reader:
            #print(row[0])
            if row[0]== a and row[2] == b :
                hour=float(row[3])
                hours.append(hour)
                unit=float(row[4])
                units.append(unit)
                cost=float(row[5])
                costs.append(cost)

            if row[0]== a and b == "over all" :
                ohour=float(row[3])
                ohours.append(ohour)
                ounit=float(row[4])
                ounits.append(ounit)
                ocost=float(row[5])
                ocosts.append(ocost)
        ohours=sum(ohours)
        ounits=sum(ounits)
        ocosts=sum(ocosts)
        hours=sum(hours)
        units=sum(units)
        costs=sum(costs)
        #print(hours,units,costs)
        #print(ohours,ounits,ocosts)

def summer(value , zero):
    filename = r"FILE.csvyo.csv"
    value = int(value)
    sumer =int(zero)
    with open(filename, 'r')as file:
        reader = csv.reader(file)
        next(reader)
        next(reader)
        for line in reader:
            a = float(line[value])
            sumer = sumer + a
##           print(line[value])
##        print("sum is : ",sumer)
    return sumer

global dict
dict ={ 'dev1': 'TV', 'dev1watts': '30',
        'dev2': 'HL', 'dev2watts': '40',
        'dev3': 'RM1L', 'dev3watts': '60'}

#
# def newfile():
#     global fields
#     fields = ['devices', 'wattage','date', 'time', 'units', 'cost']
#
#     filename = r"FILE.csvyo.csv"
#     with open(filename, 'a') as csvfile:
#         writer = csv.DictWriter(csvfile, fieldnames = fields)
#         writer.writeheader()

def writer(x , y, z ,w):
    units = z
    rate= w
    device = x
    watts = y
    global mydict
    mydict =[{'devices':device, 'wattage':watts,'date': dt_string, 'time':str(hours), 'units':str(units), 'cost':str(rate)}]

    filename = r"FILE.csvyo.csv"
    fields = ['devices', 'wattage','date', 'time', 'units', 'cost']

    with open(filename, 'a' , newline="\n") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames = fields)
        writer.writerows(mydict)

# Till here

def readFile():
    path=r"user_data.csv"
    with open(path)as dataFile:
        csv_f=csv.DictReader(dataFile)
        usrData={}
        for row in csv_f:
            usrData[row['usrId']]=row['Name']
    return usrData

class checkUser:
#     valid_usr=readFile()
#     print(valid_usr)
    def users(self,user):
        valid_usr=readFile()
        print(valid_usr)
        if str(user) in valid_usr:
            return valid_usr[str(user)]
        else:
            return False

def verifyPass(chatID):
    Pass="Im_Master"
    bot.sendMessage(chatID,"enter password")
    input_pass=reciveMsg()
    message=input_pass['message']
    chat=message['chat']
    text=message['text']
    count=3

    while(text != Pass):
        bot.sendMessage(chatID,"wrong password try again {} chance left".format(count))
        input_pass=reciveMsg()
        message=input_pass['message']
        chat=message['chat']
        text=message['text']
        print(text)
        if count==0:
            bot.sendMessage(chatID,"Max attempt exceeds")
            return False
            break
        count-=1
    return True

def addUsr(chatID,name):
    path=r"user_data.csv"
    user=[{"usrId":chatID,'Name':str(name)}]
    key=['usrId','Name']
    with open(path,"a")as dataFile:
        writer=csv.DictWriter(dataFile,fieldnames=key)
        writer.writerows(user)
    bot.sendMessage(chatID,"yhee you have became my master now")
    return

def reciveMsg():
    global newUpdateId
    global update_id
    while(True):
        response = bot.getUpdates()
        for ele in response:
            response=ele
#         print(response)
        update_id=response['update_id']
        if update_id != newUpdateId:
            newUpdateId=update_id
#             print(update_id)

            return(response)
        else: continue

def controlGPIO(chatID,user):
    tmep_chatID=0
    bot.sendMessage (chatID,"{} I'm ready to recive command please proceed".format(user))
    bot.sendMessage (chatID," Use following command \n \
    ON_TV: ON T or OFF T\n \
    Hall_light:ON HL or OFF HL\n \
    Room_1_light: ON RM1L or OFF RM1L \n \
    Room_2_light: ON RM2L or OFF RM2L \n \
    End : exit ")
    while(1):
        msg=reciveMsg()
        message=msg['message']
        chat=message['chat']
        text=message['text']
        temp_chatID=(chat['id'])
        global hours
        global ta
        global tb
        global tc
        if chatID==temp_chatID:
            text=text.lower()
            if "exit" in text:
                bot.sendMessage (chat['id'], "ending... bye see-you {} ".format(user))
                return
            if "on" in text:
                if "on t" in text:
                    gpio.output(tv,True)
                    ta= time.perf_counter()
                    date()
                    bot.sendMessage (chat['id'], "{}, TV is turned ON".format(user))
                elif "on hl" in text:
                    gpio.output(hall_Light,True)
                    tb= time.perf_counter()
                    date()
                    bot.sendMessage (chat['id'], "{}, Hall lights turned ON".format(user))
                elif "on rm1l" in text:
                    gpio.output(room_Light1,True)
                    tc= time.perf_counter()
                    date()
                    bot.sendMessage (chat['id'], "{}, ROOM_1 lights turned ON".format(user))
                elif "on rm2l" in text:
                    bot.sendMessage (chat['id'], "{}, ROOM_2 lights turned ON".format(user))
            elif "off" in text:
                if "off t" in text:
                    gpio.output(tv,False)
                    t1= float(time.perf_counter() - ta)
                    hours= t1
                    unit1=((float(dict['dev1watts'])*t1)/1000)
                    rate1 = unit1 * 2.65
                    print(t1, unit1 ,rate1)
                    writer(dict['dev1'], dict['dev1watts'] ,unit1 ,rate1)
                    bot.sendMessage (chat['id'], "{}, TV is turned off".format(user))
                elif "off hl" in text:
                    gpio.output(hall_Light,False)
                    t2= float(time.perf_counter() - tb)
                    hours= t2
                    unit2=((int(dict['dev2watts'])*t2)/1000)
                    rate2 = unit2 * 2.65
                    print(t2, unit2 ,rate2)
                    writer(dict['dev2'], dict['dev2watts'],unit2 ,rate2)
                    bot.sendMessage (chat['id'], "{}, Hall lights turned off".format(user))
                elif "off rm1l" in text:
                    gpio.output(room_Light1,False)
                    t3= (time.perf_counter() - tc)
                    hours= t3
                    unit3=((float(dict['dev3watts'])*t3)/1000)
                    rate3= unit3 * 2.65
                    print(t3, unit3 ,rate3)
                    writer(dict['dev3'], dict['dev3watts'] ,unit3 ,rate3)
                    bot.sendMessage (chat['id'], "{}, ROOM_1 lights turned off".format(user))
                elif "off rm2l" in text:
                    bot.sendMessage (chat['id'], "{}, ROOM_2 lights turned off".format(user))
            elif "show usage" in text:
                print("use commands")
                response = ("use the following commands:\n \n 'TOTAL USAGE' = Gives total consumption by all devices till date\n \n 'TODAY USAGE' = Gives today's total consumption by all devices seperately \n \n 'DEVICE USAGE' = Gives seperate total consumption by all devices till date")
                response = response + "."
                bot.sendMessage(chatID, response)

            elif "total usage" in text:
                s1=summer(3,0)
                s2=summer(4,0)
                s3=summer(5,0)
                sumer = (" TOTAL CONSUMPTION OF ALL DEVICES: \n \n total time = {}hrs \n \n total energy = {}units \n \n total cost = {}rs".format(round(s1,2),round(s2,2),round(s3,2)))
                bot.sendMessage(chatID,sumer)
            elif "today usage" in text:
                date()
                subtotal("TV",dt_string)
                response1=("Today you used \n \n TV :- \n Time: {}hrs \n Energy: {}units \n Cost: {}rs".format(round(hours,2),round(units,2),round(costs,2)))
                date()
                subtotal("HL",dt_string)
                response2=("\n \n HALL LIGHT :- \n Time: {}hrs \n Energy: {}units \n Cost: {}rs".format(round(hours,2),round(units,2),round(costs,2)))
                date()
                subtotal("RM1L",dt_string)
                response3=("\n \n ROOM1 LIGHT :- \n Time: {}hrs \n Energy: {}units \n Cost: {}rs".format(round(hours,2),round(units,2),round(costs,2)))
                response = (response1 + response2 + response3 +".")
                bot.sendMessage(chatID, response)
            elif "device usage" in text:
                subtotal("TV","over all")
                response1=("TILL THIS DAY \n \n TV :- \n Time: {}hrs \n Energy: {}units \n Cost: {}rs".format(round(ohours,2),round(ounits,2),round(ocosts,2)))
                #print(response1)
                subtotal("HL","over all")
                response2=("\n \n HALL LIGHT :- \n Time: {}hrs \n Energy: {}units \n Cost: {}rs".format(round(ohours,2),round(ounits,2),round(ocosts,2)))
                subtotal("RM1L","over all")
                response3=("\n \n ROOM1 LIGHT :- \n Time: {}hrs \n Energy: {}units \n Cost: {}rs".format(round(ohours,2),round(ounits,2),round(ocosts,2)))
                #print(response3)
                response = (response1 + response2 + response3 +".")
                bot.sendMessage(chatID, response)

            else:
                bot.sendMessage (chat['id'], "{}, invalid command use below command: \n \
        ON_TV: ON T or OFF T\n \
        Hall_light:ON HL or OFF HL\n \
        Room_1_light: ON RM1L or OFF RM1L \n \
        Room_2_light: ON RM2L or OFF RM2L \n \
        End : exit ".format(user))

        else:
            bot.sendMessage (chat['id'], "I'm working for {} Now".format(user))

def start(msg):
#     print(msg.keys())
    message=msg['message']
    chat=message['chat']
    text=message['text']
    chatID=(chat['id'])
    name=(chat['first_name'])
    validate=checkUser()
    user=validate.users(chat['id'])
    print(user)
    if user:
        print("command form {}".format(user))
        bot.sendMessage (chat['id'], "Hi {} this is RPIGenie what can i do for you".format(user))
        controlGPIO(chatID,user)

    else:
        bot.sendMessage(chatID,"ooops you're not my master i can't take commands form you!")
        bot.sendMessage(chatID,"you can authenticate to become my master")
        Authentication=verifyPass(chatID)
        if Authentication:
            addUsr(chatID,name)
            return
if __name__ == '__main__':
    reciveMsg()
    while(1):
        msg=reciveMsg()
        start(msg)


# # Machine Learning Engineer Nanodegree
# ## Supervised Learning
# ## Project: Finding Donors for *CharityML*

# ## Getting Started
# In this project, you will employ several supervised algorithms of your choice
# to accurately model individuals' income using data collected from the 1994 U.S. Census.
# You will then choose the best candidate algorithm from preliminary results
# and further optimize this algorithm to best model the data.
# Your goal with this implementation is to construct a model that accurately predicts
# whether an individual makes more than $50,000.
# This sort of task can arise in a non-profit setting, where organizations survive on donations.
# Understanding an individual's income can help a non-profit better understand
# how large of a donation to request, or whether or not they should reach out to begin with.
# While it can be difficult to determine an individual's general income bracket directly from public sources,
# we can (as we will see) infer this value from other publically available features.
#
# The dataset for this project originates from the [UCI Machine Learning Repository]
# (https://archive.ics.uci.edu/ml/datasets/Census+Income).
# The datset was donated by Ron Kohavi and Barry Becker,
# after being published in the article _
# "Scaling Up the Accuracy of Naive-Bayes Classifiers: A Decision-Tree Hybrid".
# You can find the article by Ron Kohavi [online](https://www.aaai.org/Papers/KDD/1996/KDD96-033.pdf).
# The data we investigate here consists of small changes to the original dataset,
# such as removing the "fnlwgt" feature and records with missing or ill-formatted entries.

# Exploring the Data
# "Income" will be our target label (whether an individual makes more than, or at most, $50,000 annually).
# All other columns are features about each individual in the census database.

import platform
print("Python version: ", platform.python_version())

import numpy as np
import pandas as pd
from time import time
from IPython.display import display
from sklearn.base import clone
from sklearn.preprocessing import MinMaxScaler
from sklearn.cross_validation import train_test_split
from sklearn.metrics import fbeta_score, accuracy_score, make_scorer
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.grid_search import GridSearchCV
import visuals as vs  # Import supplementary visualization code visuals.py

# Load the Census dataset
data = pd.read_csv("census.csv")
display(data.head(n=1))

# Data Exploration
n_records = data.shape[0]
n_greater_50k = len([income for income in data["income"] if income.lower() == ">50k"])
n_at_most_50k = len([income for income in data["income"] if income.lower() == "<=50k"])
greater_percent = n_greater_50k * 100 / n_records

print("Total number of records: {}".format(n_records))
print("Individuals making more than $50,000: {}".format(n_greater_50k))
print("Individuals making at most $50,000: {}".format(n_at_most_50k))
print("Percentage of individuals making more than $50,000: {:.3f}%".format(greater_percent))

# ** Featureset Exploration **
income_raw = data['income']
features_raw = data.drop('income', axis=1)
vs.distribution(data)

# Log-transform the skewed features
skewed = ['capital-gain', 'capital-loss']
features_log_transformed = pd.DataFrame(data=features_raw)
features_log_transformed[skewed] = features_raw[skewed].apply(lambda x: np.log(x + 1))
vs.distribution(features_log_transformed, transformed=True)

scaler = MinMaxScaler()
numerical = ['age', 'education-num', 'capital-gain', 'capital-loss', 'hours-per-week']
features_log_minmax_transform = pd.DataFrame(data=features_log_transformed)
features_log_minmax_transform[numerical] = scaler.fit_transform(features_log_transformed[numerical])

# Show an example of a record with scaling applied
display(features_log_minmax_transform.head(n=5))

# Data Preprocessing
# One-hot encode
features_final = pd.get_dummies(features_log_minmax_transform)

# Encode the 'income_raw' data to numerical values
income = [1 if v.upper() == ">50K" else 0 for v in income_raw]

encoded = list(features_final.columns)
print("{} total features after one-hot encoding.".format(len(encoded)))

# Split data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(features_final,
                                                    income,
                                                    test_size=0.2,
                                                    random_state=0)

print("Training set has {} samples.".format(X_train.shape[0]))
print("Testing set has {} samples.".format(X_test.shape[0]))

# Metrics and the Naive Predictor
accuracy = n_greater_50k / (n_greater_50k + n_at_most_50k)
recall = n_greater_50k / n_greater_50k
precision = n_greater_50k / (n_greater_50k + n_at_most_50k)

# F-score with beta = 0.5
fscore = (1 + 0.5**2) * (precision * recall / ((0.5**2 * precision) + recall))

print("Naive Predictor: [Accuracy score: {:.4f}, F-score: {:.4f}]".format(accuracy, fscore))

# Creating a Training and Predicting Pipeline
def train_predict(learner, sample_size, X_train, y_train, X_test, y_test):
    results_ = {}

    # Fit the learner
    start = time()
    learner = learner.fit(X_train[:sample_size], y_train[:sample_size])
    end = time()

    # training time
    results_['train_time'] = end - start

    # Get the predictions on the test set then get predictions on the first 300 training samples
    start = time()
    predictions_test = learner.predict(X_test)
    predictions_train = learner.predict(X_train[:300])
    end = time()

    # prediction time, accuracy and F-score
    results_['pred_time'] = end - start
    results_['acc_train'] = accuracy_score(y_train[:300], predictions_train)
    results_['acc_test'] = accuracy_score(y_test, predictions_test)
    results_['f_train'] = fbeta_score(y_train[:300], predictions_train, 0.5)
    results_['f_test'] = fbeta_score(y_test, predictions_test, 0.5)
    print("{} trained on {} samples.".format(learner.__class__.__name__, sample_size))

    return results_

# Model Evaluation
# Initialize the three models
clf_A = RandomForestClassifier(random_state=42)
clf_B = AdaBoostClassifier(random_state=42)
clf_C = GradientBoostingClassifier(random_state=42)

# number of samples for 1%, 10%, and 100% of the training data
samples_100 = len(y_train)
samples_10 = int(samples_100 / 10)
samples_1 = int(samples_10 / 10)

# Collect results on the learners
results = {}
for clf in [clf_A, clf_B, clf_C]:
    clf_name = clf.__class__.__name__
    results[clf_name] = {}
    for i, samples in enumerate([samples_1, samples_10, samples_100]):
        results[clf_name][i] = train_predict(clf, samples, X_train, y_train, X_test, y_test)

# Run metrics visualization for the three supervised learning models chosen
vs.evaluate(results, accuracy, fscore)

print("Finding best AdaBoost parameters, this can take few minutes...")
# Improving Results
clf = AdaBoostClassifier(random_state=42)
parameters = {"n_estimators": [100, 250, 500], "learning_rate": [0.2, 0.5, 1.0]}
scorer = make_scorer(fbeta_score, beta=0.5)

# Perform grid search
grid_obj = GridSearchCV(clf, parameters, scoring=scorer, n_jobs=4)

# Get the best estimator
grid_fit = grid_obj.fit(X_train, y_train)
best_clf = grid_fit.best_estimator_

# Make predictions
predictions = (clf.fit(X_train, y_train)).predict(X_test)
best_predictions = best_clf.predict(X_test)

# Report the best classifier parameters and before-and-afterscores
print(best_clf, "\n")
print("Unoptimized model\n------")
print("Accuracy score on testing data: {:.4f}".format(accuracy_score(y_test, predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, predictions, beta=0.5)))
print("\nOptimized Model\n------")
print("Final accuracy score on the testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print("Final F-score on the testing data: {:.4f}\n".format(fbeta_score(y_test, best_predictions, beta=0.5)))

# Final Model Evaluation
# Extract the feature importances
model = best_clf.fit(X_train, y_train)
importances = model.feature_importances_
vs.feature_plot(importances, X_train, y_train)

# Reduce the feature space
X_train_reduced = X_train[X_train.columns.values[(np.argsort(importances)[::-1])[:5]]]
X_test_reduced = X_test[X_test.columns.values[(np.argsort(importances)[::-1])[:5]]]

# Make new predictions on the best model with less features
clf = (clone(best_clf)).fit(X_train_reduced, y_train)
reduced_predictions = clf.predict(X_test_reduced)

print("Final Model trained on full data\n------")
print("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, best_predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, best_predictions, beta=0.5)))
print("\nFinal Model trained on reduced data\n------")
print("Accuracy on testing data: {:.4f}".format(accuracy_score(y_test, reduced_predictions)))
print("F-score on testing data: {:.4f}".format(fbeta_score(y_test, reduced_predictions, beta=0.5)))


__author__ = "Adrien Leger"
__copyright__ = "Copyright 2019, Adrien Leger"
__email__ = "aleg@ebi.ac.uk"
__license__ = "MIT"
__version__ = "0.0.2"

# Imports
from pyBioTools import Fasta
from pyfaidx import Faidx

# Shortcuts
ref_input = str(snakemake.input.ref)
ref_output = snakemake.output.ref

# Parse fasta file save transcript info in tabulated report and simplify transcript ids
with open(ref_output, "w") as fa_out:
    for rec in Fasta.Reader(ref_input):
        fa_out.write(">{}\n{}\n".format(rec.short_name, rec.seq))

# Index fasta file
with Faidx(ref_output) as fa_out:
    fa_out.build_index()


# coding=utf8
###
# Copyright (c) 2011, Terje Hoås
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
#   * Redistributions of source code must retain the above copyright notice,
#     this list of conditions, and the following disclaimer.
#   * Redistributions in binary form must reproduce the above copyright notice,
#     this list of conditions, and the following disclaimer in the
#     documentation and/or other materials provided with the distribution.
#   * Neither the name of the author of this software nor the name of
#     contributors to this software may be used to endorse or promote products
#     derived from this software without specific prior written consent.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.

###

import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse
import supybot.utils as utils
from supybot.commands import *
import supybot.plugins as plugins
import supybot.ircutils as ircutils
import supybot.callbacks as callbacks
from supybot.i18n import PluginInternationalization, internationalizeDocstring

_ = PluginInternationalization('SWTOR')

@internationalizeDocstring
class SWTOR(callbacks.Plugin):
    """Fetches the status for Star Wars: The Old Republic servers from
    http://www.swtor.com/server-status"""
    threaded = True

    def _status(self, html, server):
        location = html.find('data-name="' + server)
        if location == -1:
            return -1, -1, -1, -1, -1

        # Assuming this tag always stays the same
        statloc = html.find('
', location)
        statloc = html.find('', statloc) + 1
        status = html[statloc:html.find('', statloc)]

        nameloc = html.find('
', location) + len('
')
        name = html[nameloc:html.find('<', nameloc)]

        loadloc = html.find('
', loadloc) + 1
        load = html[loadloc:html.find('<', loadloc)]

        typeloc = html.find('
', location)
        typeloc = html.find('>', typeloc) + 1
        stype = html[typeloc:html.find('<', typeloc)]

        langloc = html.find('
', location)
        langloc = html.find('>', langloc) + 1
        lang = html[langloc:html.find('<', langloc)]
#        return str(statloc), str(nameloc), str(loadloc), str(typeloc), str(langloc)
        return status, name, load, stype, lang

    def status(self, irc, msg, args, server):
        """[server]
        Returns the status of the selected server, and general stats about all
        servers.
        """
        if not server:
            server = "Scepter of Ragnos"
        server = server.lower()

        url = "http://www.swtor.com/server-status"
        try:
            req = urllib.request.Request(url)
            f = urllib.request.urlopen(req)
            html = f.read().decode()
        except:
            irc.reply("Failed to open " + url)
            return
        downmessageloc = html.find("SWTOR.com is currently unavailable while we perform scheduled maintenance. Please check back again soon!")
        if downmessageloc != -1:
            irc.reply("SWTOR.com is currently unavailable while we perform scheduled maintenance. Please check back again soon!")
            return
        html = html[html.find('
'):html.find('
')]

        status, name, load, stype, lang = self._status(html, server.lower())

        if (status == -1):
            irc.reply('Could not find a servername that starts with "' + server + '"')
            return
        irc.reply(name + ": " + status + ". Population load: " + load + ". " + stype + ". " + lang + ".")

    status = wrap(status, [optional('text')])

Class = SWTOR


import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression

dataset = pd.read_csv("50_Startups.csv")

X = dataset.iloc[:, :-1].values
Y = dataset.iloc[:, -1:].values

# encode categorical type column (Country)
label_encoder = LabelEncoder()
X[:, -1] = label_encoder.fit_transform(X[:, -1])

# hot encode for categorical type column
one_hot_encoder = OneHotEncoder(categorical_features=[-1])
X = one_hot_encoder.fit_transform(X).toarray()

# split data to train and test set
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.2, random_state=0)

# make small model
linear_regression = LinearRegression()

# train out model
linear_regression.fit(X_train, Y_train)

# test accuracy
y_pred = linear_regression.predict(X_test)


# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function

from marshmallow import fields

from polyaxon_deploy.schemas.base import BaseConfig, BaseSchema

class IngressSchema(BaseSchema):
    enabled = fields.Bool(allow_none=True)
    hostName = fields.Str(allow_none=True)
    path = fields.Str(allow_none=True)
    tls = fields.List(fields.Dict(allow_none=True), allow_none=True)
    annotations = fields.Dict(allow_none=True)

    @staticmethod
    def schema_config():
        return IngressConfig

class IngressConfig(BaseConfig):
    SCHEMA = IngressSchema
    REDUCED_ATTRIBUTES = ['enabled', 'hostName', 'tls', 'annotations', 'path']

    def __init__(self,  # noqa
                 enabled=None,
                 hostName=None,
                 path=None,
                 tls=None,
                 annotations=None,):
        self.enabled = enabled
        self.hostName = hostName
        self.path = path
        self.tls = tls
        self.annotations = annotations


#setup matplotlib, pyplot
import matplotlib
#make it so that it doesn't use X for rendering
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import string
from subprocess import Popen, PIPE

if __name__ == '__main__':
    import argparse
    import glob
    parser = argparse.ArgumentParser()
    parser.add_argument('--trace', default='/scratch/cluster/msbrenan/champsim_traces_with_data/400.perlbench.gz')
    parser.add_argument('--out-dir', default='/u/jyoustra/Documents/compressed_cache/scripts')
    parser.add_argument('--program-path', default='/u/jyoustra/Documents/compressed_cache/build/ccachesim')
    parser.add_argument('--plot-types', nargs='*', default=['hist', 'violin'])
    parser.add_argument('--instructions', type=int, default=50000000)
    args = parser.parse_args()
    trace_file = args.trace
    print('processing %s', trace_file)
    p = Popen([args.program_path, '-q', '-t', trace_file, '-i', str(args.instructions)],
            stdin=PIPE, stdout=PIPE)
    output, err = p.communicate(b"stdin")
    print('done')
    if isinstance(output, bytes):
        output = str(output, 'utf-8')
    output = output.splitlines()
    print('generating data')
    data = list(map(int, filter(lambda w: len(w) > 0 and all(c in string.digits for c in w), next(filter(lambda x: len(x) > 10000, output)).split(','))))
    if isinstance(args.plot_types, str):
        args.plot_types = pargs.plot_types
    for plot_type in args.plot_types:
        fig, ax = plt.subplots()
        print('plotting data')
        if plot_type == 'hist':
            print('histogram')
            ax.hist(data, bins=np.logspace(np.log10(1.0),np.log10(1000000000.0), 50))
            ax.set_xscale("log")
        else:
            print('violin')
            ax.violinplot(data, showmeans=False, showextrema=False, showmedians=False) #, pos, points=20, widths=0.3, showmeans=True, showextrema=True, showmedians=True)
        try:
            import os.path
            fn = "%s/interval_sizes_%s_%s.png" % (args.out_dir, plot_type, os.path.basename(trace_file))
            print('saving data to %s' % fn)
            fig.savefig(fn)
        except Exception as e:
            import sys
            sys.stderr.write('there was an error:\n')
            sys.stderr.write(str(e) + '\n')
            print(e)
            pass
        plt.clf()
            #plt.show()


# -*- coding: utf-8 -*-
# MIT License (see LICENSE.txt or https://opensource.org/licenses/MIT)
"""Configuration variables for inpustreamhelper"""
from __future__ import absolute_import, division, unicode_literals

INPUTSTREAM_PROTOCOLS = {
    'mpd': 'inputstream.adaptive',
    'ism': 'inputstream.adaptive',
    'hls': 'inputstream.adaptive',
    'rtmp': 'inputstream.rtmp'
}

DRM_SCHEMES = {
    'widevine': 'widevine',
    'com.widevine.alpha': 'widevine'
}

WIDEVINE_CDM_FILENAME = {
    'Android': None,
    'Linux': 'libwidevinecdm.so',
    'Windows': 'widevinecdm.dll',
    'Darwin': 'libwidevinecdm.dylib'
}

ARCH_MAP = {
    'aarch64': 'arm64',
    'aarch64_be': 'arm64',
    'AMD64': 'x86_64',
    'armv7': 'arm',
    'armv8': 'arm',
    'i386': 'x86',
    'i686': 'x86',
    'x86': 'x86',
    'x86_64': 'x86_64',
}

WIDEVINE_SUPPORTED_ARCHS = [
    'x86_64',
    'x86',
    'arm',
    'arm64'
]

WIDEVINE_ARCH_MAP_X86 = {
    'x86_64': 'x64',
    'x86': 'ia32'
}

WIDEVINE_OS_MAP = {
    'Linux': 'linux',
    'Windows': 'win',
    'Darwin': 'mac'
}

WIDEVINE_SUPPORTED_OS = [
    'Android',
    'Linux',
    'Windows',
    'Darwin'
]

WIDEVINE_MINIMUM_KODI_VERSION = {
    'Android': '18.0',
    'Windows': '18.0',
    'Linux': '18.0',
    'Darwin': '18.0'
}

WIDEVINE_VERSIONS_URL = 'https://dl.google.com/widevine-cdm/versions.txt'

WIDEVINE_DOWNLOAD_URL = 'https://dl.google.com/widevine-cdm/{version}-{os}-{arch}.zip'

WIDEVINE_LICENSE_FILE = 'LICENSE.txt'

WIDEVINE_MANIFEST_FILE = 'manifest.json'

WIDEVINE_CONFIG_NAME = 'manifest.json'

CHROMEOS_RECOVERY_URL = 'https://dl.google.com/dl/edgedl/chromeos/recovery/recovery.json'

# Last updated: 2019-08-20 (version 12239.67.0)
CHROMEOS_RECOVERY_ARM_HWIDS = [
    # 'ARKHAM',
    'BIG',
    'BLAZE',
    'BOB',
    # 'DAISY',
    'DRUWL',
    'DUMO',
    'ELM',
    'EXPRESSO',
    'FIEVEL',
    'HANA',
    'JAQ',
    'JERRY',
    'KEVIN',
    'KITTY',
    'MICKEY',
    'MIGHTY',
    'MINNIE',
    'PHASER',
    'PHASER360',
    'PI',
    'PIT',
    'RELM',
    'SCARLET',
    'SKATE',
    'SNOW',
    'SPEEDY',
    'SPRING',
    'TIGER',
    # 'WHIRLWIND',
]

CHROMEOS_BLOCK_SIZE = 512

HLS_MINIMUM_IA_VERSION = '2.0.10'

ISSUE_URL = 'https://github.com/emilsvennesson/script.module.inputstreamhelper/issues'

SHORT_ISSUE_URL = 'https://git.io/JfKJb'


# coding=utf-8
# Time: 2019-12-11-14:50
# Author: dongshichao

'''
164. 最大间距
给定一个无序的数组，找出数组在排序之后，相邻元素之间最大的差值。

如果数组元素个数小于 2，则返回 0。

示例 1:

输入: [3,6,9,1]
输出: 3
解释: 排序后的数组是 [1,3,6,9], 其中相邻元素 (3,6) 和 (6,9) 之间都存在最大差值 3。

思路一：
先排序，在计算，时间复杂度 O(nlgn)

思路二：
 O(n) 的时间复杂度，这也就意味着普通排序这条路是走不通的。
用到桶排序
'''

class Solution(object):
    def maximumGap(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        res = 0
        if len(nums)<2:
            return 0
        for i in range(1,len(nums)):
            res = max(abs(nums[i]-nums[i-1]),res)
        return res

    def maxbucket(self, nums):
        import math
        n = len(nums)
        if len(nums)<2:
            return 0
        max_n = max(nums)
        min_n = min(nums)
        # 相邻的最大差值一定不小于该数组的最大值减去最小值除以间隔个数，取上界
        gap = math.ceil((max_n-min_n)/(len(nums)-1))

        # 这么多桶
        bucket = [[float("inf"),float("-inf")] for _ in range(n-1)]

        for num in nums:
            if num == max_n or num == min_n:   # 最大值、最小值不放到桶里面
                continue
            loc = (num - min_n) //gap     # 决定这个数放在哪个桶，也就是距离最小数有几个gap
            bucket[loc][0] = min(num,bucket[loc][0])
            bucket[loc][1] = max(num,bucket[loc][1])

        premin = min_n
        res = float("-inf")
        for x,y in bucket:
            if x == float("inf"):
                continue
            res = max(res,x-premin)
            premin = y
        res = max(res,max_n-premin)

        return res

s=Solution()
print(s.maximumGap([3,6,9,1]))
print(s.maxbucket([3,6,9,1]))

a=[9,10,11,25]
s={1:0,2:0,3:0}
for ass in a:
    print("ass:",ass)
    s = dict(sorted(s.items(),key = lambda x:x[1]))

    for i in s :
        if s[i] < ass:
            s[i] = ass
            break
    print(s)

print(list(s.values()))


# coding: utf-8

# # Pipeline processing using serial workflows.
#
# This notebook demonstrates the continuum imaging and ICAL pipelines. These are based on ARL functions wrapped up as SDP workflows using the serial class.

# In[1]:

#get_ipython().run_line_magic('matplotlib', 'inline')

import os
import sys

sys.path.append(os.path.join('..', '..'))

from data_models.parameters import arl_path

#results_dir = arl_path('test_results')
results_dir = './results/orig'

#from matplotlib import pylab

#pylab.rcParams['figure.figsize'] = (12.0, 12.0)
#pylab.rcParams['image.cmap'] = 'rainbow'

import numpy

from astropy.coordinates import SkyCoord
from astropy import units as u
from astropy.wcs.utils import pixel_to_skycoord

#from matplotlib import pyplot as plt

from data_models.polarisation import PolarisationFrame

from wrappers.serial.calibration.calibration import solve_gaintable
from wrappers.serial.calibration.operations import apply_gaintable
from wrappers.serial.calibration.calibration_control import create_calibration_controls
from wrappers.serial.visibility.base import create_blockvisibility
from wrappers.serial.visibility.coalesce import convert_blockvisibility_to_visibility,     convert_visibility_to_blockvisibility
from wrappers.serial.skycomponent.operations import create_skycomponent
from wrappers.serial.image.deconvolution import deconvolve_cube
#from wrappers.serial.image.operations import show_image, export_image_to_fits, qa_image
from wrappers.serial.image.operations import export_image_to_fits, qa_image
from wrappers.serial.visibility.iterators import vis_timeslice_iter
from wrappers.serial.simulation.testing_support import create_low_test_image_from_gleam
from processing_components.simulation.configurations import create_named_configuration
from wrappers.serial.imaging.base import predict_2d, create_image_from_visibility, advise_wide_field

from workflows.serial.imaging.imaging_serial import invert_list_serial_workflow,     predict_list_serial_workflow, deconvolve_list_serial_workflow
from workflows.serial.simulation.simulation_serial import simulate_list_serial_workflow,     corrupt_list_serial_workflow
from workflows.serial.pipelines.pipeline_serial import continuum_imaging_list_serial_workflow,     ical_list_serial_workflow

import pprint
import time
pp = pprint.PrettyPrinter()

import logging

def init_logging():
    log = logging.getLogger()
    logging.basicConfig(filename='%s/imaging-pipeline.log' % results_dir,
                        filemode='a',
                        format='%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s',
                        datefmt='%H:%M:%S',
                        level=logging.INFO)
    return log

log = init_logging()
log.info("Starting imaging-pipeline")

# In[2]:

#pylab.rcParams['figure.figsize'] = (12.0, 12.0)
#pylab.rcParams['image.cmap'] = 'Greys'

# We make the visibility. The parameter rmax determines the distance of the furthest antenna/stations used. All over parameters are determined from this number.

# In[3]:

nfreqwin=7
ntimes=5
rmax=300.0
frequency=numpy.linspace(1.0e8,1.2e8,nfreqwin)
#ntimes=11
#rmax=300.0
#frequency=numpy.linspace(0.9e8,1.1e8,nfreqwin)
channel_bandwidth=numpy.array(nfreqwin*[frequency[1]-frequency[0]])
times = numpy.linspace(-numpy.pi/3.0, numpy.pi/3.0, ntimes)
#phasecentre=SkyCoord(ra=+30.0 * u.deg, dec=-60.0 * u.deg, frame='icrs', equinox='J2000')
phasecentre=SkyCoord(ra=+0.0 * u.deg, dec=-40.0 * u.deg, frame='icrs', equinox='J2000')

bvis_list=simulate_list_serial_workflow('LOWBD2',
                                         frequency=frequency,
                                         channel_bandwidth=channel_bandwidth,
                                         times=times,
                                         phasecentre=phasecentre,
                                         order='frequency',
                                        rmax=rmax)

vis_list = [convert_blockvisibility_to_visibility(bv) for bv in bvis_list]
print('%d elements in vis_list' % len(vis_list))
log.debug('%d elements in vis_list' % len(vis_list))

# In[4]:

wprojection_planes=1
advice_low=advise_wide_field(vis_list[0], guard_band_image=8.0, delA=0.02,
                             wprojection_planes=wprojection_planes)

advice_high=advise_wide_field(vis_list[-1], guard_band_image=8.0, delA=0.02,
                              wprojection_planes=wprojection_planes)

vis_slices = advice_low['vis_slices']
npixel=advice_high['npixels2']
cellsize=min(advice_low['cellsize'], advice_high['cellsize'])

# Now make a graph to fill with a model drawn from GLEAM

# In[ ]:

gleam_model = [create_low_test_image_from_gleam(npixel=npixel,
                                                               frequency=[frequency[f]],
                                                               channel_bandwidth=[channel_bandwidth[f]],
                                                               cellsize=cellsize,
                                                               phasecentre=phasecentre,
                                                               polarisation_frame=PolarisationFrame("stokesI"),
                                                               flux_limit=1.0,
                                                               applybeam=True)
                     for f, freq in enumerate(frequency)]
log.info('About to make GLEAM model')

# In[ ]:

log.info('About to run predict to get predicted visibility')
log.info('About to run predict to get predicted visibility')
start=time.time()
predicted_vislist = predict_list_serial_workflow(vis_list, gleam_model,
                                                context='wstack', vis_slices=vis_slices)
#log.info('About to run corrupt to get corrupted visibility')
#corrupted_vislist = corrupt_list_serial_workflow(predicted_vislist, phase_error=1.0)

end=time.time()
print('predict finished in %f seconds'%(end-start),flush=True)

# Get the LSM. This is currently blank.

# In[ ]:

model_list = [create_image_from_visibility(vis_list[f],
                                                     npixel=npixel,
                                                     frequency=[frequency[f]],
                                                     channel_bandwidth=[channel_bandwidth[f]],
                                                     cellsize=cellsize,
                                                     phasecentre=phasecentre,
                                                     polarisation_frame=PolarisationFrame("stokesI"))
               for f, freq in enumerate(frequency)]

# In[ ]:

start=time.time()
print('About to start invert' ,flush=True)

dirty_list = invert_list_serial_workflow(predicted_vislist, model_list,
                                  context='wstack',
                                  vis_slices=vis_slices, dopsf=False)
psf_list = invert_list_serial_workflow(predicted_vislist, model_list,
                                context='wstack',
                                vis_slices=vis_slices, dopsf=True)

end=time.time()
print('invert finished in %f seconds'%(end-start),flush=True)

# Create and execute graphs to make the dirty image and PSF

# In[ ]:

log.info('About to run invert to get dirty image')
dirty = dirty_list[0][0]
#show_image(dirty, cm='Greys', vmax=1.0, vmin=-0.1)
#plt.show()
print(qa_image(dirty))
export_image_to_fits(dirty, '%s/imaging-dirty.fits'
                     %(results_dir))

log.info('About to run invert to get PSF')
psf = psf_list[0][0]
#show_image(psf, cm='Greys', vmax=0.1, vmin=-0.01)
#plt.show()
print(qa_image(psf))
export_image_to_fits(psf, '%s/imaging-psf.fits'
                     %(results_dir))

# Now deconvolve using msclean

# In[ ]:

log.info('About to run deconvolve')
start=time.time()

deconvolved, _ =     deconvolve_list_serial_workflow(dirty_list, psf_list, model_imagelist=model_list,
                            deconvolve_facets=8, deconvolve_overlap=16, deconvolve_taper='tukey',
                            scales=[0, 3, 10],
                            algorithm='msclean', niter=1000,
                            fractional_threshold=0.1,
                            threshold=0.1, gain=0.1, psf_support=64)

end=time.time()
print('deconvolve finished in %f seconds'%(end-start),flush=True)
#show_image(deconvolved[0], cm='Greys', vmax=0.1, vmin=-0.01)
#plt.show()

# In[ ]:

log.info('About to run continuum imaging')
start=time.time()
continuum_imaging_list =     continuum_imaging_list_serial_workflow(predicted_vislist,
                                            model_imagelist=model_list,
                                            context='wstack', vis_slices=vis_slices,
                                            scales=[0, 3, 10], algorithm='mmclean',
                                            nmoment=3, niter=1000,
                                            fractional_threshold=0.1,
                                            threshold=0.1, nmajor=5, gain=0.25,
                                            deconvolve_facets = 8, deconvolve_overlap=16,
                                            deconvolve_taper='tukey', psf_support=64)

# In[ ]:

end=time.time()
print('continuum imaging finished in %f seconds'%(end-start),flush=True)

deconvolved = continuum_imaging_list[0][0]
residual = continuum_imaging_list[1][0]
restored = continuum_imaging_list[2][0]

#f=show_image(deconvolved, title='Clean image - no selfcal', cm='Greys',
#             vmax=0.1, vmin=-0.01)
print(qa_image(deconvolved, context='Clean image - no selfcal'))

#plt.show()

#f=show_image(restored, title='Restored clean image - no selfcal',
#             cm='Greys', vmax=1.0, vmin=-0.1)
print(qa_image(restored, context='Restored clean image - no selfcal'))
#plt.show()
export_image_to_fits(restored, '%s/imaging-dask_continuum_imaging_restored.fits'
                     %(results_dir))

#f=show_image(residual[0], title='Residual clean image - no selfcal', cm='Greys',
#             vmax=0.1, vmin=-0.01)
print(qa_image(residual[0], context='Residual clean image - no selfcal'))
#plt.show()
export_image_to_fits(residual[0], '%s/imaging-dask_continuum_imaging_residual.fits'
                     %(results_dir))

# In[ ]:

#for chan in range(nfreqwin):
#    residual = continuum_imaging_list[1][chan]
    #show_image(residual[0], title='Channel %d' % chan, cm='Greys',
    #           vmax=0.1, vmin=-0.01)
    #plt.show()

# In[ ]:

controls = create_calibration_controls()

controls['T']['first_selfcal'] = 1
controls['G']['first_selfcal'] = 3
controls['B']['first_selfcal'] = 4

controls['T']['timescale'] = 'auto'
controls['G']['timescale'] = 'auto'
controls['B']['timescale'] = 1e5

pp.pprint(controls)

# In[ ]:
start=time.time()
log.info('About to run ical')

# TODO I change this to predicted_vislist to make it deterministic, I hope it makes
# sense :)
#ical_list = ical_list_serial_workflow(corrupted_vislist,
ical_list = ical_list_serial_workflow(predicted_vislist,
                                        model_imagelist=model_list,
                                        context='wstack',
                                        calibration_context = 'TG',
                                        controls=controls,
                                        scales=[0, 3, 10], algorithm='mmclean',
                                        nmoment=3, niter=1000,
                                        fractional_threshold=0.1,
                                        threshold=0.1, nmajor=5, gain=0.25,
                                        deconvolve_facets = 8,
                                        deconvolve_overlap=16,
                                        deconvolve_taper='tukey',
                                        vis_slices=ntimes,
                                        timeslice='auto',
                                        global_solution=False,
                                        psf_support=64,
                                        do_selfcal=True)

# In[ ]:

end=time.time()
print('ical finished in %f seconds'%(end-start),flush=True)

deconvolved = ical_list[0][0]
residual = ical_list[1][0]
restored = ical_list[2][0]

#f=show_image(deconvolved, title='Clean image', cm='Greys', vmax=1.0, vmin=-0.1)
print(qa_image(deconvolved, context='Clean image'))
#plt.show()

#f=show_image(restored, title='Restored clean image', cm='Greys', vmax=1.0,
#             vmin=-0.1)
print(qa_image(restored, context='Restored clean image'))
#plt.show()
export_image_to_fits(restored, '%s/imaging-dask_ical_restored.fits'
                     %(results_dir))

#f=show_image(residual[0], title='Residual clean image', cm='Greys',
#             vmax=0.1, vmin=-0.01)
print(qa_image(residual[0], context='Residual clean image'))
#plt.show()
export_image_to_fits(residual[0], '%s/imaging-dask_ical_residual.fits'
                     %(results_dir))