# -*- coding: utf-8 -*-

from openerp.osv import osv, fields
from openerp import models, tools, SUPERUSER_ID, api, exceptions
import base64
import StringIO
import xlwt
from datetime import datetime, date
import time

class popup_wizard_purchase_export(osv.TransientModel):

    _name = "purchase.report.wizard_analysis_achat"

    _table = "purchase_report_wizard_analysis_achat"

    _columns = {
        'product_ids': fields.many2many('product.product', string='Products'),
        'category_ids': fields.many2many('product.category', string='Category'),
        'google_url': fields.char(string='Google URL'),
        'export_total': fields.boolean(string='All Years', default=False),
        'state': fields.selection([('choose', 'choose'),  # choose date
                                   ('get', 'get')]),
        "start_date": fields.date(string="Start date"),
        "end_date": fields.date(string="End date"),
        "last": fields.date(string="End date"),
    }

    _defaults = {
        'state': 'choose',
        'start_date': time.strftime('2017-01-01'),
        'end_date': time.strftime('2017-12-31')
    }

    @api.multi
    def prepare_export_data_products_annexes(self):

        headers_annexes = ['Article', 'Prix', 'Moyenne pondérée', 'Nombre de fournisseurs', 'Nombre des commandes',
                           'Total des quantités commandées', 'Total des prix', 'Quantité commandée par fournisseur',
                           'Montant par fournisseur']
        if self.category_ids:
            product_ids = [x.id for x in self.category_ids]
            products_annexes = self.env['product.template'].search([('categ_id', 'in', product_ids)])
        if self.product_ids:
            product_ids = [x.product_tmpl_id.id for x in self.product_ids]
            products_annexes = self.env['product.template'].search([('id', 'in', product_ids)])
        # products_annexes = self.env['product.template'].search([('purchase_ok', '=', True), ('type', '!=', 'service')])
        sheets = {}
        result_ann = [headers_annexes]
        for ann in products_annexes:
            name = ann.name
            standard_price = ann.standard_price
            average_weight = ann.average_weight_func(self.start_date, self.end_date)
            sum_supp = ann.calcul_sum_supp(self.start_date, self.end_date)
            qty = ann.calcul_qty(self.start_date, self.end_date)
            sum_qty = ann.calcul_sum_qty(self.start_date, self.end_date)
            qty_supp = ann.qty_supp(self.start_date, self.end_date)
            price_total = ann.price_total(self.start_date, self.end_date)
            price_supp = ann.price_supp(self.start_date, self.end_date)
            ann_list = [name, standard_price, average_weight, sum_supp, sum_qty, qty, price_total, qty_supp, price_supp]
            result_ann.append(ann_list)
        sheets['articles_annexes'] = {'sheet_name': 'Purchase cost - Analyse Cout Achat', 'sheet_data': result_ann}
        return sheets, headers_annexes

    @api.multi
    def create_report_cout_achat(self):

        popup_auth_obj = self.env['popup.auth_functions']

        sheets, headers = self.prepare_export_data_products_annexes()
        folder_name = "Analyse Comptables"
        file_name = "Analyse Cout d'achat"
        # spreadsheet_id="1usIPXwE6Ms9qKhpN4ngh08n5v5fe7A6Vit977Z-dJw8"
        sheet_report = popup_auth_obj.create_sheet_report(sheets, headers, file_name, folder_name, share_folder=False)

        return sheet_report


from collections import deque

def bfs(y, x):
    q = deque()
    q.append((y, x))
    bcount = 1

    visited[y][x] = 1
    while q:
        ny, nx = q.popleft()

        for i in range(4):
            ty = ny + dy[i]
            tx = nx + dx[i]

            if -1 < ty < M and -1 < tx < N and visited[ty][tx] == 0 and board[ty][tx] == 0:
                q.append((ty, tx))
                visited[ty][tx] = 1
                bcount += 1
    return bcount

dy = [0, 0, 1, -1]
dx = [1, -1, 0, 0]

M, N, K = map(int, input().split())

board = [[0] * N for _ in range(M)]
visited = [[0] * N for _ in range(M)]
arange = []

for i in range(K):
    x1, y1, x2, y2 = map(int, input().split())
    for j in range(y1, y2):
        for k in range(x1, x2):
            board[j][k] = 1

for i in range(M):
    for j in range(N):
        if visited[i][j] == 0 and board[i][j] == 0:
            arange.append(bfs(i, j))

print(len(arange))
arange.sort()
for i in arange:
    print(i, end=" ")


#!/usr/bin/python3
""" """
from api.v1.views import app_views
from flask import abort, jsonify, make_response, request
from models import storage
from models.user import User

@app_views.route('/users/all', methods=['GET'], strict_slashes=False)
def users():
    """
    Retrieves a list of all User
    """
    all_users = storage.get(User)
    list_users = []
    for user in all_users:
        list_users.append(user.to_dict())
    return jsonify(list_users)

@app_views.route('/user', methods=['POST'], strict_slashes=False)
def post_user():
    """
    Creates an user
    """
    if not request.get_json():
        abort(400, description="Not a JSON")

    data = request.get_json()
    instance = User(**data)
    instance.save()
    return make_response(jsonify(instance.to_dict()), 201)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

from typing import List, Optional, Text

from absl import logging
from tfx import types
from tfx.components.example_validator import executor
from tfx.dsl.components.base import base_component
from tfx.dsl.components.base import executor_spec
from tfx.types import standard_artifacts
from tfx.types.standard_component_specs import ExampleValidatorSpec
from tfx.utils import json_utils

class ExampleValidator(base_component.BaseComponent):
  """A TFX component to validate input examples.

  The ExampleValidator component uses [Tensorflow Data
  Validation](https://www.tensorflow.org/tfx/data_validation) to
  validate the statistics of some splits on input examples against a schema.

  The ExampleValidator component identifies anomalies in training and serving
  data. The component can be configured to detect different classes of anomalies
  in the data. It can:
    - perform validity checks by comparing data statistics against a schema that
      codifies expectations of the user.

  Schema Based Example Validation
  The ExampleValidator component identifies any anomalies in the example data by
  comparing data statistics computed by the StatisticsGen component against a
  schema. The schema codifies properties which the input data is expected to
  satisfy, and is provided and maintained by the user.

  Please see https://www.tensorflow.org/tfx/data_validation for more details.

  ## Example
  ```
  # Performs anomaly detection based on statistics and data schema.
  validate_stats = ExampleValidator(
      statistics=statistics_gen.outputs['statistics'],
      schema=infer_schema.outputs['schema'])
  ```
  """

  SPEC_CLASS = ExampleValidatorSpec
  EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(executor.Executor)

  def __init__(self,
               statistics: types.Channel = None,
               schema: types.Channel = None,
               exclude_splits: Optional[List[Text]] = None,
               output: Optional[types.Channel] = None,
               stats: Optional[types.Channel] = None,
               instance_name: Optional[Text] = None):
    """Construct an ExampleValidator component.

    Args:
      statistics: A Channel of type `standard_artifacts.ExampleStatistics`.
      schema: A Channel of type `standard_artifacts.Schema`. _required_
      exclude_splits: Names of splits that the example validator should not
        validate. Default behavior (when exclude_splits is set to None)
        is excluding no splits.
      output: Output channel of type `standard_artifacts.ExampleAnomalies`.
      stats: Backwards compatibility alias for the 'statistics' argument.
      instance_name: Optional name assigned to this specific instance of
        ExampleValidator. Required only if multiple ExampleValidator components
        are declared in the same pipeline.  Either `stats` or `statistics` must
        be present in the arguments.
    """
    if stats:
      logging.warning(
          'The "stats" argument to the StatisticsGen component has '
          'been renamed to "statistics" and is deprecated. Please update your '
          'usage as support for this argument will be removed soon.')
      statistics = stats
    if exclude_splits is None:
      exclude_splits = []
      logging.info('Excluding no splits because exclude_splits is not set.')
    anomalies = output
    if not anomalies:
      anomalies = types.Channel(type=standard_artifacts.ExampleAnomalies)
    spec = ExampleValidatorSpec(
        statistics=statistics,
        schema=schema,
        exclude_splits=json_utils.dumps(exclude_splits),
        anomalies=anomalies)
    super(ExampleValidator, self).__init__(
        spec=spec, instance_name=instance_name)


from warehouse import Warehouse
from drones import Drone
from instructions_parser import parse
from collections import defaultdict
from outputter import Outputer
from math import ceil, sqrt

def main(file):
    with open(file) as handler:
        d = parse(handler)

    warehouses = [Warehouse(w,i) for i,w in enumerate(d['warehouses'])]
    WEIGHTS = d['products_weights']
    Drone.WEIGHTS = WEIGHTS
    raw_orders = d['orders']
    orders = []
    drones = [Drone(i, d['max_load']) for i in range(d['drone_number'])]
    output = Outputer()

    for order_id, order in enumerate(raw_orders):
        x, y, items = order
        weight = 0
        used_items = []
        for item in items:
            if weight + WEIGHTS[item] >= d['max_load']:
                orders.append((order_id, (x, y, used_items)))
                used_items = []
                weight = 0

            weight += WEIGHTS[item]
            used_items.append(item)
        if used_items:
            orders.append((order_id, (x, y, used_items)))

    for step in range(d['deadline']):
        list(map(lambda x: x.step(), drones))

        available_drones = list(filter(lambda x: not x.is_occupied, drones))
        if not orders:
            break

        while available_drones:
            if not orders:
                break
            order_id, order = orders.pop()
            destX, destY, order_products = order
            def dist(warehouse):
                d = ceil(sqrt((warehouse.locX - destX)**2 + (warehouse.locY - destY)**2))
                return (d, warehouse)

            sorted_warehouses = sorted(map(dist, warehouses), key=lambda x: x[0])
            drone = available_drones.pop()
            got_items = [False] * len(order_products)
            stack = []
            for dist, warehouse in sorted_warehouses:
                used = False
                for i, item in enumerate(order_products):
                    if got_items[i]:
                        continue
                    if warehouse.has_item(item):
                        warehouse.charge(drone, item)
                        got_items[i] = True
                        used = True
                        stack.append((warehouse, item))
                if all(got_items):
                    stack = reversed(stack)
                    for inst in stack:
                        drone.goto(inst[0].locX, inst[0].locY)
                        output.load(drone, inst[0], inst[1], 1)
                    drone.goto(destX, destY)
                    drone.unload()
                    for item in order_products:
                        output.deliver(drone, order_id, item, 1)
                    break

    return output

if __name__ == '__main__':
    open("busy_day.sol", "w").write(str(main('busy_day.in')))
    open("mother_of_all_warehouses.sol", "w").write(str(main('mother_of_all_warehouses.in')))
    open("redundancy.sol", "w").write(str(main('redundancy.in')))


class Solution(object):
    def removeElements(self, head, val):
        dummy = ListNode(0)
        dummy.next = head
        p = dummy
        while p.next:
            if p.next.val == val:
                p.next = p.next.next
                continue
            p = p.next
        return dummy.next

class ListNode(object):
    def __init__(self, val):
        self.val = val
        self.next = None

def convert(lst):
    if lst == []:
        return None
    dummy = ListNode(0)
    q = dummy
    for e in lst:
        q.next = ListNode(0)
        q.next.val = e
        q = q.next
    return dummy.next

def print_ll(head):
    while head:
        print('{} -> '.format(head.val), end='')
        head = head.next
    print('NULL')


import json

from rest_framework import serializers

from basicmodule.models import BasicModule
from basicmodule.serializers import BasicModuleSerializer
from models import Environments
from utils.customer_exceptions import (
    ParamNotEnoughException, ObjectDoesNotExist,
    ObjectNotExistException
)
from utils.validators import (
    NameLenValidator, DspLenValidator,
    IdTypeValidator, ConfigTypeValidator
)

class ModuleDetailSerializer(serializers.Serializer,
                            NameLenValidator,
                            ConfigTypeValidator,
                            IdTypeValidator):
    """show the detail of the environment module"""
    id = serializers.IntegerField()
    name = serializers.CharField()
    config = serializers.CharField()

class EnvironmentSerializer(serializers.Serializer,
                            NameLenValidator,
                            DspLenValidator,
                            IdTypeValidator):
    """environment model serializer"""
    id = serializers.IntegerField(required=False)
    name = serializers.CharField()
    description = serializers.CharField()
    # this field will be update separately
    # see view source code how to control this
    details = ModuleDetailSerializer(required=False, many=True)

    def to_internal_value(self, data):
        """
        check value exist and value legal
        """
        # valid data
        valid_data = {}

        try:
            name = data['name']
        except KeyError:
            raise ParamNotEnoughException('name')
        self.validate_name(name)
        valid_data.update(name=name)

        try:
            description = data['description']
        except KeyError:
            description = None
        if description:
            self.validate_description(description)
            valid_data.update(description=description)

        return valid_data

class EnvironmentModuleSerializer(serializers.Serializer,
                                  NameLenValidator,
                                  IdTypeValidator,
                                  ConfigTypeValidator):
    """show environment module detail"""
    id = serializers.IntegerField(required=False)
    name = serializers.CharField()
    moduleID = BasicModuleSerializer()
    envID = EnvironmentSerializer()
    config = serializers.CharField(required=False)

    def to_internal_value(self, data):
        """
        function before getting new instance
        even before validate
        we need to get the moduleID instance by pk
        we need to get the envID instance by pk
        we need to check the data by hand
        """
        valid_data = {}

        # deal with name
        try:
            name = data['name']
        except KeyError:
            raise ParamNotEnoughException('name')
        self.validate_name(name)
        valid_data.update(name=name)

        # deal with envID
        try:
            env_id = data['envID']
        except KeyError:
            raise ParamNotEnoughException('envID')
        self.validate_id(env_id)
        try:
            envID = Environments.objects.get(id=env_id)
        except ObjectDoesNotExist:
            raise ObjectNotExistException(env_id)
        valid_data.update(envID=envID)

        # deal with moduleID
        try:
            module_id = data['moduleID']
        except KeyError:
            raise ParamNotEnoughException('moduleID')
        self.validate_id(module_id)
        try:
            moduleID = BasicModule.objects.get(id=module_id)
        except ObjectDoesNotExist:
            raise ObjectNotExistException(module_id)
        valid_data.update(moduleID=module_id)

        # no required config
        try:
            config = data['config']
        except KeyError:
            config = None
        if config:
            self.validate_config(config)
            valid_data.update(config=json.dumps(config))

        return valid_data


import os

import boto3
import cfnresponse
import yaml

spoke_accounts_objects_dict = {}
spoke_accounts_objects_dict[os.getenv("ACCOUNT_NUMBER")] = [
    "account_" + os.getenv("ACCOUNT_NUMBER")
]
spoke_accounts_list = os.getenv("SPOKE_ACCOUNTS").split(",")

for account_id in spoke_accounts_list:
    spoke_accounts_objects_dict[str(account_id)] = ["account_" + account_id]

spoke_accounts_objects_list_yaml = yaml.dump(
    {"account_ids_to_name": spoke_accounts_objects_dict},
    explicit_start=False,
    default_flow_style=False,
    default_style="'",
)

s3_client = boto3.client("s3")

def handler(event, context):
    request_type = event["RequestType"]

    if request_type == "Create":
        return on_create(event, context)
    if request_type == "Update":
        return on_create(event, context)
    if request_type == "Delete":
        return on_delete(event, context)

    raise Exception("Invalid request type: %s" % request_type)

def on_create(event, context):
    with open("config.yaml") as f:
        config_yaml = f.read()

    config_yaml = config_yaml.format(
        issuer=os.getenv("ISSUER"),
        oidc_metadata_url=os.getenv("OIDC_METADATA_URL"),
        redis_host=os.getenv("REDIS_HOST"),
        aws_region=os.getenv("AWS_REGION"),
        ses_identity_arn=os.getenv("SES_IDENTITY_ARN"),
        support_chat_url=os.getenv("SUPPORT_CHAT_URL"),
        application_admin=os.getenv("APPLICATION_ADMIN"),
        account_number=os.getenv("ACCOUNT_NUMBER"),
        spoke_accounts_objects_list_yaml=spoke_accounts_objects_list_yaml,
        config_secret_name=os.getenv("CONFIG_SECRET_NAME"),
    )
    encoded_config = config_yaml.encode("utf-8")

    bucket_name = os.getenv("DEPLOYMENT_BUCKET")
    file_name = "config.yaml"
    s3_path = file_name

    try:
        result = s3_client.put_object(
            Bucket=bucket_name, Key=s3_path, Body=encoded_config
        )
        cfnresponse.send(event, context, cfnresponse.SUCCESS, result)
    except Exception as ex:
        cfnresponse.send(event, context, cfnresponse.FAILED, str(ex))

def on_delete(event, context):
    bucket_name = os.getenv("DEPLOYMENT_BUCKET")
    file_name = "config.yaml"
    s3_path = file_name

    try:
        result = s3_client.delete_object(Bucket=bucket_name, Key=s3_path)
        cfnresponse.send(event, context, cfnresponse.SUCCESS, result)
    except Exception as ex:
        cfnresponse.send(event, context, cfnresponse.FAILED, str(ex))


class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        adj={i:set() for i in range(len(points))}

        for i in range(len(points)):
            x1,y1=points[i]
            for j in range(i+1,len(points)):
                x2,y2=points[j]
                dist=abs(x2-x1) + abs(y2-y1)
                adj[i].add((dist,j))
                adj[j].add((dist,i))

        minheap=[(0,0)] # (cost: point)
        visit,cost=set(),0

        while len(visit) < len(points):
            dist,i=heapq.heappop(minheap)

            if i in visit:
                continue
            visit.add(i)
            cost+=dist

            for path_cost,nei in adj[i]:
                if nei not in visit:
                    heapq.heappush(minheap,(path_cost,nei))

        return cost


import os
import pytest
import unittest
from collections import defaultdict
from subprocess import PIPE, Popen

from sacrerouge.common import TemporaryDirectory
from sacrerouge.common.testing import FIXTURES_ROOT
from sacrerouge.data import Metrics
from sacrerouge.io import JsonlReader

_summaries_file_path = 'datasets/duc-tac/tac2008/v1.0/task1.A.summaries.jsonl'
_config_file_path = f'{FIXTURES_ROOT}/configs/score.json'

class TestScore(unittest.TestCase):
    @pytest.mark.skipif(not os.path.exists(_summaries_file_path), reason='TAC 2008 summaries file does not exist')
    def test_score(self):
        with TemporaryDirectory() as temp_dir:
            output_file = f'{temp_dir}/metrics.jsonl'
            command = [
                'python', '-m', 'sacrerouge', 'score',
                _config_file_path,
                output_file
            ]

            process = Popen(command, stdout=PIPE, stderr=PIPE)
            stdout, stderr = process.communicate()

            instances = JsonlReader(_summaries_file_path).read()
            metrics_list = JsonlReader(output_file, Metrics).read()
            metrics_dicts = defaultdict(dict)

            assert len(instances) == len(metrics_list)
            for instance, metrics in zip(instances, metrics_list):
                assert metrics.instance_id == instance['instance_id']
                assert metrics.summarizer_id == instance['summarizer_id']
                assert metrics.summarizer_type == instance['summarizer_type']
                metrics_dicts[metrics.instance_id][metrics.summarizer_id] = metrics

                if metrics.summarizer_type == 'reference':
                    assert 'python-rouge-1_jk' in metrics.metrics
                    assert 'python-rouge-2_jk' in metrics.metrics
                else:
                    assert 'python-rouge-1' in metrics.metrics
                    assert 'python-rouge-2' in metrics.metrics
                    assert 'python-rouge-1_jk' in metrics.metrics
                    assert 'python-rouge-2_jk' in metrics.metrics

            # Test a couple of instances. I did not check to see if these are correct,
            # but the test will check if the results have changed
            assert metrics_dicts['d0801-A']['0'].metrics == {
                'python-rouge-1': {
                    'precision': 29.444444444444446,
                    'recall': 26.700251889168765,
                    'f1': 28.005284015852048
                },
                'python-rouge-2': {
                    'precision': 2.8089887640449436,
                    'recall': 2.5445292620865136,
                    'f1': 2.67022696929239
                },
                'python-rouge-1_jk': {
                    'precision': 29.444444444444443,
                    'recall': 26.719572295067344,
                    'f1': 28.015250464050713
                },
                'python-rouge-2_jk': {
                    'precision': 2.808988764044944,
                    'recall': 2.549772468714448,
                    'f1': 2.6730599647266313
                }
            }

            assert metrics_dicts['d0805-A']['B'].metrics == {
                'python-rouge-1_jk': {
                    'precision': 37.84722222222222,
                    'recall': 36.21262458471761,
                    'f1': 37.011884550084886
                },
                'python-rouge-2_jk': {
                    'precision': 9.12280701754386,
                    'recall': 8.724832214765101,
                    'f1': 8.919382504288166
                }
            }


#!/usr/bin/env python
"""
SaturnMKII Configuration File
Created: 2016 Jan 08
Author: James Quen

Description:
Configuration file for the SaturnMKII project.
"""

from common import *

#===============================================================================
# STATION SOFTWARE VERSION
#===============================================================================
#Version scheme is defined as
#<station_type>.<product>.<major>.<minor>.<internal_rev>.<prod | dev>

STATION = "ATE"             # Can be either ATE or RMA
PRODUCT = DEVICE_TYPE       # The product type
MAJOR = "1"                 # Major version
MINIOR = "0"                # Minior version
INTERNAL = "0"              # Internal version - used for development.
RELEASE_TYPE = "dev"        # Can be either prod or dev - prod indicates that it is used on the production floor.  dev indicates it's used for development.
STATION_SOFTWARE_VERSION = STATION + "." + PRODUCT + "." + MAJOR + "." + MINIOR + "." + INTERNAL + "." + RELEASE_TYPE

#===============================================================================
# DEVICE FIRMWARE VERSION
#===============================================================================
FW_VERSION="SV0.1.5r.prod"

#===============================================================================
# MANUFACTURER INFORMATION
#===============================================================================
MANUFACTURER_NAME='VS'
TEST_LOCATION='Korea'

#===============================================================================
# DEVICE PHYSICAL INFORMATION
#===============================================================================
MECHANICAL_REVISION = "1.0"
PCB_REVISION = ""                   # *** TODO: fill this in ****
PCBA_REVISION = ""                  # *** TODO: fill this in ****
DEVICE_COLOR = None                 # Needs to come from packaging serial number
MODEL_NUMBER = "SH0AZB"
LED_COLOR = "WHITE"

colorMapApollo = {
            'A':'SILVER',
            'B':'JET',
            'C':'GREEN',
            'D':'PINK',
            'E':'PURE',
            'F':'COCA-COLA',
            'G':'TOPAZ',
            'H':'CHAMPAGNE',
            'J':'STORM',
            'K':'CORAL',
            'M':'WINE',
            'L':'SEA GLASS',
            }

MCU="nRF51822"

#===============================================================================
# SERIAL NUMBER SCHEME
#===============================================================================
ATE_ID = 'SV'
SERIAL_NUM_PREFIX = 'S'

if not MFG_DB_STAGING:
      MATCHSTR_INTERNAL_REGEX = 'V.ZZ[^BOSI]{5}'
      MATCHSTR_REGEX = 'V.[^Z]Z[^BOSI]{5}'
else:
      MATCHSTR_INTERNAL_REGEX = 'V.ZZ.{5}'
      MATCHSTR_REGEX = 'V.[^Z]Z.{5}'

#========================================================================================
# TEST LIMITS
#========================================================================================
MCU_CURRENT_LOWER = 0.0028          # equals 2.8 milliamps
MCU_CURRENT_UPPER = 0.0035          # equals 3.5 milliamps
IDLE_CURRENT_LOWER  = 0.000003      # equals 3 microamps
IDLE_CURRENT_UPPER  = 0.000006      # equals 6 microamps - raised to account for watchdog and 32khz clock
LED_CURRENT_LOWER  = 0.0045         # equals 4.5 milliamps
LED_CURRENT_UPPER  = 0.0067         # equals 6.7 milliamps
LOAD_CURRENT_LOWER  = 0.0020        # equals 2.0 milliamps
LOAD_CURRENT_UPPER  = 0.0025        # equals 2.5 milliamps
ACCEL_CURRENT_LOWER = 0.000003      # equals 3 microamps
ACCEL_CURRENT_UPPER = 0.000010      # equals 10 microamps
DEEP_SLEEP_CURRENT_LOWER  = 0.0000002     # equals 0.2 microamps
DEEP_SLEEP_CURRENT_UPPER  = 0.0000007     # equals 0.7 microamps
Z_DATA_THRESHOLD_LOWER = 435        # accelerometer reading
Z_DATA_THRESHOLD_UPPER = 600        # accelerometer reading
RSSI_LOWER = -75
RSSI_UPPER = -30
OPER_CURR_THRESH_LOWER = 0.000003     # equals 3 microamps
OPER_CURR_THRESH_UPPER = 0.000007     # equals 7 microamps
BATT_BASE_VOLTAGE_THRESH_LOWER = 3000     # equals 3000 mV
BATT_BASE_VOLTAGE_THRESH_UPPER = 3300     # equals 3300 mV
BATT_LOAD_VOLTAGE_THRESH_LOWER = 2900     # equals 2900 mV
BATT_LOAD_VOLTAGE_THRESH_UPPER = 3300     # equals 3300 mV
SERIAL_BAUDRATE = 38400
NUM_LED_TESTS = 6

#========================================================================================
# PARAMETER SETUP
#========================================================================================
NUM_READINGS_BASELINE = 100     # How many readings to take for purpose of estimating baseline (for operating current test)
BASELINE_WINDOW_SIZE = 4        # Sliding window size for estimating baseline

ledTestList = []
for ledIndex in range(1, NUM_LED_TESTS+1):
      ledTestList.append("LED Test %s" % ledIndex)

testList = []
bleTestList = []

PROGRAM_DEVICE = True

if STATION_ID == 1:
      params['programming_done'] = False
params['num_readings_baseline'] = NUM_READINGS_BASELINE
params['baseline_window_size'] = BASELINE_WINDOW_SIZE
params['mcu_current_lower'] = MCU_CURRENT_LOWER
params['mcu_current_upper'] = MCU_CURRENT_UPPER
params['idle_current_lower'] = IDLE_CURRENT_LOWER
params['idle_current_upper'] = IDLE_CURRENT_UPPER
params['led_current_lower'] = LED_CURRENT_LOWER
params['led_current_upper'] = LED_CURRENT_UPPER
params['load_current_lower'] = LOAD_CURRENT_LOWER
params['load_current_upper'] = LOAD_CURRENT_UPPER
params['accel_current_lower'] = ACCEL_CURRENT_LOWER
params['accel_current_upper'] = ACCEL_CURRENT_UPPER
params['deep_sleep_current_lower'] = DEEP_SLEEP_CURRENT_LOWER
params['deep_sleep_current_upper'] = DEEP_SLEEP_CURRENT_UPPER
params['z_data_threshold_lower'] = Z_DATA_THRESHOLD_LOWER
params['z_data_threshold_upper'] = Z_DATA_THRESHOLD_UPPER
params['oper_curr_thresh_upper'] = OPER_CURR_THRESH_UPPER
params['oper_curr_thresh_lower'] = OPER_CURR_THRESH_LOWER
params['batt_base_voltage_lower'] = BATT_BASE_VOLTAGE_THRESH_LOWER
params['batt_base_voltage_upper'] = BATT_BASE_VOLTAGE_THRESH_UPPER
params['batt_load_voltage_lower'] = BATT_LOAD_VOLTAGE_THRESH_LOWER
params['batt_load_voltage_upper'] = BATT_LOAD_VOLTAGE_THRESH_UPPER
params['rssi_lower'] = RSSI_LOWER
params['rssi_upper'] = RSSI_UPPER
params['baud_rate'] = SERIAL_BAUDRATE

#========================================================================================
# ATE 1 TESTS
#========================================================================================
if STATION_ID == 1:
      testList = [
            "Electrical Current Test",
            "Get Mac Address Test",
            "Idle Mode Test",
            ledTestList,
            "Load Test",
            "BT DTM Test",
            "Dummy Test",
            "Accelerometer Orientation Test",
            "Accelerometer Current Test",
      ]

      bleTestList = [
            "Get RSSI Test",
      ]

#========================================================================================
# ATE 2 TESTS
#========================================================================================
elif STATION_ID == 2:
      testList = [
            "Operating Current Test",
      ]

      bleTestList = [
            "Get RSSI Test",
            "Accelerometer BT Self Test",
      ]

#========================================================================================
# ATE 3 TESTS
#========================================================================================
elif STATION_ID == 3:
      testList = [
            "Operating Current Test",
            "Duplicate Serial Number Test",
            "Recent Sync Test",
            "Battery Plot Test",
      ]

      bleTestList = [
            "Get RSSI Test",
            "Read Serial Number Test",
      ]

testList = flattenList(testList)
testOrder = createTestOrder(testList)

bleTestList = flattenList(bleTestList)
testOrderBLE = createTestOrder(bleTestList)


import torch
import numpy as np
import torch.nn.functional as F
from torch import nn, optim
from progan_modules import Generator
from utils import get_texture2D_iter
from matplotlib import pyplot as plt
import cv2

device = 'cuda:0'
# device = 'cpu'
b_size = 32
input_z_channels = 6
# step = 7
alpha = 1.0
A_B_dif_sum_total = 0
A_AB_dif_sum_total = 0
B_AB_dif_sum_total = 0
A_B_dif_array_total = 0
A_AB_dif_array_total = 0
B_AB_dif_array_total = 0

generator = Generator(in_channel=128, input_z_channels=input_z_channels, pixel_norm=False, tanh=False).to(device)

# generator.load_state_dict(torch.load('trial_test18_2021-08-02_21_57/checkpoint/180000_g.model'))  # Step 4
# step = 4
# generator.load_state_dict(torch.load('trial_test18_2021-08-06_10_12/checkpoint/360000_g.model'))    # Step 7
# step = 6

# best so far
generator.load_state_dict(torch.load('trial_test18_2021-08-07_16_10/checkpoint/360000_g.model'))
step = 6

# For control
# generator.load_state_dict(torch.load('trial_test18_2021-07-26_0_52/checkpoint/180000_g.model'))

for x in range(100):
    # Disable gradients
    with torch.no_grad():
        # sample input data: vector for Generator
        # second half of the batch is a top-swapped version of the first half
        gen_z_A = torch.randn(b_size, input_z_channels, 2, 2).to(device)
        gen_z_B = torch.randn(b_size, input_z_channels, 2, 2).to(device)
        gen_z_A_left_half = gen_z_A[:, :, :, 0:gen_z_A.shape[3] // 2]
        gen_z_B_right_half = gen_z_B[:, :, :, gen_z_B.shape[3] // 2:gen_z_B.shape[3]]
        gen_z_AB = torch.cat((gen_z_A_left_half, gen_z_B_right_half), dim=3)
        gen_z = torch.cat((gen_z_A, gen_z_B, gen_z_AB), dim=0)
        # breakpoint()

        # Produce images
        fake_image_A = generator(gen_z_A, step=step, alpha=alpha)
        fake_image_B = generator(gen_z_B, step=step, alpha=alpha)
        fake_image_AB = generator(gen_z_AB, step=step, alpha=alpha)

        # Calculate correlations
        A_B_diff_array = (fake_image_A - fake_image_B)**2
        A_B_dif_sum = torch.sum(A_B_diff_array)
        # print('A_B_dif_sum: ', A_B_dif_sum)

        A_AB_diff_array = (fake_image_A - fake_image_AB)**2
        A_AB_dif_sum = torch.sum(A_AB_diff_array)
        # print('A_AB_dif_sum: ', A_AB_dif_sum)

        B_AB_diff_array = (fake_image_B - fake_image_AB)**2
        B_AB_dif_sum = torch.sum(B_AB_diff_array)
        # print('B_AB_dif_sum: ', B_AB_dif_sum)

        print(x, A_B_dif_sum, A_AB_dif_sum, B_AB_dif_sum)

        A_B_dif_sum_total = A_B_dif_sum_total + A_B_dif_sum.cpu().detach().numpy()
        A_AB_dif_sum_total = A_AB_dif_sum_total + A_AB_dif_sum.cpu().detach().numpy()
        B_AB_dif_sum_total = B_AB_dif_sum_total + B_AB_dif_sum.cpu().detach().numpy()

        A_B_dif_array_total = A_B_dif_array_total + A_B_diff_array.cpu().detach().numpy()
        A_AB_dif_array_total = A_AB_dif_array_total + A_AB_diff_array.cpu().detach().numpy()
        B_AB_dif_array_total = B_AB_dif_array_total + B_AB_diff_array.cpu().detach().numpy()

        # # Show results
        img_g_A = fake_image_A[0, 0].cpu().detach().numpy() * 255
        img_g_B = fake_image_B[0, 0].cpu().detach().numpy() * 255
        img_g_AB = fake_image_AB[0, 0].cpu().detach().numpy() * 255
        img_g_A_g_B = np.concatenate((img_g_A[:, 0:img_g_A.shape[1]//2],
                                      img_g_B[:, img_g_B.shape[1]//2:img_g_B.shape[1]]),  axis=1)
        img_all = np.concatenate((img_g_A, img_g_B, img_g_AB, img_g_A_g_B), axis=1)

        # plt.matshow(img_g_A)
        # print(img_g_A.shape)
        # print(gen_z_A[0, 0])
        # plt.matshow(img_g_B)
        # print(gen_z_B[0, 0])
        # plt.matshow(img_g_AB)
        # print(gen_z_AB[0, 0])
        # plt.matshow(img_all)

        # cv2.imwrite('left_right_sample.png', img_all)

        # plt.figure()

        # # subplot(r,c) provide the no. of rows and columns
        # f, axarr = plt.subplots(1, 3)
        #
        # # use the created array to output your multiple images. In this case I have stacked 4 images vertically
        # axarr[0].imshow(img_g_A)
        # axarr[0].axis('off')
        #
        # axarr[1].imshow(img_g_B)
        # axarr[1].axis('off')
        #
        # axarr[2].imshow(img_g_AB)
        # axarr[2].axis('off')

        # plt.show()

print(A_B_dif_sum_total, A_AB_dif_sum_total, B_AB_dif_sum_total)
A_B_img = A_B_dif_array_total / np.max(A_B_dif_array_total)
A_AB_img = A_AB_dif_array_total / np.max(A_AB_dif_array_total)
B_AB_img = B_AB_dif_array_total / np.max(B_AB_dif_array_total)

# Create figure of results
plt.matshow(np.sum(A_B_img, axis=0)[0])
plt.title(r'$\mathrm{\mathbb{E}} [(G(z_{A}) - G(z_{B}))^{2}]$', fontsize=20)
plt.axis('off')
plt.show()

plt.matshow(np.sum(A_AB_img, axis=0)[0])
plt.title(r'$\mathrm{\mathbb{E}} [(G(z_{A}) - G(z_{A} \oplus z_{B}))^{2}]$', fontsize=20)
plt.axis('off')
plt.show()

plt.matshow(np.sum(B_AB_img, axis=0)[0])
plt.title(r'$\mathrm{\mathbb{E}} [(G(z_{B}) - G(z_{A} \oplus z_{B}))^{2}]$', fontsize=20)
plt.axis('off')
plt.show()


from collections import deque
import sys
global check
def bfs(g, start):
    global check
    q = deque()
    q.append(start)
    check[start] = True
    while q:
        x = q.popleft()
        for i in g[x]:
            if not check[i]:
                q.append(i)
                check[i] = True

input = sys.stdin.readline
n, m = map(int, input().split())

g = [[] for _ in range(n+1)]
for _ in range(m):
    a, b = map(int, input().split())
    g[a].append(b)
    g[b].append(a)
check = [False for _ in range(n+1)]

cnt = 0
for i in range(1, n+1):
    if not check[i]:
        cnt = cnt+1
        bfs(g, i)

print(cnt)


from collections import defaultdict
from functools import cache

succ = defaultdict(list)
rate = {}

with open('q16.txt') as file:
    for line in file:
        words = line.split()
        v = words[1]
        rate[v] = int(words[4][5:-1])
        for u in words[9:]:
            succ[v].append(u.strip(','))

@cache
def solve(time, v, opened, others):
    if time == 0:
        return 0 if others == 0 else solve(26, 'AA', opened, others-1)

    flow = 0
    if v not in opened and rate[v] > 0:
        flow = rate[v] * (time-1) + max(flow, solve(time-1, v, tuple(sorted(list(opened) + [v])), others))
    for u in succ[v]:
        flow = max(flow, solve(time-1, u, opened, others))

    return flow

print(solve(30, 'AA', (), 0))   # Part 1
print(solve(26, 'AA', (), 1))   # Part 2


"""empty message

Revision ID: 4ee680ab1614
Revises: 87f05bac6e4d
Create Date: 2020-12-16 22:01:31.077136

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '4ee680ab1614'
down_revision = '87f05bac6e4d'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('game_team_scores', 'score',
               existing_type=sa.INTEGER(),
               nullable=True)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('game_team_scores', 'score',
               existing_type=sa.INTEGER(),
               nullable=False)
    # ### end Alembic commands ###


from os import listdir
from fpdf import FPDF

path="/home/vivek/Pictures/Wallpapers/"

imagelist=listdir(path)
imagelist.sort()

pdf=FPDF('P','mm','A4')

x=0
y=0
w=210
h=297

for image in imagelist:
	pdf.add_page()
	pdf.image(path+image,x,y,w,h)

pdf.output("output.pdf","F")


import sys

from PyQt5 import QtWidgets as qtw
from PyQt5 import QtGui as qtg
from PyQt5 import QtCore as qtc
from PyQt5 import QtMultimedia as qtm
import json
import os
import datetime
import time
import pymorphy2
import enchant
from style import STYLESHEET
from widgets import check_days,date_validate,dial,event,my_bar,toaster,tree_widget,value_validate,tree_delegate

class MainWindow(qtw.QMainWindow):

    def __init__(self):
        '''MainWindow constructor'''
        super().__init__()
        self.setObjectName('MainWindow')
        main_layout = qtw.QVBoxLayout()
        # and populate it upper widget
        main_layout.addWidget(my_bar.MyBar(self))
        main_layout.setContentsMargins(0, 0, 0, 0)
        main_layout.setSpacing(0)
        self.setMinimumSize(300, 400)
        main_widget = qtw.QWidget()
        main_horisontal_layout = qtw.QHBoxLayout()
        main_widget.setLayout(main_horisontal_layout)
        main_layout.addWidget(main_widget)
        self.setStyleSheet(STYLESHEET)
        left_widget = qtw.QWidget()
        left_layout = qtw.QVBoxLayout()
        left_widget.setLayout(left_layout)
        main_horisontal_layout.addWidget(left_widget)

        upper_left_widget = qtw.QWidget()
        left_layout.addWidget(upper_left_widget)
        upper_left_layout = qtw.QHBoxLayout()
        upper_left_layout.setContentsMargins(0, 0, 0, 0)
        upper_left_layout.setSpacing(0)
        upper_left_widget.setLayout(upper_left_layout)
        username = os.getlogin()
        label_name = qtw.QLabel(f'Hello {username}')
        upper_left_layout.addWidget(label_name, alignment=qtc.Qt.AlignLeft)
        choose_label = qtw.QLabel(f'Choose day of the week')
        upper_left_layout.addWidget(choose_label, alignment=qtc.Qt.AlignRight)
        self.pick_day = qtw.QComboBox(
            self,
            editable=False,
            insertPolicy=qtw.QComboBox.InsertAtTop
        )
        week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        for x in week:
            self.pick_day.addItem(x, 1)
        self.pick_day.setCurrentIndex(datetime.datetime.today().weekday())
        self.pick_day.currentIndexChanged.connect(self.write)
        upper_left_layout.addWidget(self.pick_day, alignment=qtc.Qt.AlignRight)

        self.setWindowFlags(qtc.Qt.FramelessWindowHint)
        self.tree = tree_widget.MyTreeWidget()

        delegate = tree_delegate.TreeWidgetDelegate()

        self.tree.setItemDelegateForColumn(1, delegate)
        self.tree.setItemDelegateForColumn(2, delegate)

        self.tree.setContextMenuPolicy(qtc.Qt.CustomContextMenu)
        self.tree.customContextMenuRequested.connect(self.openMenu)

        self.tree.setColumnCount(3)
        self.tree.setHeaderLabels(["Name", "Start", 'Finish'])
        self.write()
        self.scroll = qtw.QScrollArea(self)
        self.scroll.setFixedSize(400, 300)
        self.scroll.setHorizontalScrollBarPolicy(qtc.Qt.ScrollBarAlwaysOff)
        self.scroll.setWidgetResizable(True)
        self.scroll.setWidget(self.tree)
        self.tree.expandAll()
        #self.tree.setStyleSheet(STYLESHEET)
        #self.tree.setSelectionMode(qtw.QAbstractItemView.ExtendedSelection)
        self.tree.setSelectionMode(qtw.QAbstractItemView.SingleSelection)
        self.tree.setDragEnabled(True)
        self.tree.setAcceptDrops(True)
        self.tree.setDropIndicatorShown(True)
        self.tree.setDragDropMode(qtw.QAbstractItemView.InternalMove)
        self.tree.setHorizontalScrollBarPolicy(qtc.Qt.ScrollBarAlwaysOff)
        self.tree.itemChanged.connect(self.sorting)
        header = self.tree.header()
        header.setSectionResizeMode(qtw.QHeaderView.ResizeToContents)
        # header.setStretchLastSection(False)
        header.setSectionResizeMode(0, qtw.QHeaderView.Stretch)
        header.setSectionResizeMode(1, qtw.QHeaderView.Stretch)

        right_widget = qtw.QWidget()
        right_layout = qtw.QVBoxLayout()
        right_layout.setContentsMargins(0, 0, 0, 0)
        right_layout.setSpacing(15)
        right_widget.setLayout(right_layout)
        self.dial = dial.ValueDial(minimum=0, maximum=60, pageStep=5, singleStep=5, wrapping=1)
        self.dial.valueChanged.connect(self.dialchan)
        right_layout.addWidget(self.dial, alignment=qtc.Qt.AlignTop)
        minutes_value = qtw.QLabel('Minutes: ')
        self.value = qtw.QLineEdit('0')
        self.value.setValidator(value_validate.ValueValidator())
        self.move_time_button = qtw.QPushButton('Move timer')
        self.move_time_button.setObjectName('main_button')
        self.move_time_button.clicked.connect(self.move_min)
        form_box = qtw.QFormLayout()
        form_box.addRow(minutes_value, self.value)
        self.start_notifications = qtw.QPushButton('Start notifications')
        self.start_notifications.setObjectName('main_button')
        self.start_notifications.clicked.connect(self.notifications)

        pause_layout = qtw.QHBoxLayout()
        self.pause = qtw.QPushButton('Pause')
        self.pause.setObjectName('main_button')
        self.pause.clicked.connect(self.pause_func)
        pause_layout.addWidget(self.pause)

        self.resume = qtw.QPushButton('Resume')
        self.resume.setObjectName('main_button')
        self.resume.clicked.connect(self.resume_func)
        pause_layout.addWidget(self.resume)

        self.correct_to_cur_time = qtw.QPushButton('Correct to current time')
        self.correct_to_cur_time.setObjectName('main_button')
        self.correct_to_cur_time.clicked.connect(self.correct)
        self.save = qtw.QPushButton('Save')
        self.save.setObjectName('main_button')
        self.save.clicked.connect(lambda:self.rewrite(self.pick_day.currentText()))

        copy_layout=qtw.QHBoxLayout()
        self.copy = qtw.QPushButton('Copy')
        self.copy.setObjectName('main_button')
        self.copy.clicked.connect(self.copy_schedule)
        self.pick_day2 = check_days.CheckableComboBox()
        self.pick_day2.addItems(week)
        copy_layout.addWidget(self.copy)
        copy_layout.addWidget(self.pick_day2)

        right_layout.addLayout(form_box)
        right_layout.addWidget(self.move_time_button)
        right_layout.addWidget(self.correct_to_cur_time)
        right_layout.addWidget(self.start_notifications)
        right_layout.addLayout(pause_layout)
        right_layout.addWidget(self.save)
        right_layout.addLayout(copy_layout)
        right_layout.addStretch()

        main_horisontal_layout.addWidget(right_widget)
        left_layout.addWidget(self.scroll)

        entry_layout = qtw.QHBoxLayout()
        entry = qtw.QWidget()
        entry.setLayout(entry_layout)
        self.name = qtw.QLineEdit(self, placeholderText='Text event...')
        self.name.setFixedWidth(175)
        self.start_time = qtw.QLineEdit('00:00')
        self.start_time.setValidator(date_validate.DateValidator())
        self.start_time.setFixedWidth(50)
        tire = qtw.QLabel('—')
        tire.setFixedWidth(10)
        self.finish_time = qtw.QLineEdit('00:00')
        self.finish_time.setValidator(date_validate.DateValidator())
        self.finish_time.setFixedWidth(50)
        entry_layout.addWidget(self.name, alignment=qtc.Qt.AlignLeft)
        entry_layout.addStretch(0)
        entry_layout.addWidget(self.start_time, alignment=qtc.Qt.AlignRight)
        entry_layout.addWidget(tire, alignment=qtc.Qt.AlignRight)
        entry_layout.addWidget(self.finish_time, alignment=qtc.Qt.AlignRight)
        left_layout.addWidget(entry)
        self.format = 'HH:mm'
        set_days = qtw.QPushButton('Add Event')
        set_days.setObjectName('main_button')
        set_days.clicked.connect(self.add_new)
        left_layout.addWidget(set_days)
        mainWidget = qtw.QWidget()
        mainWidget.setLayout(main_layout)
        self.setCentralWidget(mainWidget)
        self.setWindowFlags(self.windowFlags() | qtc.Qt.FramelessWindowHint |
                            qtc.Qt.BypassWindowManagerHint | qtc.Qt.SplashScreen)
        self.show()

    def pause_func(self):
        try:
            self.remain=self.timer.remainingTime()
            print(self.remain)
            self.timer.stop()
        except Exception as e:
            print(e)

    def resume_func(self):
        try:

            self.set_timer(self.item,self.pos,self.remain)
            print(self.remain)
        except Exception as e:
            print(e)

    def copy_schedule(self):
        list=self.pick_day2.currentData()
        for day in list:
            self.rewrite(day)

    def correct(self):
        def get_subtree_nodes(tree_widget_item, x):
            cur_text = tree_widget_item.text(x)
            new = qtc.QTime.fromString(cur_text, self.format).addSecs(dif).toString(self.format)
            tree_widget_item.setText(x, new)
            if tree_widget_item.childCount() != 0:
                for i in range(tree_widget_item.childCount()):
                    get_subtree_nodes(tree_widget_item.child(i), x)

        current_time = qtc.QTime.currentTime()
        top = self.tree.topLevelItem(0)
        get_first_time = qtc.QTime.fromString(top.text(1), self.format)
        dif = get_first_time.secsTo(current_time)

        for i in range(self.tree.topLevelItemCount()):
            top_item = self.tree.topLevelItem(i)
            for x in range(1, 3):
                get_subtree_nodes(top_item, x)

    def toast(self, name, pos):

        def morph(word):
            d = enchant.Dict("en_US")
            if not d.check(word):
                morph = pymorphy2.MorphAnalyzer()
                butyavka = morph.parse(word)[0]
                gent = butyavka.inflect({'gent'})
                return gent.word.capitalize()
            else:
                return word

        time.sleep(1)
        filename = 'tuturu_1.mp3'
        fullpath = qtc.QDir.current().absoluteFilePath(filename)
        url = qtc.QUrl.fromLocalFile(fullpath)
        content = qtm.QMediaContent(url)
        self.player = qtm.QMediaPlayer()
        self.player.setMedia(content)
        self.player.play()
        if not pos:
            if name.parent():
                #print(f'{name.text(0)} from {morph(name.parent().text(0))} is over!')
                toaster.QToaster.showMessage(self, f'{name.text(0)} from {morph(name.parent().text(0))} is start!')
            else:
                print(name.text(0))
                toaster.QToaster.showMessage(self, f'{name.text(0)} is start!')
        else:
            if name.parent():
                toaster.QToaster.showMessage(self, f'{name.text(0)} from {morph(name.parent().text(0))} is over!')
            else:
                toaster.QToaster.showMessage(self, f'{name.text(0)} is over!')
        self.notifications()

    def set_timer(self,name, pos,remain=0):
        self.timer = qtc.QTimer()
        self.timer.setSingleShot(True)
        if not remain:
            time = self.cur.msecsTo(qtc.QTime.fromString(self.req, self.format))
            print(time / 60000)
            self.timer.setInterval(time)
        else:
            print(remain / 60000)
            self.timer.setInterval(remain)
        self.timer.timeout.connect(lambda: self.toast(name, pos))
        self.timer.start()

    def notifications(self):

        def find_time(parent, req=None, item=None, pos=0):
            def find_child(parent, req=None, item=None, pos=0):
                for id in range(parent.childCount()):
                    if self.cur.secsTo(qtc.QTime.fromString(parent.child(id).text(1), self.format)) > 0:
                        item = parent.child(id)
                        req = item.text(1)
                        pos = 0
                        return item, req, pos
                    elif self.cur.secsTo(qtc.QTime.fromString(parent.child(id).text(2), self.format)) > 0:
                        item = parent.child(id)
                        req = item.text(2)
                        pos = 1
                        if parent.child(id).childCount() != 0:
                            return find_child(parent.child(id), req, item, pos)
                        return item, req, pos
                return item, req, pos

            for id in range(parent.topLevelItemCount()):
                if self.cur.secsTo(qtc.QTime.fromString(parent.topLevelItem(id).text(1), self.format)) > 0:
                    item = parent.topLevelItem(id)
                    req = item.text(1)
                    pos = 0
                    return item, req, pos
                elif self.cur.secsTo(qtc.QTime.fromString(parent.topLevelItem(id).text(2), self.format)) > 0:
                    item = parent.topLevelItem(id)
                    req = item.text(2)
                    pos = 1
                    if parent.topLevelItem(id).childCount() != 0:
                        return find_child(parent.topLevelItem(id), req, item, pos)
                    return item, req, pos
            return item, req, pos

        self.cur = qtc.QTime.currentTime()
        self.item, self.req, self.pos = find_time(self.tree, None, None, 0)

        if self.req is None:
            toaster.QToaster.showMessage(self, 'Day end!!!!')
        else:
            self.set_timer(self.item, self.pos)

    def move_min(self):
        def get_subtree_nodes(tree_widget_item, x):
            cur_text = tree_widget_item.text(x)
            new = qtc.QTime.fromString(cur_text, self.format).addSecs(int(self.value.text()) * 60).toString(self.format)
            tree_widget_item.setText(x, new)
            if tree_widget_item.childCount() != 0:
                for i in range(tree_widget_item.childCount()):
                    get_subtree_nodes(tree_widget_item.child(i), x)

        for i in range(self.tree.topLevelItemCount()):
            top_item = self.tree.topLevelItem(i)
            for x in range(1, 3):
                get_subtree_nodes(top_item, x)

    def sorting(self):
        if self.tree.currentItem():
            if self.tree.currentItem().parent():
                self.tree.currentItem().parent().sortChildren(1, qtc.Qt.AscendingOrder)
                self.tree.currentItem().parent().sortChildren(2, qtc.Qt.AscendingOrder)
            else:
                self.tree.sortByColumn(1, qtc.Qt.AscendingOrder)
                self.tree.sortByColumn(2, qtc.Qt.AscendingOrder)
            # self.rewrite()

    def dialchan(self):
        self.value.setText(str(self.dial.dial.value()))

    def openMenu(self, position):
        indexes = self.sender().selectedIndexes()
        mdlIdx = self.tree.indexAt(position)
        if not mdlIdx.isValid():
            return
        if len(indexes) > 0:
            level = 0
            index = indexes[0]
            while index.parent().isValid():
                index = index.parent()
                level += 1
        else:
            level = 0
        right_click_menu = qtw.QMenu()
        act_add = right_click_menu.addAction(self.tr("Add Child Item"))
        act_add.triggered.connect(self.add_child)
        act_del = right_click_menu.addAction(self.tr("Delete Item"))
        act_del.triggered.connect(self.de)
        right_click_menu.exec_(self.sender().viewport().mapToGlobal(position))

    def chil(self):
        item = qtw.QTreeWidgetItem([self.ev.name.text(), self.ev.line1.text(), self.ev.line2.text()])
        item.setFlags(item.flags() |qtc.Qt.ItemIsDragEnabled|qtc.Qt.ItemIsDropEnabled| qtc.Qt.ItemIsEditable)
        currNode = self.tree.currentItem()
        currNode.addChild(item)
        self.tree.expandAll()
        self.ev.close()
        self.tree.currentItem().sortChildren(1, qtc.Qt.AscendingOrder)
        # self.rewrite()

    def add_child(self):
        self.ev = event.Event()
        self.ev.buttonClicked.connect(self.chil)

    def add_new(self):
        item = qtw.QTreeWidgetItem([self.name.text(), self.start_time.text(), self.finish_time.text()])
        item.setFlags(item.flags() | qtc.Qt.ItemIsEditable)
        self.tree.addTopLevelItem(item)
        self.tree.expandAll()
        self.tree.sortByColumn(1, qtc.Qt.AscendingOrder)
        # self.rewrite()

    def get_all_items(self, tree_widget):
        def get_subtree_nodes(tree_widget_item):
            """Returns all QTreeWidgetItems in the subtree rooted at the given node."""
            nodes = {tree_widget_item.text(0): {'start': tree_widget_item.text(1),
                                                'finish': tree_widget_item.text(2),
                                                'somes': {}}}
            for i in range(tree_widget_item.childCount()):
                if tree_widget_item.child(i).childCount() != 0:
                    nodes[tree_widget_item.text(0)]['somes'].update(get_subtree_nodes(tree_widget_item.child(i)))
                else:
                    nodes[tree_widget_item.text(0)]['somes'].update(
                        {tree_widget_item.child(i).text(0): {
                            'start': tree_widget_item.child(i).text(1),
                            'finish': tree_widget_item.child(i).text(2),
                            'somes': {}}})
            return nodes

        """Returns all QTreeWidgetItems in the given QTreeWidget."""
        all_items = {}
        for i in range(tree_widget.topLevelItemCount()):
            top_item = tree_widget.topLevelItem(i)
            all_items.update(get_subtree_nodes(top_item))
        # print(json.dumps(all_items,indent=2,ensure_ascii=False))
        return all_items

    def de(self, child):
        try:
            currNode = self.tree.currentItem()
            parent1 = currNode.parent()
            parent1.removeChild(currNode)
            # self.rewrite()
        except Exception:
            try:
                rootIndex = self.tree.indexOfTopLevelItem(currNode)
                self.tree.takeTopLevelItem(rootIndex)
                # self.rewrite()
            except Exception:
                print(Exception)

    def add_time(self, ):
        pass

    def write(self):
        def repe(main, chil):
            if not chil['somes']:
                return
            for keys, value in chil['somes'].items():
                child = qtw.QTreeWidgetItem([keys, value['start'], value['finish']])
                child.setFlags(main.flags()  | qtc.Qt.ItemIsEditable)
                main.addChild(child)
                repe(child, value)

        self.tree.clear()
        with open('package.json', encoding='utf8') as f:
            token = json.load(f)
            day = self.pick_day.currentText()
            for key, values in token[day].items():
                item = qtw.QTreeWidgetItem([key, values['start'], values['finish']])
                repe(item, values)

                item.setFlags(item.flags()  | qtc.Qt.ItemIsEditable)
                self.tree.addTopLevelItem(item)
        self.tree.expandAll()

    def rewrite(self,day=None):
        with open('package.json', encoding='utf8') as f:
            token = json.load(f)
            tr = self.get_all_items(self.tree)
            day = day
            token[day] = tr
            with open('package.json', 'w', encoding='utf8') as outfile:
                json.dump(token, outfile, indent=2, ensure_ascii=False)

if __name__ == '__main__':

    @qtc.pyqtSlot(qtw.QSystemTrayIcon.ActivationReason)
    def slotSystrayActivated(reason):
        if reason == qtw.QSystemTrayIcon.Context:  # right
            pass
        elif reason == qtw.QSystemTrayIcon.MiddleClick:  # middle
            pass
        elif reason == qtw.QSystemTrayIcon.DoubleClick:  # double click
            pass
        elif reason == qtw.QSystemTrayIcon.Trigger:  # left
            if main.isHidden() or main.isMinimized():
                main.setGeometry(main.geometry())
                main.showNormal()
                main.activateWindow()
                main.raise_()
            else:
                main.hide()

    app = qtw.QApplication(sys.argv)

    main = MainWindow()
    # Adding an icon
    icon = qtg.QIcon("pngwing.com.png")

    # Adding item on the menu bar
    tray = qtw.QSystemTrayIcon()
    tray.setIcon(icon)
    tray.setVisible(True)
    tray.activated.connect(slotSystrayActivated)
    menu = qtw.QMenu()
    quit = qtw.QAction("Quit")
    quit.triggered.connect(app.quit)
    menu.addAction(quit)

    tray.setContextMenu(menu)

    sys.exit(app.exec())


class Solution:
    def isValid(self, s: str) -> bool:
        map = {")": "(", "}": "{", "]":"["}
        stack = []
        for i in range(len(s)) :
            if s[i] in ['(', '{', '['] :
                stack.append(s[i])
            elif len(stack) > 0 and stack[-1] == map[s[i]] :
                stack.pop()
            else :
                return False
        return len(stack) == 0

s = Solution()

print(s.isValid("()"))


import random
print('Welcome to the Number Guessing Game')
print('I am thinking of a number between 1 and 100')

count_easy = 10
count_hard = 5

def play_game():
    choose = random.randint(1, 100)
    lives = 0

    difficulty = input('Choose a difficulty level. Type "easy" or "hard": ')
    if difficulty == 'easy':
        lives = count_easy
        print(f"You have {lives} attempts")
    elif difficulty == 'hard':
        lives = count_hard
        print(f"You have {lives} attempts")
    else:
        print('Invalid input. Try again.')
        return

    while lives > 0:
        guess = int(input('Make a guess: '))

        if guess == choose:
            print(f'You got it! The answer was {choose}.')
            return
        elif guess > choose:
            lives -= 1
            print('Too high.')
            print(f"You have {lives} attempts left.")
        elif guess < choose:
            lives -= 1
            print('Too low.')
            print(f"You have {lives} attempts left.")

    print(f"You have run out of attempts. The answer was {choose}. Game over.")

play_game()


"""
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along
the path equals the given sum.

Example :

Given the below binary tree and sum = 22,

              5
             / \
            4   8
           /   / \
          11  13  4
         /  \      \
        7    2      1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.

Return 0 / 1 ( 0 for false, 1 for true ) for this problem
"""

from Python.Level6.TreeDataStructure import Node

class Solution:

    def path_sum(self, root, target):

        if root is None:
            return target == 0

        else:
            res = 0
            target -= root.data

            if target == 0 and root.left is None and root.right is None:
                return 1

            if root.left:
                res = res or self.path_sum(root.left, target)
            if root.right:
                res = res or self.path_sum(root.right, target)

            return res

"""Testing program"""
s = Solution()
root = Node(5)
root.left = Node(4)
root.right = Node(8)
root.left.left = Node(11)
root.right.left = Node(13)
root.right.right = Node(4)
root.left.left.left = Node(7)
root.left.left.right = Node(2)
root.right.right.right = Node(1)

print(s.path_sum(root, 22))


# -*- coding: utf-8 -*-
from comport.data.cleaners import Cleaners, RESIDENT_WEAPONS_LOOKUP, OFFICER_FORCE_TYPE_LOOKUP, RACE_LOOKUP, GENDER_LOOKUP, CAPITALIZE_LIST, CAPITALIZE_IGNORE_KEYS_LIST
from titlecase import titlecase

class TestCleaners:

    def test_unknown_resident_weapon_returned(self):
        ''' Cleaning an unknown weapon returns the same value passed.
        '''
        cleaner = Cleaners()
        weapon = "Suspect - Lewd Nebulosity "
        cleaned = cleaner.resident_weapon_used(weapon)
        assert cleaned == weapon

    def test_known_resident_weapons_cleaned(self):
        ''' Cleaning known weapons returns the expected value.
        '''
        cleaner = Cleaners()
        for weapon in RESIDENT_WEAPONS_LOOKUP:
            check_weapon = cleaner.resident_weapon_used(weapon)
            assert check_weapon == RESIDENT_WEAPONS_LOOKUP[weapon]

    def test_unknown_officer_force_type_returned(self):
        ''' Cleaning an unknown weapon returns the same value passed.
        '''
        cleaner = Cleaners()
        force_type = "Bugbear Squeeze"
        cleaned = cleaner.officer_force_type(force_type)
        assert cleaned == force_type

    def test_known_officer_force_types_cleaned(self):
        ''' Cleaning known weapons returns the expected value.
        '''
        cleaner = Cleaners()
        for force_type in OFFICER_FORCE_TYPE_LOOKUP:
            check_force_type = cleaner.officer_force_type(force_type)
            assert check_force_type == OFFICER_FORCE_TYPE_LOOKUP[force_type]

    def test_unknown_race_returned(self):
        ''' Cleaning an unknown race returns the same value passed.
        '''
        cleaner = Cleaners()
        race = "Comet"
        cleaned = cleaner.race(race)
        assert cleaned == race

    def test_known_races_cleaned(self):
        ''' Cleaning known races returns the expected value.
        '''
        cleaner = Cleaners()
        for race in RACE_LOOKUP:
            check_race = cleaner.race(race)
            assert check_race == RACE_LOOKUP[race]

    def test_unknown_gender_returned(self):
        ''' Cleaning an unknown gender returns the same value passed.
        '''
        cleaner = Cleaners()
        gender = "Golf"
        cleaned = cleaner.sex(gender)
        assert cleaned == gender

    def test_known_genders_cleaned(self):
        ''' Cleaning known genders returns the expected value.
        '''
        cleaner = Cleaners()
        for gender in GENDER_LOOKUP:
            check_gender = cleaner.sex(gender)
            assert check_gender == GENDER_LOOKUP[gender]

    def test_capitalization(self):
        ''' A phrase is title-cased with expected exceptions.
        '''
        cleaner = Cleaners()
        in_sentence = "I thought I would sail about a little and see the watery part of the world"
        titlecased_sentence = titlecase(in_sentence)
        send = " ".join(i.lower() + " " + j.lower() for i, j in zip(in_sentence.split(" "), CAPITALIZE_LIST))
        check = " ".join(i + " " + j for i, j in zip(titlecased_sentence.split(" "), CAPITALIZE_LIST))
        result = cleaner.capitalize(send)
        assert check == result

    def test_capitalization_inside_parentheses(self):
        ''' Words are left titlecased even if they're inside parentheses
        '''
        cleaner = Cleaners()
        in_sentence = "I thought I would sail about a little and see the watery part of the world"
        titlecased_sentence = titlecase(in_sentence)
        send = " ".join(i.lower() + " (" + j.lower() + ")" for i, j in zip(in_sentence.split(" "), CAPITALIZE_LIST))
        check = " ".join(i + " (" + j + ")" for i, j in zip(titlecased_sentence.split(" "), CAPITALIZE_LIST))
        result = cleaner.capitalize(send)
        assert check == result

    def test_captilization_handles_non_strings(self):
        ''' Non-strings passed to capitalize aren't altered.
        '''
        cleaner = Cleaners()
        send_int = 23
        send_float = 32.01
        send_list = ["I", "thought", "I", "would", "sail"]
        result_int = cleaner.capitalize(send_int)
        result_float = cleaner.capitalize(send_float)
        result_list = cleaner.capitalize(send_list)
        assert send_int == result_int
        assert send_float == result_float
        assert send_list == result_list

    def test_incident_capitalization(self):
        ''' Incident descriptions are title-cased with expected exceptions.
        '''
        cleaner = Cleaners()
        in_sentence = "Northwest and east district"
        send = {}
        send["division"] = in_sentence
        send["precinct"] = in_sentence
        for key in CAPITALIZE_IGNORE_KEYS_LIST:
            send[key] = in_sentence

        result = cleaner.capitalize_incident(send)

        # values of keys not in the list should be titlecased
        titlecased_sentence = "Northwest and East District"
        assert result["division"] == titlecased_sentence
        assert result["precinct"] == titlecased_sentence
        # values of keys in the list should not be titlecased
        for key in CAPITALIZE_IGNORE_KEYS_LIST:
            assert result[key] == in_sentence

    def test_number_to_string(self):
        ''' Numbers are turned into strings.
        '''
        cleaner = Cleaners()
        in_int = 85
        in_float = 82.12
        in_string = "big frame, small spirit!"
        in_list = ["hands", "by", "the", "halyards"]
        in_none = None
        assert cleaner.number_to_string(in_int) == str(in_int)
        assert cleaner.number_to_string(in_float) == str(in_float)
        assert cleaner.number_to_string(in_string) == in_string
        assert cleaner.number_to_string(in_list) == in_list
        assert cleaner.number_to_string(in_none) is None

    def test_string_to_integer(self):
        ''' Strings are turned into integers.
        '''
        cleaner = Cleaners()
        in_string_success_int = '85'
        in_string_success_float = '33.34'
        in_int = 85
        in_float = 82.12
        in_string_fail = 'whaleman'
        in_list = ["hands", "by", "the", "halyards"]
        in_none = None
        assert cleaner.string_to_integer(in_string_success_int) == int(in_string_success_int)
        assert cleaner.string_to_integer(in_string_success_float) == int(float(in_string_success_float))
        assert cleaner.string_to_integer(in_int) == in_int
        assert cleaner.string_to_integer(in_float) == int(in_float)
        assert cleaner.string_to_integer(in_string_fail) is None
        assert cleaner.string_to_integer(in_list) is None
        assert cleaner.string_to_integer(in_none) is None


#!/usr/bin/python3

from Bio import SeqIO
import argparse

def slidingWindow(sequence,winSize,stepSize):

	# Verify the inputs
	try: it = iter(sequence)
	except TypeError:
		raise Exception("**ERROR** sequence must be iterable.")
	if stepSize > winSize:
		raise Exception("**ERROR** stepSize must not be larger than winSize.")
	# if winSize > len(sequence):
		# raise Exception("**ERROR** winSize must not be larger than sequence length.")

	# HACK
	# numOfPieces = ((len(sequence)-winSize)//stepSize)+1
	numOfPieces = max (((len(sequence)-winSize)//stepSize)+1,0)
	# Do the work
	for i in range(0,numOfPieces*stepSize+1,stepSize):
		if i+winSize > len(sequence):
			end = len(sequence)
		else:
			end = i+winSize
		yield (sequence[i:end],(i,end))

def process_fasta(fasta_file,window,step):

	for seq_record in SeqIO.parse(fasta_file, "fasta"):
		mygenerator = slidingWindow(seq_record.seq,window,step)
		out_file = seq_record.id.split("|")[0]  + '.outfile'

		with open(out_file,"w") as f:
			for i in mygenerator:
				seq_name = seq_record.id  + "_" +  str(i[1][0]) + "_" + str(i[1][1])
				seq_win = str(i[0])
				f.write(">" + seq_name + "\n")
				f.write(seq_win + "\n")

def main():
	parser = argparse.ArgumentParser()

	parser.add_argument("-i","--input", dest="infile",  help = "input fasta file", required = True)
	parser.add_argument("-w","--window", dest="window", default=120, help="Define window size" )
	parser.add_argument("-s","--step", dest="step", default=60,  help = "Define step size")
	args = parser.parse_args()

	out_file = args.infile + ".outfile"
	process_fasta(args.infile,int(args.window),int(args.step))

if __name__ == "__main__":
	main()


class Computers:
    def Comp1(self):
        print("i5","intel","gen12")

'''''device1=Computers()
     Computers.Comp1(device1)
     #this is the old method of class calling'''''
device1=Computers()
device1.Comp1()

print("--"*50)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''Example 1 '''''
class Car:

    wheels ='4'                                  # class variable

    def __init__(self):
        self.mil =10
        self.com ="amw"                       #instance variable

car1=Car()
car2 = Car()

print(car1.mil,car2.com)
print(car2.wheels)
car2.wheels=5
print(car2.wheels)
car2.mil =20
print(car2.mil)

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("--"*50)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''Example 2 '''''
print("class method and static method")

class Student:

    school ="Trootech"

    def __init__(self,m1,m2,m3):
        self.m1=m1
        self.m2=m2
        self.m3=m3

    def aveerage(self):
        print(self.m2+self.m1+self.m3/3)

    @classmethod
    def info(cls):
        return cls.school                                # class method

    @classmethod
    def average(cls,m1,m2,m3):
        return cls(m1,m2,m3)

    @staticmethod
    def getinfo():                                      # static method
        print("checking the static method ")

obj3=Student.average(20,30,40)
obj3.aveerage()

obj1=Student(20,23,65)
print(obj1.m1)
obj2=Student(12,21,42)
print(obj2.aveerage())
print(Student.info())
print(Student.getinfo())

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("--"*50)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''Example 3 '''''

print("Example 3 :inner class method")

class Students:
    def __init__(self,rollno,marks):
        self.rollno=rollno
        self.marks = marks
        self.lap =self.Laptop()

    def show(self):
        print(self.rollno,self.marks)

    class Laptop:
        def __init__(self):
            self.company = "HP"
            self.ram = "8 GB"
        def show(self):
            print(self.ram,self.company)

obj1= Students(10,99)
obj2= Students(10,98)
obj1.show()

lap1 = Students.Laptop()
lap1.show()

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("--"*50)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''Example 4 '''''
print("Example 4 \n")

'''''Inheritance'''''

class A:
    def fun1(self):
        print("Function 1 is working ")
    def fun2(self):
        print("Function 2 is working ")

class B(A):
    def fun3(self):
        print("Function 3 is working")
    def fun4(self):
        print("Function 4 is working ")

class C(B):
    def fun5(self):
        print("Functioin 5 working")

obj1= A()
print(obj1.fun2())

obj2 =B()
print(obj2.fun1())

obj3=C()
print(obj3.fun5())

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
print("--"*50)
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'''''Example 5 '''''
print("Example 5 \n")
'''''Constructor in Inheritance'''''

class A:
    def __init__(self):
        print("in A init")
    def fun1(self):
        print("Function 1-A is working ")
    def fun2(self):
        print("Function 2 is working ")

class B:
    def fun1(self):
        print("Function 1-B is working")
    def fun4(self):
        print("Function 4 is working ")
    def __init__(self):
        print("in B  init ")
#obj1= B()

class C(A,B):
    def __init__(self):
        super().__init__()                                     # Method Resolution Order
        print("In C init")

obj3 = C()
obj3.fun1()


# -*- coding: utf-8 -*-

import sys
import time
import json
import cv2
import base64
import numpy as np
import datetime

from kafka import KafkaConsumer
from kafka import TopicPartition
from kafka.errors import KafkaError

# KAFAKA_TOPIC = "cv2-logic-pidbysecond"
KAFAKA_TOPIC = "snap-cap"

consumer = KafkaConsumer(group_id="test", bootstrap_servers = '192.168.237.189:9092',enable_auto_commit = True,auto_commit_interval_ms = 5000)

consumer.assign([TopicPartition(topic=KAFAKA_TOPIC, partition=0)])

consumer.seek(TopicPartition(KAFAKA_TOPIC,0), 62063)

def base64_to_image(base64_code):
    img_data = base64.b64decode(base64_code)
    img_array = np.fromstring(img_data, np.uint8)
    img = cv2.imdecode(img_array, cv2.COLOR_RGB2BGR)
    return img

def oldCoding():
    total_num = 0
    for msg in consumer:
        jsonStr = bytes.decode(msg.value)
        msg_dict = json.loads(jsonStr)
        if msg_dict["regist"]==1:
            print("index: ",total_num)
            frame_dict = msg_dict["frame"]
            face_dict = msg_dict["face"]
            img_regis = base64_to_image(face_dict["grab_img"])
            img = img_regis[:,:,0:3]
            if img is not None:
                dtime = datetime.datetime.strptime(frame_dict["_timestamps"], "%Y-%m-%d %H:%M:%S")
                strdt = dtime.strftime("%Y_%m_%d_%H_%M_%S")
                filename = "./img/"+strdt+"_"+str(msg.offset)+".jpg"
                print("filename: ",filename)
                cv2.imwrite(filename,img)
            #print("time: ",frame_dict["_timestamps"])
            #print("offset: ",msg.offset)
            total_num += 1
        if total_num>500:
            break

    print("total numbers: ",total_num)

msg = next(consumer)
jsonStr = bytes.decode(msg.value)
msg_dict = json.loads(jsonStr)
print(msg_dict)
consumer.close()


from __future__ import print_function

import os
import sys

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import keras
from keras.utils import to_categorical
from keras.preprocessing.image import ImageDataGenerator
import cv2

from NeuralNet.DroneData import Loader
from NeuralNet.ModelLib import ModelFactory

class TrainCNN:

    def __init__(self):
        '''
        Initialize the directories
        '''
        if len(sys.argv) != 3:
            self.help()

        self.in_dir     = sys.argv[1]
        self.model_dir  = sys.argv[2]

        if not os.path.isdir(self.in_dir):
            self.help()
        if not os.path.isdir(self.model_dir):
            try:
                os.makedirs(self.model_dir)
            except OSError:
                pass
        self.model_file     = os.path.join(self.model_dir, 'drone_vision_model.json')
        self.weight_file    = os.path.join(self.model_dir, 'drone_vision_weight.h5')
        self.batch_size     = 256
        self.epochs         = 50

    def help(self):
        print("Usages: python train_cnn.py [input_dir] [model_dir]")
        sys.exit()

    def train(self):
        '''
        Train load data and train the network
        '''
        loader = Loader(self.in_dir)

        (train_images, train_labels), (test_images, test_labels)  = loader.balance_data()

        print('Training data shape : ', train_images.shape, train_labels.shape)
        print('Testing data shape : ', test_images.shape, test_labels.shape)

        classes     = np.unique(train_labels)
        nClasses    = len(classes)
        print('Total number of outputs : ', nClasses)
        print('Output classes : ', classes)

        plt.figure(figsize=[4,2])

        # Display the first image in training data
        plt.subplot(121)
        plt.imshow(train_images[0,:,:], cmap='gray')
        plt.title("Ground Truth : {}".format(train_labels[0]))

        # Display the first image in testing data
        plt.subplot(122)
        plt.imshow(test_images[0,:,:], cmap='gray')
        plt.title("Ground Truth : {}".format(test_labels[0]))

        # Find the shape of input images and create the variable input_shape
        nRows,nCols,nDims = train_images.shape[1:]
        train_data = train_images.reshape(train_images.shape[0], nRows, nCols, nDims)
        test_data = test_images.reshape(test_images.shape[0], nRows, nCols, nDims)
        input_shape = (nRows, nCols, nDims)

        # Change to float datatype
        train_data = train_data.astype('float32')
        test_data = test_data.astype('float32')

        # Scale the data to lie between 0 to 1
        train_data /= 255
        test_data /= 255

        # Change the labels from integer to categorical data
        train_labels_one_hot = to_categorical(train_labels)
        test_labels_one_hot = to_categorical(test_labels)

        print('Original label 0 : ', train_labels[0])
        print('After conversion to categorical ( one-hot ) : ', train_labels_one_hot[0])

        model = ModelFactory.createModel(nRows, nClasses, input_shape)
        model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy'])
        model.summary()

        # With Data Generator
    #     datagen = ImageDataGenerator(
    # #         zoom_range=0.2, # randomly zoom into images
    # #         rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)
    #         width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
    #         height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
    #         horizontal_flip=True,  # randomly flip images
    #         vertical_flip=False)  # randomly flip images

    #     history = model.fit_generator(datagen.flow(train_data, train_labels_one_hot, batch_size=self.batch_size),
    #                           steps_per_epoch=int(np.ceil(train_data.shape[0] / float(self.batch_size))),
    #                           epochs=self.epochs,
    #                           validation_data=(test_data, test_labels_one_hot),
    #                           workers=4)

        # Without data generator
        history = model.fit(train_data, train_labels_one_hot, batch_size=self.batch_size, epochs=self.epochs, verbose=1,
                   validation_data=(test_data, test_labels_one_hot))
        model.evaluate(test_data, test_labels_one_hot)

        # serialize model to JSON
        model_json = model.to_json()
        with open(self.model_file, "w") as json_file:
            json_file.write(model_json)
        # serialize weights to HDF5
        model.save_weights(self.weight_file)
        print("Saved model to disk")

        plt.figure(figsize=[8,6])
        plt.plot(history.history['loss'],'r',linewidth=3.0)
        plt.plot(history.history['val_loss'],'b',linewidth=3.0)
        plt.legend(['Training loss', 'Validation Loss'],fontsize=18)
        plt.xlabel('Epochs ',fontsize=16)
        plt.ylabel('Loss',fontsize=16)
        plt.title('Loss Curves',fontsize=16)

        plt.figure(figsize=[8,6])
        plt.plot(history.history['acc'],'r',linewidth=3.0)
        plt.plot(history.history['val_acc'],'b',linewidth=3.0)
        plt.legend(['Training Accuracy', 'Validation Accuracy'],fontsize=18)
        plt.xlabel('Epochs ',fontsize=16)
        plt.ylabel('Accuracy',fontsize=16)
        plt.title('Accuracy Curves',fontsize=16)

        print("Training Complete")

        plt.show()

if __name__ == "__main__":
    TrainCNN().train()


# import sys
# sys.path.insert(0, "/home/emmanuel/code/py_esdc")
# from py_esdc.utils import xarray2df
from sklearn.preprocessing import Normalizer
from sklearn.model_selection import train_test_split
import xarray as xr
import pandas as pd
import numpy as np
# import sys
import matplotlib.pyplot as plt
import matplotlib
plt.style.use('ggplot')

figure_path = '/home/emmanuel/projects/2019_sakame/reports/figures/dependence/'

class GetXYData:
  def __init__(
      self,
      normalize=True,
      subsample=None,
      variables=["gross_primary_productivity", "soil_moisture"],
      random_state=123,
  ):
    self.normalize = normalize
    self.subsample = subsample
    self.variables = variables
    self.random_state = random_state

  def set_XY(self, xr_data, xr_data2=None):
    """Excepts a dataframe with the time components.
    Converts it into an array."""
    # Convert xarray into dataframe for variables

    if xr_data2 is None:
      xr_data2 = xr_data

    X = xarray2df(xr_data[self.variables[0]])
    Y = xarray2df(xr_data2[self.variables[1]])

    # Merge the Two DataFrames
    var_df = X.merge(Y)

    # Drop the NA Values
    var_df = var_df.dropna()

    # Extract variables
    X = var_df[self.variables[0]].values
    Y = var_df[self.variables[1]].values
    lat = var_df["lat"]
    lon = var_df["lon"]

    # ===============
    # Normalize
    # ===============
    if self.normalize:
      self.x_normalizer = Normalizer()
      X = self.x_normalizer.fit_transform(X)

      self.y_normalizer = Normalizer()
      Y = self.y_normalizer.fit_transform(Y)

    # Subsample if necessary
    if self.subsample:
      X, _, Y, _, lat, _, lon, _ = train_test_split(
          X,
          Y,
          lat,
          lon,
          train_size=self.subsample,
          random_state=self.random_state,
      )

    return X, Y, lat, lon

class DependenceExplore:

  def __init__(self, variable1='root_moisture', variable2='gross_primary_productivity'):
    self.variable1 = variable1
    self.variable2 = variable2

  def get_xr_data(self, start_year='2010', end_year='2010'):

    ESDC_data = xr.merge([
        xr.open_mfdataset(
            '/media/disk/databases/BACI-CABLAB/low_res_data/root_moisture/*e.nc'),
        xr.open_mfdataset('/media/disk/databases/BACI-CABLAB/low_res_data/gross_primary_productivity/*.nc')]
    )
    var1 = ESDC_data[self.variable1].sel(
        time=slice(str(start_year), str(end_year)))
    var2 = ESDC_data[self.variable2].sel(
        time=slice(str(start_year), str(end_year)))

    return xr.merge([var1, var2])

  def plot_yearly_mean(self, xr_data, save_name=None):

    fig, ax = plt.subplots()

    xr_data.mean(dim='time').plot.pcolormesh(ax=ax, cmap='viridis')
    if save_name:
      fig.savefig(figure_path + save_name + '.png')

    plt.show()

    return None

  def get_corr(self, xr_data, var_name1='gross_primary_productivity', var_name2='root_moisture', corr='spatial', ):
    if corr == 'spatial':

      corr_func = get_corr_spatial
    elif corr == 'temporal':
      corr_func = get_corr_temporal
    else:
      raise ValueError(f'Unrecognized Variable: {corr}')

    corr_data = corr_func(
        xr_data[var_name1], xr_data[var_name2]
    )

    return corr_data

  def plot_corr(self, corr_data1, corr_data2, save_name=None):

    fig, ax = plt.subplots(figsize=(10, 5))

    corr_data1.plot(ax=ax, label='Europe', color='blue')
    corr_data2.plot(ax=ax, label='Russia', color='red')
    ax.legend()
    ax.set_ylabel('Correlation (GPP|RM)')

    if save_name:
      fig.savefig(figure_path + save_name + '.png')

    plt.show()

    return None

  def plot_monthly(self, xr_data1, xr_data2, stat='mean', save_name=None):

    fig, ax = plt.subplots(figsize=(10, 5))
    if stat == 'mean':
      xr_data1 = xr_data1.mean(dim=['lat', 'lon'])
      xr_data2 = xr_data2.mean(dim=['lat', 'lon'])
    elif stat == 'std':
      xr_data1 = xr_data1.std(dim=['lat', 'lon'])
      xr_data2 = xr_data2.std(dim=['lat', 'lon'])
    else:
      raise ValueError(f'Unrecognized stat: {stat}')

    xr_data1.plot(
        ax=ax, label='Europe', color='blue', linewidth=2)
    xr_data2.plot(
        ax=ax, label='Russia', color='red', linewidth=2)
    ax.legend(fontsize=15)
    ax.set_title('Monthly Spatial Mean')
    if save_name:
      fig.savefig(figure_path + save_name + f'_{stat}.png')
    plt.show()

    return None

  def get_subarea(self, xr_data, area='europe'):
    if area == 'europe':
      return xr_data.sel(lat=slice(70., 30.), lon=slice(-20., 35.))
    elif area == 'russia':
      return xr_data.sel(lat=slice(60., 50.), lon=slice(30., 60.))
    else:
      raise ValueError(f"Unrecognized area: {area}")

def standardize_spatial(x):
  return (x - x.mean(dim=['lat', 'lon'])) / x.std(dim=['lat', 'lon'])

def standardize_temporal(x):
  return (x - x.mean(dim=['time'])) / x.std(dim=['time'])

def get_corr_temporal(xr_data1, xr_data2):
  X = (xr_data1 - xr_data1.mean(dim='time', skipna=None))
  Y = (xr_data2 - xr_data2.mean(dim='time', skipna=None))

  # Get the covariance matrix
  cov = (X * Y)
  X_std = xr_data1.std(dim='time')
  Y_std = xr_data2.std(dim='time')

  corr_coef = (cov / (X_std * Y_std)).mean(dim=['lat', 'lon'])

  return corr_coef

def get_corr_spatial(xr_data1, xr_data2):

  times = xr_data1.time.data
  corr_coef = list()

  for itime in times:
    X_sub = xr_data1.sel(time=itime)
    Y_sub = xr_data2.sel(time=itime)

    # Calculate Mean
    X_mean = X_sub.mean(dim=['lat', 'lon'], skipna=None)
    Y_mean = Y_sub.mean(dim=['lat', 'lon'], skipna=None)

    # Calculate Standard Deviation
    X_std = X_sub.std(dim=['lat', 'lon'])
    Y_std = Y_sub.std(dim=['lat', 'lon'])

    # Subtract Mean

    X = (X_sub - X_mean)
    Y = (Y_sub - Y_mean)

    # Get the covariance matrix
    cov = (X * Y)

    # Get Correlation Coefficient
    coef = (cov / (X_std * Y_std)).mean(dim=['lat', 'lon'])
    coef['time'] = itime
    corr_coef.append(coef)
  return xr.concat(corr_coef, dim='time')

def xarray2df(xr_data: xr.DataArray) -> pd.DataFrame:
    """Converts an xarray dataset from (lat,lon,time)
    to a pandas dataframe of (lat, lon, time, data). Useful
    for machine learning methods but can be more inefficient
    due to repeated storage of redundant coordinates.

    Parameters
    ----------
    xr_data : xr.DataArray object ( l x w x h )
        coordinates = ['lat', 'lon', 'time']

    Returns
    -------
    pd.DataFrame : ((l x w x h) x columns)
        columns = ['lat', 'lon', 'time', 'data']

    Example
    -------
    >> dataset = xr.DataArray(...)
    >> df = xarray2df(dataset)
    """
    # Convert to Dataframe
    xr_df = xr_data.to_dataframe()

    # Reset Index to simple matrix
    xr_df = xr_df.reset_index().drop_duplicates()

    return xr_df