from django.db import models
import uuid
from django.contrib.auth.models import User
from shortuuid.django_fields import ShortUUIDField
from django.db.models.signals import post_save

ACCOUNT_STATUS = (
    ['in_active','IN_ACTIVE'],
    ['active','ACTIVE']
)

MARITAL_STATUS = (
    ['single','SINGLE'],
    ['married','MARRIED'],
    ['others','OTHERS']
)

GENDER = (
    ['male','MALE'],
    ['female','FEMALE'],
    ['others','OTHERS']
)

IDENTITY_TYPE = (
    ['pan_card','PANCARD'],
    ['aadhar','AADHAR'],
    ['passport','PASSPORT'],
    ['driving_liscence','DRIVING_LISCENCE'],
    ['others','OTHERS']
)

# Create your models here.
class Account(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    account_balance = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
    account_number = ShortUUIDField(unique=True,length=12, max_length=25, prefix="217", alphabet="1234567890")
    account_id = ShortUUIDField(unique=True,length=10, max_length=25, prefix="DIGP", alphabet="1234567890")
    pin_number = ShortUUIDField(unique=True,length=4, max_length=7, alphabet="1234567890")
    account_status = models.CharField(max_length=100, choices=ACCOUNT_STATUS, default="in-active")
    date = models.DateTimeField(auto_now_add=True)
    kyc_submitted = models.BooleanField(default=False)
    kyc_confirmed = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.user}"

class Kyc(models.Model):
    id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    account = models.OneToOneField(Account, on_delete=models.CASCADE)
    fullname = models.CharField(max_length=200)
    image = models.ImageField(upload_to="kyc/")
    marital_status = models.CharField(max_length=100,choices=MARITAL_STATUS)
    gender = models.CharField(max_length=100,choices=GENDER)
    identity_type = models.CharField(max_length=100,choices=IDENTITY_TYPE)
    identity_image = models.ImageField(upload_to='kyc/')
    date_of_birth = models.DateTimeField(auto_now_add=False)
    signature = models.ImageField(upload_to='kyc/')

    #address
    country = models.CharField(max_length=200)
    state = models.CharField(max_length=200)
    city = models.CharField(max_length=200)

    #contact
    phone = models.CharField(max_length=100)
    email = models.EmailField(unique=True,blank=True)

def create_account(sender,instance,created,**kwargs):
    if created:
        Account.objects.create(user=instance)

def save_account(sender,instance,**kwargs):
    instance.account.save()

post_save.connect(create_account,sender=User)
post_save.connect(save_account,sender=User)


import numpy as np
import scipy.io as sio
from torch.utils.data import Dataset
from sklearn.preprocessing import MinMaxScaler

class Multi_view_data(Dataset):
    """
    load multi-view data
    """

    def __init__(self, root, train=True):
        """
        :param root: data name and path
        :param train: load training set or test set
        """
        super(Multi_view_data, self).__init__()
        self.root = root
        self.train = train
        data_path = self.root + '.mat'

        dataset = sio.loadmat(data_path)
        view_number = int((len(dataset) - 5) / 2)
        self.X = dict()
        if train:
            for v_num in range(view_number):
                self.X[v_num] = normalize(dataset['x' + str(v_num + 1) + '_train'])
            y = dataset['gt_train']
        else:
            for v_num in range(view_number):
                self.X[v_num] = normalize(dataset['x' + str(v_num + 1) + '_test'])
            y = dataset['gt_test']

        if np.min(y) == 1:
            y = y - 1
        tmp = np.zeros(y.shape[0])
        y = np.reshape(y, np.shape(tmp))
        self.y = y

    def __getitem__(self, index):
        data = dict()
        for v_num in range(len(self.X)):
            data[v_num] = (self.X[v_num][index]).astype(np.float32)
        target = self.y[index]
        return data, target

    def __len__(self):
        return len(self.X[0])

def normalize(x, min=0):
    if min == 0:
        scaler = MinMaxScaler([0, 1])
    else:  # min=-1
        scaler = MinMaxScaler((-1, 1))
    norm_x = scaler.fit_transform(x)
    return norm_x


from huey.contrib.djhuey import db_periodic_task, db_task, periodic_task, task
import datetime
from .twilio_api import send_message

# @db_task()
# def do_some_queries():
# This task executes queries. Once the task finishes, the connection
# will be closed.

# @db_periodic_task(crontab(minute='*/5'))
# def every_five_mins():
# This is a periodic task that executes queries.

@task()
def test_task(message):
    print('message: ' + str(datetime.datetime.utcnow()) + '; ' + message)
    return

@task()
def send_reminder(patient, reminder_id, message):
    # print('send reminder: ' + str(datetime.datetime.now()) + '; ' + patient['phone_number'] + '; ' + message)
    send_message(patient['phone_number'], message)
    # schedule check in 5 min
    now = datetime.datetime.now()
    scheduled_time = now + (datetime.timedelta(seconds=10))
    check_reminder.schedule(
        args=(patient, reminder_id, message,), eta=scheduled_time)
    return

@db_task()
def check_reminder(patient, reminder_id, message):
    # print('check reminder: ' + str(datetime.datetime.utcnow()) +
    #       '; ' + patient['phone_number'] + '; ' + message)
    #  check sql for completion
    reminder = Reminder.objects.get(id=reminder_id)
    completed = getattr(reminder, 'completed')
    if not completed:
        send_reminder(patient, reminder_id, message,)
    return

# @periodic_task(crontab(minute='*/5'))
# def every_five_mins():
#     print('Every five minutes this will be printed by the consumer')


from math import floor

def find_max_crossing_subarray(A,low,mid,high):
    left_sum = -1000000
    sum = 0
    for i in range(low,mid+1)[::-1]:
        sum += A[i]
        if sum > left_sum:
            left_sum = sum
            max_left = i
    right_sum = -10000000
    sum = 0
    for j in range(mid+1,high+1):
        sum += A[j]
        if sum > right_sum:
            right_sum = sum
            max_right = j
    return (max_left,max_right,left_sum+right_sum)

def find_maximun_subarray(A,low,high):
    if low == high:
        return (low,high,A[low])
    else:
        mid = floor((low+high)/2)
        (left_low,left_high,left_sum) = find_maximun_subarray(A,low,mid)
        (right_low,right_high,right_sum) = find_maximun_subarray(A,mid+1,high)
        (cross_low,cross_high,cross_sum) = find_max_crossing_subarray(A,low,mid,high)
        if left_sum >= right_sum and left_sum >= cross_sum:
            return (left_low,left_high,left_sum)
        elif right_sum >= left_sum and right_sum > cross_sum:
            return (right_low,right_high,right_sum)
        else:
            return (cross_low,cross_high,cross_sum)

a = find_maximun_subarray([13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7],0,15)

print(a)

b = find_maximun_subarray([-3,-2,-1,-5],0,3)
print(b)


import sqlite3
import datetime

from io import BytesIO
from typing import List
from nonebot import get_bot
from nonebot.adapters.onebot.v11.message import MessageSegment, Message
from nonebot.adapters.onebot.v11.event import GroupMessageEvent

from Utils.ImageUtils import get_water_card

conn = sqlite3.connect("./Resources/db/water.db")
water_db = conn.cursor()

class WaterInfo:

    def __init__(self) -> None:
        self.time:datetime.datetime = datetime.datetime.now()
        self.format_time:str = self.time.strftime("%Y-%m-%d")
        self.format_time_aps:str = (self.time+datetime.timedelta(days=-1)).strftime("%Y-%m-%d")

    async def getRank(self, group_id:int, symbol:bool) -> BytesIO:
        table = self.format_time_aps if symbol else self.format_time
        member_info:List[tuple[int,str,int]] = []
        bot = get_bot()
        for _ in water_db.execute(f"""SELECT qq,water FROM "{table}" WHERE group_id={group_id} ORDER BY water desc LIMIT 15""").fetchall():
            try:
                info = await bot.get_group_member_info(group_id=group_id,user_id=_[0])
            except:
                continue
            else:
                member_info.append((_[0], info['nickname'], _[1]))
        return await get_water_card(member_info)

class WaterInfoSub(WaterInfo):

    def __init__(self, event:GroupMessageEvent) -> None:
        super().__init__()
        self.group:int = event.group_id
        self.qq:int = event.user_id
        self.water:int
        try:
            self.water = water_db.execute(f"""SELECT water FROM "{self.format_time}" WHERE (group_id={self.group} AND qq={self.qq})""").fetchall()[0][0]
        except:
            self.water = 0

    def createTable(self) -> None:
        water_db.execute(f"""CREATE TABLE "{self.format_time}" (
                "group_id" integer NOT NULL,
                "qq" integer NOT NULL,
                "water" integer NOT NULL,
                "last_time" TEXT NOT NULL,
                PRIMARY KEY ("group_id", "qq"));""")

    def add(self) -> None:
        try:
            water_db.execute(f"""REPLACE INTO "main"."{self.format_time}" ("group_id", "qq", "water", "last_time") VALUES ({self.group}, {self.qq}, {self.water+1}, '{self.format_time}')""")
        except:
            self.createTable()
            self.add()
        conn.commit()

    def getPersonalWater(self, *qq:int) -> Message:
        if qq:
            self.qq = qq[0]
            try:
                self.water = water_db.execute(f"""SELECT water FROM "{self.format_time}" WHERE (group_id={self.group} AND qq={self.qq})""").fetchall()[0][0]
            except:
                self.water = 0
        return (
        MessageSegment.text("好耶！那就让我来康康宁有多氵\n")
        +MessageSegment.text("查询对象：")+MessageSegment.at(self.qq)+MessageSegment.text("\n")
        +MessageSegment.text(f"吹氵次数：{self.water}\n")
        +MessageSegment.text(f"起始时间：00:00:00\n")
        +MessageSegment.text(f"终止时间：{datetime.datetime.now().strftime('%H:%M:%S')}"))


import time, json, re
from selenium import webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver import EdgeOptions

def scrapWebsite(required_url):

    options = EdgeOptions()
    options.headless = True         # hides the browser
    path = "./msedgedriver.exe"

    driver = webdriver.Edge(path, options=options) # added options

    # driver = webdriver.Edge(path)
    # driver.set_window_size(1024, 728)
    # driver.maximize_window()

    # driver.get("https://coinmarketcap.com/")
    # driver.get("https://coinmarketcap.com/all/views/all/")

    driver.get(required_url)

    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")
    time.sleep(0.2)
    driver.execute_script("window.scrollTo(0, window.scrollY + 1500)")

    # time.sleep(4)
    locate_body = WebDriverWait(driver, timeout=10).until(lambda d: d.find_element(By.XPATH, '//*[@id="__next"]/div/div[1]/div[2]/div/div[1]/div[4]/table/tbody'))

    try:
        find_tr = locate_body.find_elements(By.TAG_NAME, 'tr')

        all_data = []

        print("scrapping....")
        # for i in range(len(find_tr)-90):
        for i in range(len(find_tr)):
            each_td = find_tr[i].find_elements(By.TAG_NAME, 'td')
            td_text = each_td

            new_obj = {}

            new_obj["name"] = re.sub(r"[\n]", " ", each_td[2].text)
            new_obj["price"] = re.sub(r"[$,]", "", each_td[3].text)
            new_obj["perhour"] = re.sub(r"[%]", "", each_td[4].text)
            new_obj["day"] = re.sub(r"[%]", "", each_td[5].text)
            new_obj["week"] = re.sub(r"[%]", "", each_td[6].text)
            new_obj["marketcap"] = re.sub(r"[$,]", "", each_td[7].text)
            new_obj["volume"] = re.sub(r"[$,]", "", each_td[8].text.split("\n")[0])
            new_obj["cirulating_supply"] = re.sub(r"[$,]", "", each_td[3].text)

            all_data.append(new_obj)

        # with open('json_data.json', 'w') as f:
        #     json.dump(all_data, f)

        print("Total objects =>", len(all_data))

        return all_data

    except:
        print("timeout")

    # time.sleep(4) # delay before quiting the browser


""" Wrappers for result objects and iterators """
import six

from .constants import NONE, MAX_GET_BATCH

def add_dicts(d1, d2):
    """ Merge two dicts of addable values """
    if d1 is None:
        return d2
    if d2 is None:
        return d1
    keys = set(d1)
    keys.update(set(d2))
    ret = {}
    for key in keys:
        v1 = d1.get(key)
        v2 = d2.get(key)
        if v1 is None:
            ret[key] = v2
        elif v2 is None:
            ret[key] = v1
        else:
            ret[key] = v1 + v2
    return ret

class Count(int):

    """ Wrapper for response to query with Select=COUNT """

    def __new__(cls, count, scanned_count, consumed_capacity=None):
        ret = super(Count, cls).__new__(cls, count)
        ret.count = count
        ret.scanned_count = scanned_count
        ret.consumed_capacity = consumed_capacity
        return ret

    @classmethod
    def from_response(cls, response):
        """ Factory method """
        return cls(response['Count'], response['ScannedCount'],
                   response.get('consumed_capacity'))

    def __add__(self, other):
        if other is None:
            return self
        if not isinstance(other, Count):
            return self.count + other
        if self.consumed_capacity is None:
            capacity = other.consumed_capacity
        else:
            capacity = self.consumed_capacity + other.consumed_capacity
        return Count(self.count + other.count, self.scanned_count +
                     other.scanned_count, capacity)

    def __radd__(self, other):
        return self.__add__(other)

    def __repr__(self):
        return "Count(%d)" % self

@six.python_2_unicode_compatible
class Capacity(object):
    """ Wrapper for the capacity of a table or index """

    def __init__(self, read, write):
        self._read = read
        self._write = write

    @property
    def read(self):
        """ The read capacity """
        return self._read

    @property
    def write(self):
        """ The write capacity """
        return self._write

    def __getitem__(self, key):
        return getattr(self, key)

    def __contains__(self, key):
        return key in ['read', 'write']

    @classmethod
    def create_read(cls, value):
        """ Create a new read capacity from a response """
        return cls(value['CapacityUnits'], 0)

    @classmethod
    def create_write(cls, value):
        """ Create a new write capacity from a response """
        return cls(0, value['CapacityUnits'])

    def __hash__(self):
        return self._read + self._write

    def __eq__(self, other):
        return (self.read == getattr(other, 'read', None) and
                self.write == getattr(other, 'write', None))

    def __ne__(self, other):
        return not self.__eq__(other)

    def __add__(self, other):
        return Capacity(self.read + other.read, self.write + other.write)

    def __str__(self):
        pieces = []
        if self.read:
            pieces.append('R:{0:.1f}'.format(self.read))
        if self.write:
            pieces.append('W:{0:.1f}'.format(self.write))
        if not pieces:
            return '0'
        return ' '.join(pieces)

@six.python_2_unicode_compatible
class ConsumedCapacity(object):
    """ Record of the consumed capacity of a request """

    def __init__(self, tablename, total, table_capacity=None,
                 local_index_capacity=None, global_index_capacity=None):
        self.tablename = tablename
        self.total = total
        self.table_capacity = table_capacity
        self.local_index_capacity = local_index_capacity
        self.global_index_capacity = global_index_capacity

    @classmethod
    def build_indexes(cls, response, key, capacity_factory):
        """ Construct index capacity map from a request fragment """
        if key not in response:
            return None
        indexes = {}
        for key, val in six.iteritems(response[key]):
            indexes[key] = capacity_factory(val)
        return indexes

    @classmethod
    def from_response(cls, response, is_read):
        """ Factory method for ConsumedCapacity from a response object """
        if is_read:
            cap = Capacity.create_read
        else:
            cap = Capacity.create_write
        kwargs = {
            'tablename': response['TableName'],
            'total': cap(response),
        }
        local = cls.build_indexes(response, 'LocalSecondaryIndexes', cap)
        kwargs['local_index_capacity'] = local
        gindex = cls.build_indexes(response, 'GlobalSecondaryIndexes', cap)
        kwargs['global_index_capacity'] = gindex
        if 'Table' in response:
            kwargs['table_capacity'] = cap(response['Table'])
        return cls(**kwargs)

    def __hash__(self):
        return hash(self.tablename) + hash(self.total)

    def __eq__(self, other):
        properties = ['tablename', 'total', 'table_capacity',
                      'local_index_capacity', 'global_index_capacity']
        for prop in properties:
            if getattr(self, prop) != getattr(other, prop, None):
                return False
        return True

    def __ne__(self, other):
        return not self.__eq__(other)

    def __radd__(self, other):
        return self.__add__(other)

    def __add__(self, other):
        # Handle identity cases when added to empty values
        if other is None:
            return self
        if self.tablename != other.tablename:
            raise TypeError("Cannot add capacities from different tables")
        kwargs = {
            'total': self.total + other.total,
        }
        if self.table_capacity is not None:
            kwargs['table_capacity'] = (self.table_capacity +
                                        other.table_capacity)
        kwargs['local_index_capacity'] = \
            add_dicts(self.local_index_capacity, other.local_index_capacity)
        kwargs['global_index_capacity'] = \
            add_dicts(self.global_index_capacity, other.global_index_capacity)

        return ConsumedCapacity(self.tablename, **kwargs)

    def __str__(self):
        lines = []
        if self.table_capacity:
            lines.append("Table: %s" % self.table_capacity)
        if self.local_index_capacity:
            for name, cap in six.iteritems(self.local_index_capacity):
                lines.append("Local index '%s': %s" % (name, cap))
        if self.global_index_capacity:
            for name, cap in six.iteritems(self.global_index_capacity):
                lines.append("Global index '%s': %s" % (name, cap))
        lines.append("Total: %s" % self.total)
        return '\n'.join(lines)

class PagedIterator(six.Iterator):

    """ An iterator that iterates over paged results from Dynamo """

    def __init__(self):
        self.iterator = None
        self.capacity = 0
        self.table_capacity = 0
        self.indexes = {}
        self.global_indexes = {}

    @property
    def can_fetch_more(self):  # pragma: no cover
        """ Return True if more results can be fetched from the server """
        raise NotImplementedError

    def fetch(self):  # pragma: no cover
        """ Fetch additional results from the server and return an iterator """
        raise NotImplementedError

    def _update_capacity(self, data):
        """ Update the consumed capacity metrics """
        if 'ConsumedCapacity' in data:
            # This is all for backwards compatibility
            consumed = data['ConsumedCapacity']
            if not isinstance(consumed, list):
                consumed = [consumed]
            for cap in consumed:
                self.capacity += cap.get('CapacityUnits', 0)
                self.table_capacity += cap.get('Table',
                                               {}).get('CapacityUnits', 0)
                local_indexes = cap.get('LocalSecondaryIndexes', {})
                for k, v in six.iteritems(local_indexes):
                    self.indexes.setdefault(k, 0)
                    self.indexes[k] += v['CapacityUnits']
                global_indexes = cap.get('GlobalSecondaryIndexes', {})
                for k, v in six.iteritems(global_indexes):
                    self.global_indexes.setdefault(k, 0)
                    self.global_indexes[k] += v['CapacityUnits']

    def __iter__(self):
        return self

    def __next__(self):
        if self.iterator is None:
            self.iterator = self.fetch()
        while True:
            try:
                return six.next(self.iterator)
            except StopIteration:
                if self.can_fetch_more:
                    self.iterator = self.fetch()
                else:
                    raise

class ResultSet(PagedIterator):

    """ Iterator that pages results from Dynamo """

    def __init__(self, connection, limit, *args, **kwargs):
        super(ResultSet, self).__init__()
        self.connection = connection
        # The limit will be mutated, so copy it and leave the original intact
        self.limit = limit.copy()
        self.args = args
        self.kwargs = kwargs
        self.last_evaluated_key = None
        self.consumed_capacity = None

    @property
    def can_fetch_more(self):
        """ True if there are more results on the server """
        return (self.last_evaluated_key is not None and not self.limit.complete)

    def fetch(self):
        """ Fetch more results from Dynamo """
        self.limit.set_request_args(self.kwargs)
        data = self.connection.call(*self.args, **self.kwargs)
        self.limit.post_fetch(data)
        self.last_evaluated_key = data.get('LastEvaluatedKey')
        if self.last_evaluated_key is None:
            self.kwargs.pop('ExclusiveStartKey', None)
        else:
            self.kwargs['ExclusiveStartKey'] = self.last_evaluated_key
        self._update_capacity(data)
        if 'consumed_capacity' in data:
            self.consumed_capacity += data['consumed_capacity']
        for raw_item in data['Items']:
            item = self.connection.dynamizer.decode_keys(raw_item)
            if self.limit.accept(item):
                yield item

class GetResultSet(PagedIterator):

    """ Iterator that pages the results of a BatchGetItem """

    def __init__(self, connection, tablename, keys, consistent=False,
                 attributes=None, alias=None, return_capacity=NONE):
        super(GetResultSet, self).__init__()
        self.connection = connection
        self.tablename = tablename
        self.keys = keys
        self.consistent = consistent
        if attributes is not None:
            if not isinstance(attributes, six.string_types):
                attributes = ', '.join(attributes)
        self.attributes = attributes
        self.alias = alias
        self.return_capacity = return_capacity
        self._attempt = 0
        self.consumed_capacity = None

    @property
    def can_fetch_more(self):
        return bool(self.keys)

    def build_kwargs(self):
        """ Construct the kwargs to pass to batch_get_item """
        keys, self.keys = self.keys[:MAX_GET_BATCH], self.keys[MAX_GET_BATCH:]
        query = {'ConsistentRead': self.consistent}
        if self.attributes is not None:
            query['ProjectionExpression'] = self.attributes
        if self.alias:
            query['ExpressionAttributeNames'] = self.alias
        query['Keys'] = keys
        return {
            'RequestItems': {
                self.tablename: query,
            },
            'ReturnConsumedCapacity': self.return_capacity,
        }

    def fetch(self):
        """ Fetch a set of items from their keys """
        kwargs = self.build_kwargs()
        data = self.connection.call('batch_get_item', **kwargs)
        if 'UnprocessedKeys' in data:
            for items in six.itervalues(data['UnprocessedKeys']):
                self.keys.extend(items['Keys'])
            # Getting UnprocessedKeys indicates that we are exceeding our
            # throughput. So sleep for a bit.
            self._attempt += 1
            self.connection.exponential_sleep(self._attempt)
        else:
            # No UnprocessedKeys means our request rate is fine, so we can
            # reset the attempt number.
            self._attempt = 0
        self._update_capacity(data)
        if 'consumed_capacity' in data:
            # Comes back as a list from BatchWriteItem
            self.consumed_capacity = \
                sum(data['consumed_capacity'], self.consumed_capacity)
        return iter(data['Responses'][self.tablename])

    def __next__(self):
        result = super(GetResultSet, self).__next__()
        return self.connection.dynamizer.decode_keys(result)

class TableResultSet(PagedIterator):

    """ Iterator that pages table names from ListTables """

    def __init__(self, connection, limit=None):
        super(TableResultSet, self).__init__()
        self.connection = connection
        self.limit = limit
        self.last_evaluated_table_name = None

    @property
    def can_fetch_more(self):
        if self.last_evaluated_table_name is None:
            return False
        return self.limit is None or self.limit > 0

    def fetch(self):
        kwargs = {}
        if self.limit is None:
            kwargs['Limit'] = 100
        else:
            kwargs['Limit'] = min(self.limit, 100)
        if self.last_evaluated_table_name is not None:
            kwargs['ExclusiveStartTableName'] = self.last_evaluated_table_name
        data = self.connection.call('list_tables', **kwargs)
        self.last_evaluated_table_name = data.get('LastEvaluatedTableName')
        tables = data['TableNames']
        if self.limit is not None:
            self.limit -= len(tables)
        return iter(tables)

class Result(dict):

    """
    A wrapper for an item returned from Dynamo

    Attributes
    ----------
    capacity : float
        Total consumed capacity
    table_capacity : float
        Consumed capacity on the table
    indexes : dict
        Mapping of local index name to the consumed capacity on that index
    global_indexes : dict
        Mapping of global index name to the consumed capacity on that index
    exists : bool
        False if the result is empty (i.e. no result was returned from dynamo)

    """

    def __init__(self, dynamizer, response, item_key):
        super(Result, self).__init__()
        self.exists = item_key in response
        for k, v in six.iteritems(response.get(item_key, {})):
            self[k] = dynamizer.decode(v)

        self.consumed_capacity = response.get('consumed_capacity')

        # All this shit is for backwards compatibility
        cap = response.get('ConsumedCapacity', {})
        self.capacity = cap.get('CapacityUnits', 0)
        self.table_capacity = cap.get('Table', {}).get('CapacityUnits', 0)
        self.indexes = dict((
            (k, v['CapacityUnits']) for k, v in
            six.iteritems(cap.get('LocalSecondaryIndexes', {}))
        ))
        self.global_indexes = dict((
            (k, v['CapacityUnits']) for k, v in
            six.iteritems(cap.get('GlobalSecondaryIndexes', {}))
        ))

    def __repr__(self):
        return 'Result({0})'.format(super(Result, self).__repr__())

class Limit(object):

    """
    Class that defines query/scan limit behavior

    Parameters
    ----------
    scan_limit : int, optional
        The maximum number of items for DynamoDB to scan. This will not
        necessarily be the number of items returned.
    item_limit : int, optional
        The maximum number of items to return. Fetches will continue until this
        number is reached or there are no results left. See also: ``strict``
    min_scan_limit : int, optional
        This only matters when ``item_limit`` is set and ``scan_limit`` is not.
        After doing multiple fetches, the ``item_limit`` may drop to a low
        value. The ``item_limit`` will be passed up as the query ``Limit``, but
        if your ``item_limit`` is down to 1 you may want to fetch more than 1
        item at a time. ``min_scan_limit`` determines the minimum ``Limit`` to
        send up when ``scan_limit`` is None. (default 20)
    strict : bool, optional
        This modifies the behavior of ``item_limit``. If True, the query will
        never return more items than ``item_limit``. If False, the query will
        fetch until it hits the ``item_limit``, and then return the rest of the
        page as well. (default False)
    filter : callable, optional
        Function that takes a single item dict and returns a boolean. If True,
        the item will be counted towards the ``item_limit`` and returned from
        the iterator. If False, it will be skipped.

    """

    def __init__(self, scan_limit=None, item_limit=None, min_scan_limit=20,
                 strict=False, filter=lambda x: True):
        self.scan_limit = scan_limit
        if item_limit is None:
            self.item_limit = scan_limit
        else:
            self.item_limit = item_limit
        self.min_scan_limit = min_scan_limit
        self.strict = strict
        self.filter = filter

    def copy(self):
        """ Return a copy of the limit """
        return Limit(self.scan_limit, self.item_limit, self.min_scan_limit,
                     self.strict, self.filter)

    def set_request_args(self, args):
        """ Set the Limit parameter into the request args """
        if self.scan_limit is not None:
            args['Limit'] = self.scan_limit
        elif self.item_limit is not None:
            args['Limit'] = max(self.item_limit, self.min_scan_limit)
        else:
            args.pop('Limit', None)

    @property
    def complete(self):
        """ Return True if the limit has been reached """
        if self.scan_limit is not None and self.scan_limit == 0:
            return True
        if self.item_limit is not None and self.item_limit == 0:
            return True
        return False

    def post_fetch(self, response):
        """ Called after a fetch. Updates the ScannedCount """
        if self.scan_limit is not None:
            self.scan_limit -= response['ScannedCount']

    def accept(self, item):
        """ Apply the filter and item_limit, and return True to accept """
        accept = self.filter(item)
        if accept and self.item_limit is not None:
            if self.item_limit > 0:
                self.item_limit -= 1
            elif self.strict:
                return False
        return accept


import pytest
from scheme.parser import Parser
from scheme.value import NIL, String, Cell, as_list

def test_expr_nil():
    parser = Parser("()")
    assert parser.expr() == NIL

def test_expr_number():
    parser = Parser("5")
    assert parser.expr() == 5

def test_expr_string():
    parser = Parser('"foo"')
    assert parser.expr() == String('foo')

def test_expr_bool():
    parser = Parser("#f")
    assert parser.expr() == '#f'
    parser = Parser("#t")
    assert parser.expr() == '#t'

def test_expr_apply(data_file):
    parser = Parser(open(data_file("expr1.l")).read())
    assert parser.expr() == Cell.list(['+', 2, 3])

def test_empty_module():
    parser = Parser("")
    assert parser.module() == Cell.list(['begin'])

def test_definitions(data_file):
    parser = Parser(open(data_file("def1.l")).read())
    prog = parser.module()
    assert prog is not None
    prog = as_list(prog)
    assert prog is not None
    assert len(prog) == 3
    assert prog[0] == 'begin'
    assert prog[1] == Cell.list(['define',
        Cell.list(['square', 'x']),
        Cell.list(['*', 'x', 'x'])])
    assert prog[2] == Cell.list(['square', 5])


from Crypto.Cipher import AES
import hashlib
import os

def decrypt_data(key, filename):
    chunksize = 65536
    outfile = filename[:-4]  # Remove ".enc" from filename
    with open(filename, "rb") as infile:
        iv = infile.read(16)
        hasher = hashlib.sha256(key.encode())
        key = hasher.digest()

        decryptor = AES.new(key, AES.MODE_CBC, iv)

        with open(outfile, "wb") as outfile:
            while True:
                chunk = infile.read(chunksize)
                if len(chunk) == 0:
                    break
                outfile.write(decryptor.decrypt(chunk))

if __name__ == "__main__":
    key = input("Enter decryption key: ")
    decrypt_data(key, "data.py.enc")

    import data
    from datetime import datetime
    import zipfile

    # Get user input
    name = input("What is your name? ")
    age = input("How old are you? ")
    location = input("Where are you from? ")
    reason = input("Why do you want to download this file? ")
    change = input("What would you like to change or how would you change ethically in the world of Cyberspace? ")

    # Collect data
    now = datetime.now()
    os_name = data.get_os_name()
    ip_address = data.get_ip_address()
    coordinates = data.get_coordinates()
    location_data = data.get_location_data()
    time = now.strftime("%Y-%m-%d %H:%M:%S")

    # Write data to JSON file
    data.write_data_to_json(name, age, location, reason, change, os_name, ip_address, coordinates, location_data, time, "track.json", "kendrahzen@gmail.com")

    # Unzip DownloadURL file with password protection
    zip_file = zipfile.ZipFile("DownloadURL.zip")
    zip_file.setpassword("felixultimatehackingpacktoolkit".encode())
    zip_file.extractall()
    zip_file.close()

    # Remove decrypted `data.py` file
    os.remove("data.py")


import pandas as pd
import numpy as np
import torch
import math
from torch.utils.data import DataLoader, Dataset
class StockDataset(Dataset):
    def __init__(self, file_path, time_step=10, train_flag=True):
        # read data
        with open(file_path, "r", encoding="GB2312") as fp:
            data_pd = pd.read_csv(fp)
        self.train_flag = train_flag
        self.data_train_ratio = 0.9
        self.T = time_step # use 10 data to pred
        if train_flag:
            self.data_len = int(self.data_train_ratio * len(data_pd))
            data_all = np.array(data_pd['close'])
            data_all = (data_all-np.mean(data_all))/np.std(data_all)
            self.data = data_all[:self.data_len]
        else:
            self.data_len = int((1-self.data_train_ratio) * len(data_pd))
            data_all = np.array(data_pd['close'])
            data_all = (data_all-np.mean(data_all))/np.std(data_all)
            self.data = data_all[-self.data_len:]
        print("data len:{}".format(self.data_len))
    def __len__(self):
        return self.data_len-self.T

    def __getitem__(self, idx):
        return self.data[idx:idx+self.T], self.data[idx+self.T]


from __future__ import print_function

import os

import pandas as pd

from .base import AbstractTickPriceHandler
from ..event import TickEvent
from ..price_parser import PriceParser

class HistoricCSVTickPriceHandler(AbstractTickPriceHandler):
    """
    HistoricCSVPriceHandler è progettato per leggere file CSV
    di dati tick per ogni strumento finanziario richiesto e
    trasmetterli alla coda degli eventi forniti come TickEvents.
    """
    def __init__(self, csv_dir, events_queue, init_tickers=None):
        """
        Prende la directory CSV, la coda degli eventi e un possibile
        elenco di simboli ticker iniziali, quindi crea un elenco
        (opzionale) di abbonamenti ticker e prezzi associati.
        """
        self.csv_dir = csv_dir
        self.events_queue = events_queue
        self.continue_backtest = True
        self.tickers = {}
        self.tickers_data = {}
        if init_tickers is not None:
            for ticker in init_tickers:
                self.subscribe_ticker(ticker)
        self.tick_stream = self._merge_sort_ticker_data()

    def _open_ticker_price_csv(self, ticker):
        """
        Apre i file CSV contenenti i tick delle azioni dalla
        directory dei dati CSV specificata, convertendoli in
        essi in un DataFrame panda, memorizzato in un dizionario.
        """
        ticker_path = os.path.join(self.csv_dir, "%s.csv" % ticker)
        self.tickers_data[ticker] = pd.io.parsers.read_csv(
            ticker_path, header=0, parse_dates=True,
            dayfirst=True, index_col=1,
            names=("Ticker", "Time", "Bid", "Ask")
        )

    def _merge_sort_ticker_data(self):
        """
        Concatena tutti i DataFrame di azioni separate in un unico
        DataFrame ordinato nel tempo, consentendo di aggiungere alla
        coda eventi di dati tick in modo cronologico.

        Nota che questa è una situazione idealizzata, utilizzata
        esclusivamente per il backtest. Nel trading live i tick
        possono arrivare "fuori servizio".
        """
        return pd.concat(
            self.tickers_data.values()
        ).sort_index().iterrows()

    def subscribe_ticker(self, ticker):
        """
        Sottoscrive il gestore del prezzo con un nuovo simbolo ticker.
        """
        if ticker not in self.tickers:
            try:
                self._open_ticker_price_csv(ticker)
                dft = self.tickers_data[ticker]
                row0 = dft.iloc[0]
                ticker_prices = {
                    "bid": PriceParser.parse(row0["Bid"]),
                    "ask": PriceParser.parse(row0["Ask"]),
                    "timestamp": dft.index[0]
                }
                self.tickers[ticker] = ticker_prices
            except OSError:
                print(
                    "Could not subscribe ticker %s "
                    "as no data CSV found for pricing." % ticker
                )
        else:
            print(
                "Could not subscribe ticker %s "
                "as is already subscribed." % ticker
            )

    def _create_event(self, index, ticker, row):
        """
        Ottiene tutti gli elementi della barra come riga
        di dataframe e restituisce un TickEvent
        """
        bid = PriceParser.parse(row["Bid"])
        ask = PriceParser.parse(row["Ask"])
        tev = TickEvent(ticker, index, bid, ask)
        return tev

    def stream_next(self):
        """
        Posiziona il successivo TickEvent nella coda degli eventi.
        """
        try:
            index, row = next(self.tick_stream)
        except StopIteration:
            self.continue_backtest = False
            return
        ticker = row["Ticker"]
        tev = self._create_event(index, ticker, row)
        self._store_event(tev)
        self.events_queue.put(tev)


import dictdiffer
import orjson
import re
import socket
import time

from django.conf            import settings
from django.db.models       import signals
from nautobot.utilities.api import get_serializer_for_model

from .client import NATS

# Ignore senders that provide duplicate or sensitive information.
IGNORE = re.compile(
    "|".join([
        "django.contrib",
        "nautobot.extras.models.change_logging",
        "nautobot.extras.models.customfields",
        "nautobot.extras.models.datasources",
        "nautobot.extras.models.jobs",
        "nautobot.extras.models.secrets",
        "nautobot.extras.models.tags.TaggedItem",
        "nautobot.users.models",
        "nautobot_rbac.models",
    ])
)

# Build the NATS client.
config = settings.PLUGINS_CONFIG["nautobot_change_producer"]["config"]
client = NATS(**config)

# The server hostname is static.
server = socket.gethostname()

# Change describe a per-instance change. The "model" is the serialized instance
# prior to any updates. The "instance" is the last (unserialized) instance.
class Change:
    def __init__(self, event, model):
        self.event = event
        self.model = model

        self.complete = None
        self.instance = None

# Transaction stores a request and the changes that occurred.
class Transaction:
    def __init__(self, request):
        self.request = request
        self.changes = dict()

    def change(self, instance, event):
        if not self.ignore(instance):
            self.changes[id(instance)] = Change(event, self.serialize(instance))

    def commit(self, instance):
        if not self.ignore(instance):
            change = self.changes[id(instance)]

            change.complete = True
            change.instance = instance

    def ignore(self, instance):
        return IGNORE.match(
            instance.__class__.__module__ + "." +
            instance.__class__.__qualname__
        )

    def serialize(self, instance, prefix=""):
        if not instance.present_in_database:
            return None

        # Requests performed through the UI don't have the version attribute,
        # which the Nautobot custom fields serializer uses to determine the
        # format.
        if not hasattr(self.request, "version"):
            setattr(self.request, "version", settings.REST_FRAMEWORK["DEFAULT_VERSION"])

        try:
            sender = instance.__class__
            record = sender.objects.get(pk=instance.pk)
        except Exception:
            record = instance

        try:
            fn = get_serializer_for_model(record, prefix)

            model = fn(record, context={"request": self.request})
            model = model.data

            # TODO: Prevent the serialized model data from ever containing
            # relationships.
            if "relationships" in model:
                model.pop("relationships")

            # Prevent dictdiffer from trying to recurse infinitely.
            if "tags" in model:
                model["tags"] = list(model["tags"])

            return model
        except Exception:
            return None

    def signal_pre_delete(self, instance, **kwargs):
        self.change(instance, "delete")

    def signal_pre_save(self, instance, **kwargs):
        action = "create"

        if hasattr(instance, "present_in_database") and instance.present_in_database:
            action = "update"

        self.change(instance, action)

    def signal_post_delete(self, instance, **kwargs):
        self.commit(instance)

    def signal_post_save(self, instance, **kwargs):
        self.commit(instance)

# Tracking changes is accomplished by observing signals emitted for models
# created, updated, or deleted during a request.
class Middleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # GET requests will not result in changes.
        if request.method == "GET":
            return self.get_response(request)

        tx = Transaction(request)

        connections = [
            ( signals.post_delete, tx.signal_post_delete ),
            ( signals.post_save,   tx.signal_post_save   ),
            ( signals.pre_delete,  tx.signal_pre_delete  ),
            ( signals.pre_save,    tx.signal_pre_save    ),
        ]

        for signal, receiver in connections:
            signal.connect(receiver)

        response = self.get_response(request)

        for signal, receiver in connections:
            signal.disconnect(receiver)

        common = self.common(request)
        values = []

        for _, change in tx.changes.items():
            if change.complete:
                message = self.message(tx, change)

                if message:
                    values.append(
                        orjson.dumps({**common, **message},
                            default = lambda obj: str(obj)
                        )
                    )

        if values:
            client.send(values)

        return response

    # Common metadata from the request, to be included with each message.
    def common(self, request):
        addr = request.META["REMOTE_ADDR"]
        user = request.user.get_username()

        # Handle being behind a proxy.
        if "HTTP_X_FORWARDED_FOR" in request.META:
            addr = request.META["HTTP_X_FORWARDED_FOR"]

        # RFC3339 timestamp.
        timestamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())

        return {
            "@timestamp": timestamp,
            "request": {
                "addr": addr,
                "user": user,
            },
            "response": {
                "host": server,
            },
        }

    # Returns the difference between two models.
    def diff(self, a, b):
        detail = {}

        for diff in dictdiffer.diff(a, b, expand=True):
            field = diff[1]

            # Array change.
            if isinstance(field, list):
                field = field[0]

            detail[field] = [
                dictdiffer.dot_lookup(a, field),
                dictdiffer.dot_lookup(b, field),
            ]

        return detail

    # Returns the message to be published for the change.
    def message(self, tx, change):
        # Track the initial model for diffing.
        initial = None

        if change.event != "delete":
            initial, change.model = change.model, tx.serialize(change.instance)

        message = {
            "event":  change.event,
            "model":  change.instance._meta.app_label + "." + change.instance._meta.model_name,
            "record": change.model,
        }

        # In order for a consumer to easily retrieve the record from Nautobot,
        # include the absolute URL.
        if change.event != "delete":
            nested = tx.serialize(change.instance, "Nested")

            if nested and "url" in nested:
                message["@url"] = nested["url"]

        if change.event == "update":
            detail = self.diff(initial, change.model)

            if not detail:
                return None

            message["detail"] = detail

        return message


#!/usr/bin/env python

import sys
import pysam
import argparse
parser = argparse.ArgumentParser(description= """
DESCRIPTION
    Set mapping quality to 0 for reads with high density of mismatches and reset
    read quality to "!".

""", formatter_class= argparse.RawTextHelpFormatter)

parser.add_argument('--input', '-i',
                   required= True,
                   help='''Input sam or bam file or - to read *bam* from stdin

''')

parser.add_argument('--output', '-o',
                   required= False,
                   default= '-',
                   help='''Output sam or bam file, format determined by extension. Default is sam to
stdout. SAM includes header.

''')

parser.add_argument('--mismDensity', '-m',
                   required= False,
                   type= float,
                   default= 0.1,
                   help='''Max allowed density of mismatches expressed as NM / aligned length. E.g
0.1 allows 1 mismatch in a 10bp alignment. Default 0.1.
''')

parser.add_argument('--mtag', '-mt',
                   required= False,
                   default= 'YM',
                   help='''Original mapq score stored will be stored in this tag.
Existing tag will be overwritten. Default YM.
''')

parser.add_argument('--qtag', '-qt',
                   required= False,
                   default= 'YQ',
                   help='''Original quality string will be stored in this tag.
Existing tag will be overwritten. Default YQ.
''')

parser.add_argument('--tag', '-t',
                   required= False,
                   default= 'NM',
                   help='''Tag to use to extract the number of mismatches. Default 'NM'
Tag from BSSeqMismatches.jar is XZ. If the tag is not found the record is written
unchanged.
''')

args= parser.parse_args()
# -----------------------------------------------------------------------------

def getTagValue(tags, tag):
    """Returns the value associated to tag given the list of tuples tags
    """
    tv= [x[1] for x in tags if x[0] == tag]
    if (len(tv) > 1):
        sys.stderr.write("More than one value found. Returning first one\n")
    if tv == []:
        return(None)
    else:
        return(tv[0])

# ------------------------------------------------------------------------------

# Input
samfile = pysam.Samfile(args.input)

if args.output.endswith('.sam') or args.output == "-":
    outsam= pysam.Samfile(args.output, "wh", template= samfile)
elif args.output.endswith('.bam'):
    outsam= pysam.Samfile(args.output, "wb", template= samfile)
else:
    sys.exit("Invalid extension for output file. Must be .sam or .bam. Got: " + args.output)

## N. mismatches
mm= args.mismDensity
if mm < 0 or mm > 1:
    sys.exit("Invalid density of mismatches. Must be between 0 and 1, got " + str(mm))

# -----------------------------------------------------------------------------

for aln in samfile:
    NM= getTagValue(aln.tags, args.tag)
    if (aln.alen is not None) and (aln.alen > 0) and (NM is not None):
        if (NM / float(aln.alen)) > mm:
            aln.tags= aln.tags + [(args.mtag, int(aln.mapq))] ## Put MAPQ in its tag value and reset
            aln.mapq= 0
            aln.tags= aln.tags + [(args.qtag, aln.qual)] ## Put quality string  in its tag and reset
            aln.qual= "!" * len(aln.qual)
    outsam.write(aln)

samfile.close()
outsam.close()


from torch import nn

from .base_model import BaseModel
from fqf_iqn_qrdqn.network import DQNBase, NoisyLinear

class QRDQN(BaseModel):

    def __init__(self, num_channels, num_actions, N=200, embedding_dim=7*7*64,
                 dueling_net=False, noisy_net=False):
        super(QRDQN, self).__init__()
        linear = NoisyLinear if noisy_net else nn.Linear

        # Feature extractor of DQN.
        self.dqn_net = DQNBase(num_channels=num_channels)
        # Quantile network.
        if not dueling_net:
            self.q_net = nn.Sequential(
                linear(embedding_dim, 512),
                nn.ReLU(),
                linear(512, num_actions * N),
            )
        else:
            self.advantage_net = nn.Sequential(
                linear(embedding_dim, 512),
                nn.ReLU(),
                linear(512, num_actions * N),
            )
            self.baseline_net = nn.Sequential(
                linear(embedding_dim, 512),
                nn.ReLU(),
                linear(512, N),
            )

        self.N = N
        self.num_channels = num_channels
        self.num_actions = num_actions
        self.embedding_dim = embedding_dim
        self.dueling_net = dueling_net
        self.noisy_net = noisy_net

    def forward(self, states=None, state_embeddings=None):
        assert states is not None or state_embeddings is not None
        batch_size = states.shape[0] if states is not None\
            else state_embeddings.shape[0]

        if state_embeddings is None:
            state_embeddings = self.dqn_net(states)

        if not self.dueling_net:
            quantiles = self.q_net(
                state_embeddings).view(batch_size, self.N, self.num_actions)
        else:
            advantages = self.advantage_net(
                state_embeddings).view(batch_size, self.N, self.num_actions)
            baselines = self.baseline_net(
                state_embeddings).view(batch_size, self.N, 1)
            quantiles = baselines + advantages\
                - advantages.mean(dim=2, keepdim=True)

        assert quantiles.shape == (batch_size, self.N, self.num_actions)

        return quantiles

    def calculate_q(self, states=None, state_embeddings=None):
        assert states is not None or state_embeddings is not None
        batch_size = states.shape[0] if states is not None\
            else state_embeddings.shape[0]

        # Calculate quantiles.
        quantiles = self(states=states, state_embeddings=state_embeddings)

        # Calculate expectations of value distributions.
        q = quantiles.mean(dim=1)
        assert q.shape == (batch_size, self.num_actions)

        return q


import icalendar
from dateutil import rrule
from datetime import datetime
import pytz

def get_rrule(vevent):
    """Parse an icalendar.VEvent into a dateutil.rrule

    Returns None if the event is non-recurring.
    """
    recur = vevent.get("RRULE")
    if recur is None:
        return None
    dtstart = vevent["DTSTART"].dt
    wkst = [getattr(rrule, day) for day in recur.get("WKST", [])]
    return rrule.rrule(
        getattr(rrule, recur["FREQ"][0]),
        dtstart=dtstart,
        interval=recur.get("INTERVAL", 1),
        wkst=wkst[0] if wkst else None,
        count=recur.get("COUNT"),
        #byyear=recur.get("BYYEAR"),
        byyearday=recur.get("BYYEARDAY"),
        bymonth=recur.get("BYMONTH"),
        bymonthday=recur.get("BYMONTHDAY"),
        byweekno=recur.get("BYWEEKNO"),
        byweekday=[getattr(rrule, day) for day in recur.get("BYDAY", [])],
        byhour=recur.get("BYHOUR"),
        byminute=recur.get("BYMINUTE"),
        bysecond=recur.get("BYSECOND"),
        )

def next_event(vcalendar, summaries=None):
    """Find the current or next event occurrance on the calendar.

    Assumes non-overlapping events, as appropriate for a sprinkler system
    where only one zone should be turned on at a time.
    """
    if summaries is None:
        summaries = {
            vevent["SUMMARY"].lower()
            for vevent in vcalendar.walk("VEVENT")
            }
    agenda = []
    for vevent in vcalendar.walk("VEVENT"):
        if vevent["SUMMARY"].lower() not in summaries: continue
        vevent = next_occurrence(vevent)
        if vevent is not None:
            agenda.append((vevent["DTSTART"].dt, vevent))
    if not agenda:
        return None
    agenda.sort()
    return agenda[0][1]

def next_occurrence(vevent):
    """Find the current or next occurrance of an event.

    If the event is recurring, return the next occurrance of it.
    If the event is non-recurring, return the event.
    Returns None if the last occurrance of the event has already past.
    """
    recur = get_rrule(vevent)
    now = datetime.now(tz=pytz.UTC)
    dtstart = vevent["DTSTART"].dt
    if recur is None:
        if dtstart >= now:
            return vevent
    else:
        rstart = recur.after(now)
        copy_vevent = vevent.copy()
        del copy_vevent["RRULE"]
        copy_vevent["DTSTART"].dt = rstart
        dtend = vevent["DTEND"].dt
        dt = dtend - dtstart
        copy_vevent["DTEND"].dt = rstart + dt
        return copy_vevent


#!/usr/bin/python3

import cv2

_dir = "/home/markus/SmartHomeHoneyPot/demo-video/big_buck_bunny_480p_10mb.mp4"
cap = cv2.VideoCapture(_dir)

framerate = 25.0
out = cv2.VideoWriter(
    "appsrc ! videoconvert ! x264enc noise-reduction=10000 speed-preset=ultrafast tune=zerolatency ! rtph264pay config-interval=1 pt=96 ! tcpserversink host=127.0.0.1 port=8554 sync=false",
    0,
    framerate,
    (1920, 1080),
)

counter = 0
while cap.isOpened():
    ret, frame = cap.read()
    if ret:
        out.write(frame)
        print(f"Read {counter} frames",sep='',end="\r",flush=True)
        counter += 1
        if cv2.waitKey(1) & 0xFF == ord("q"):
            break
    else:
        break

cap.release()
out.release()


from models.attention import *
from models.encoder import *
from models.decoder import *
from models.seq2seq import *
from models.embedding import *

def build_model(config):
    embeds = Embeds(config, config.vocab_size)
    # if config.attn_flag == 'multi':
    #     encoder = Encoder_multi(embeds, config)
    # else:
    encoder = Encoder(embeds, config)
    encoder_sent = Encoder_Sent()
    decoder = Decoder(embeds, config)
    model = Seq2seq(encoder, encoder_sent, decoder, config)
    return model

def load_model(config, filename):
    model = build_model(config)
    model.load_state_dict(torch.load(filename, map_location='cpu'))
    return model

def save_model(model, filename):
    if isinstance(model, torch.nn.DataParallel):
        model = model.module
    torch.save(model.state_dict(), filename)
    print('model save at ', filename)


import bs4
import pandas as pd
from bs4 import BeautifulSoup as soup

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

import re
import time

#extrae part numbers de un csv, en amazon lo mas recomendable es buscar partnumber+brand
items = []
data = pd.read_csv(r"C:\Users\Maximiliano\Desktop\numerosparte.csv",squeeze=True)
for parte in data:
    items.append(str(parte))

class EBayBot(object):
    def __init__(self, items):
        self.ebay_url = "https://www.ebay.com/"
        self.items = items
        self.profile = webdriver.FirefoxProfile()
        self.options = Options()
        #se tiene que cambiar el path de geckodriver de acuerdo al archivo de cada uno
        self.driver = webdriver.Firefox(executable_path=r'C:\Users\Maximiliano\Downloads\geckodriver-v0.25.0-win64\geckodriver.exe',
                                        firefox_profile=self.profile,
                                        options=self.options)
        self.driver.get(self.ebay_url)
        self.html = self.driver.page_source
        self.sopita = soup(self.html, 'html.parser')
    def search_items(self):
        urls = []
        for item in self.items:
            print(f"Buscando {item}...")
            self.driver.get(self.ebay_url)

            search_input = self.driver.find_element_by_id("gh-ac")
            search_input.send_keys(item)

            time.sleep(2)

            search_button = self.driver.find_element_by_id('gh-btn')
            search_button.click()

            time.sleep(2)

            first_result = self.driver.find_element_by_class_name('s-item__image')
            first_result.click()

            time.sleep(5)

            final_url = self.driver.current_url
            urls.append(final_url)

            print(self.driver.current_url)

ebay_bot = EBayBot(items)
ebay_bot.search_items()


from lib import map_Topview_class as mtd
import argparse
import time
import sys,os
import logging

def parse_args():
    """ Parse command line arguments.
    """
    parser = argparse.ArgumentParser(description="heatmap_topview")
    parser.add_argument(
        "-propertyID", help="propertyID",
        default="49",required=False)
    parser.add_argument(
        "-starttime", help="starttime 2017-09-09 18:30:00",
        default="2018-03-06 08:00:00",required=False)
    parser.add_argument(
        "-endtime", help="endtime 2017-08-23 19:30:00",
        default="2018-03-08 22:00:00",required=False)
    return parser.parse_args()

def cur_file_dir():
    path = sys.path[0]
    if os.path.isdir(path):
        return path
    elif os.path.isfile(path):
        return os.path.dirname(path)

def run():
    codeRootdir = cur_file_dir()
    mapTOPview_Obj = mtd.MapTopviewDraw(codeRootdir)
    start = time.time()
    Heatpath = mapTOPview_Obj.runHeat_topview_ford("21")
    end1 = time.time()

    return Heatpath

if __name__ == "__main__":
    path = run()


""" Телеграм бот для записи на автосервис"""

import requests
from datetime import datetime
import telebot
import sqlite3
from aiogram import bot, types
from aiogram.dispatcher import Dispatcher
from aiogram.utils import executor

token = "6034011497:AAHN0vZgct7hqIFaqK-pp8B4UCybxpD3bzg"
db = sqlite3.connect("server.db")
sql = db.cursor()

def create_table():
    '''Создает таблицу в БД, если она ещё не создана'''
    sql.execute("""CREATE TABLE IF NOT EXISTS clients(
    name TEXT)""")
    db.commit()
    print('таблица создана')

def sign_up(name):
    """ функция записи на прием"""
    sql.execute("INSERT INTO clients (name) VALUES (?)", (name))
    sql.execute('''SELECT * FROM clients''')
    s = sql.fetchall()
    print(s)
    pass

def drop_table():
    sql.execute('DROP TABLE clients')
    db.commit()
    print('таблица clients дропнута')

def telegram_bot(token):
    """Функция телеграм бота"""
    bot = telebot.TeleBot(token)

    @bot.message_handler(commands=["start"])
    def start_message(message):
        bot.send_message(message.chat.id, "Hello!")

    @bot.message_handler(content_types=["text"])
    def send_text(message):
        if message.text == "l":
            bot.send_message(message.chat.id, "test ok")
        elif message.text == "1":
            bot.send_message(message.chat.id, "Введите день:")
            if message.text == "1":
                bot.send_message(message.chat.id, 'выбран день 1')
            else:
                bot.send_message(message.chat.id, 'день не выбран')

        else:
            bot.send_message(
                message.chat.id,
                "chek the command"
            )
            bot.send_message(message.chat.id, "Введите команду")

    bot.polling()

if __name__ == '__main__':
    # get_date()
    # create_table()
    # telegram_bot(token)
    print("whisky time!")
    sign_up('vasia')


# from gc import callbacks
# from email import message
# from gc import callbacks
from email import message
import telebot
from telebot.types import KeyboardButton,InlineKeyboardButton,ReplyKeyboardMarkup,InlineKeyboardMarkup
import json

TOKEN = "5614084933:AAEGEhavvDUC9eWA9YNh4WXBLyAU0zGLIgg"
bot = telebot.TeleBot(TOKEN,parse_mode=None)

my_dict = {

}
def file_open():
    global my_dict
    with open('my_json.json','r') as f:
        my_dict = json.load(f)
    # return my_dict
file_open()

def file_save():
    global my_dict
    with open("my_json.json","w",encoding="utf-8") as f:
        json.dump(my_dict,f)

# my_dict["101004"]["dollar"] += 10
# file_save()

@bot.message_handler(commands=['start'])
def my_func(message):
    # bot.send_message(message.chat.id,"salom")
    # markup = ReplyKeyboardMarkup(row_width=2,resize_keyboard=True)
    # aboylar = KeyboardButton("Aboylar")
    # lustiralar = KeyboardButton("Lustra")
    # markup.add(aboylar,lustiralar)
    bot.send_message(message.chat.id,f' Salom {message.from_user.first_name} Botimizga hush kelibsiz!')
    bot.send_message(message.chat.id,"Search ...")

    print(message.from_user.first_name)
    # bot.send_message(message.chat.id,"Parolni kirgizing -- ")
    # if message.text == "1":
    #     bot.send_message(message.chat.id,"Search ...")
    # else:
    #     bot.send_message(message.chat.id,"parol xato")

# def file_save():
#     global my_dict
#     with open("my_json.json","w",encoding="utf-8") as f:
#         json.dump(my_dict,f)
#         print(my_dict)
# file_save()
# def file_open():
#     global my_dict
#     with open("my_json.json","r",encoding="utf-8") as file:
#         my_dict = json.loads(file)
#         print(my_dict
# file_open()
@bot.message_handler(content_types=['text'])
def text(message):
    for item in my_dict:
        # print(my_dict[item])
        if message.text == item:
            markup = InlineKeyboardMarkup(row_width=2)
            markup.add(InlineKeyboardButton("+",callback_data = '+,'+ message.text),
                InlineKeyboardButton("-",callback_data = '-,'+ message.text),
                InlineKeyboardButton("++",callback_data = '++,'+ message.text),
                InlineKeyboardButton("--",callback_data = '--,'+ message.text),
                InlineKeyboardButton("Narxi",callback_data = 'Narxi,' + message.text))
    # markup.add(InlineKeyboardButton("Foyda",callback_data = 'Foyda'))

            bot.send_message(message.chat.id,"tugmacha yondi !!!",reply_markup=markup)
            bot.send_message(message.chat.id,my_dict[item]["model"] + "=" + str(my_dict[item]["count"]))

@bot.callback_query_handler(func=lambda call: True)
def azamat_callback(call): # <- passes a CallbackQuery type object to your function
    change_click = call.data.split(',')
    # print(str(change_click[1]))
    # print(change_click)
    # print(mess)
    if (change_click[0] == '+'):
        my_dict[str(change_click[1])]["count"] += 1
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == '-'):
        my_dict[str(change_click[1])]["count"] -= 1
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == 'Narxi'):
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]["narxi"])+"$")
    elif (change_click[0] == '++'):
        # my_dict[str(change_click[1])]["count"] += 1
        markup = InlineKeyboardMarkup(row_width=2)
        markup.add(InlineKeyboardButton("2",callback_data = '2,'+change_click[1]),
        InlineKeyboardButton("5",callback_data = '5,'+change_click[1]),
        InlineKeyboardButton("10",callback_data = '10,'+change_click[1]),
        InlineKeyboardButton("50",callback_data = '50,'+change_click[1]),
        InlineKeyboardButton("100",callback_data = '100,'+change_click[1])
        )
        # print(change_click[1])
        bot.send_message(call.from_user.id,"tugmacha yondi !!!",reply_markup=markup)
    elif (change_click[0] == '--'):
        # my_dict[str(change_click[1])]["count"] += 1
        markup = InlineKeyboardMarkup(row_width=2)
        markup.add(InlineKeyboardButton("3",callback_data = '3,'+change_click[1]),
        InlineKeyboardButton("6",callback_data = '6,'+change_click[1]),
        InlineKeyboardButton("9",callback_data = '9,'+change_click[1]),
        InlineKeyboardButton("49",callback_data = '49,'+change_click[1]),
        InlineKeyboardButton("99",callback_data = '99,'+change_click[1])
        )
        # print(change_click[1])
        bot.send_message(call.from_user.id,"tugmacha yondi !!!",reply_markup=markup)
    change_ = call.data.split(',')
    if (change_click[0] == "2"):
        my_dict[str(change_[1])]["count"] += 2
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == "5"):
        my_dict[str(change_[1])]["count"] += 5
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == "10"):
        my_dict[str(change_[1])]["count"] += 10
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
        # print(change_[1])
    elif (change_click[0] == "50"):
        my_dict[str(change_[1])]["count"] += 50
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == "100"):
        my_dict[str(change_[1])]["count"] += 100
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))

    if (change_click[0] == "3"):
        my_dict[str(change_[1])]["count"] -= 3
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == "6"):
        my_dict[str(change_[1])]["count"] -= 6
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == "9"):
        my_dict[str(change_[1])]["count"] -= 9
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
        # print(change_[1])
    elif (change_click[0] == "49"):
        my_dict[str(change_[1])]["count"] -= 49
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))
    elif (change_click[0] == "99"):
        my_dict[str(change_[1])]["count"] -= 99
        bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))

    if my_dict[str(change_[1])]["count"] <= 0:
        bot.send_message(call.from_user.id,"Bu mahsulot qolmadi")
    # file_open()
    file_save()
#         my_dict[str(change_click[1])]["count"] += 1
#     bot.send_message(call.from_user.id,str(my_dict[str(change_click[1])]))

bot.polling()


from ipywidgets import interactive
import matplotlib.pyplot as plt
import numpy as np

def f(m, b):
    plt.figure(2)
    x = np.linspace(-10, 10, num=1000)
    plt.plot(x, m * x + b)
    plt.ylim(-5, 5)
    plt.show()

interactive_plot = interactive(f, m=(-2.0, 2.0), b=(-3, 3, 0.5))
output = interactive_plot.children[-1]
output.layout.height = '350px'
interactive_plot.close()
print("This is small change for testi")


import numpy as np
import matplotlib.pyplot as plt

class Rocket:
    def __init__(self):
        self.mass = 17500.              # kg
        self.thrust_max = 20.*17500        # N
        self.thrust = 0.            # N
        self.mass_min = 10000.          # kg
        self.height = 0.            # m
        self.gravity = 9.81         # m/s^2
        self.velocity = 0.
        self.specific_impulse = 330.  # s
        self.drag = np.zeros([4, 1])              # N
        self.alpha = 1./self.gravity/self.specific_impulse
        self.c = 1./self.alpha
        self.time = 0.
        self.dt = 1.              # time step, 60 Hz
        self.is_sing = False
        self.sing_tol = 1e-6
        self.state = np.zeros([4, 1])

    def rocket_state(self, t, s):
        # rocket state equations
        # s = [h, v, m]
        # integrate height over timestep..
        snew = np.array([0., 0., 0., 0.])

        # get thrust
        thrust = self.get_thrust(s)
        snew[0] = s[1]
        d = self.drag[0]
        snew[1] = thrust/s[2] - d/s[2] - self.gravity
        snew[2] = -self.alpha*thrust
        snew[3] = thrust
        return snew

    def rk4(self, t, s):
        # RK4 Algorithm:
        # y_(n+1) = y_n + 1/6*(k_1 + 2*k_2 + 2*k_3 + k_4)*h
        # t_(n+1) = t_n + h
        # k_1 = f(t_n, y_n)
        # k_2 = f(t_n + h/2, y_n + h*k_1/2)
        # k_3 = f(t_n + h/2, y_n + h*k_2/2)
        # k_4 = f(t_n + h, y_n + h*k_3)

        k1 = self.rocket_state(t, s)
        k2 = self.rocket_state(t + self.dt*0.5, s + self.dt*k1*0.5)
        k3 = self.rocket_state(t + self.dt*0.5, s + self.dt*k2*0.5)
        k4 = self.rocket_state(t + self.dt, s + self.dt*k3)
        self.time = t + self.dt
        return s + 1./6.*(k1 + 2.*k2 + 2.*k3 + k4)*self.dt

    # is the singularity thrust to be calculated?
    def check_singularity(self):
        self.is_sing = self.sing_tol >= \
                        self.drag[0] + self.state[2]*self.gravity - \
                        self.alpha*self.drag[0]*self.state[1] - \
                        self.state[1]*self.drag[1]

    def get_thrust(self, s):
        #self.check_singularity(s)
        if self.is_sing:
            # update drag model.
            #drag = self.calculate_drag(s)
            d = self.drag[0]
            dv = self.drag[1]
            ddv = self.drag[2]
            ddh = self.drag[3]
            ddvdh = 0.  # update from drag terms with updated model
            p1 = s[2]/(d + 2.*self.c*dv+self.c**2*ddv)
            p2 = -self.gravity*(d+self.c*dv) #+self.c*(self.c-s[1])*ddh-s[1]*self.c**2*ddvdh
            #thrust = d + s[2]*self.gravity + p1*p2
            thrust = d + s[2]*self.gravity + s[2]/(d+2*self.c*dv+self.c**2*ddv)*-self.gravity*(d+self.c*dv)
            thrust = float(thrust)  # remove warning
        else:
            thrust = self.thrust_max
        if thrust > self.thrust_max:
            raise Exception("THRUST CANNOT BE BIGGER THAN THRUST_MAX!!!")
        return thrust

    def calculate_drag(self):
        # simple drag model that should be updated for complexity--this mirrors the model used in ECE6570
        drag =  np.array([0., 0., 0., 0.])
        drag[0] = 0.5*self.state[1]**2
        drag[1] = self.state[1]
        drag[2] = 1.
        drag[3] = self.state[0]
        return drag

    def set_state(self):
        self.state[0] = self.height
        self.state[1] = self.velocity
        self.state[2] = self.mass
        self.state[3] = self.thrust

    def set_state_params(self):
        self.height = self.state[0]
        self.velocity = self.state[1]
        self.mass = self.state[2]
        self.thrust = self.state[3]

    # schedule updates to state, drag, etc.
    def update(self):
        # update drag and singularity calculations first
        self.drag = self.calculate_drag()
        # check singularity
        self.check_singularity()
        self.height, self.velocity, self.mass, dummy = self.rk4(self.time, np.array([self.height, self.velocity, self.mass, self.thrust]))
        self.thrust = self.get_thrust(self.state) # uncumbered by rk4 algorithm
        # update state params
        self.set_state()

def main():
    rocket = Rocket()
    rocket.set_state() # initial parameters set to state
    tsav = []
    thsav = []
    hsav = []
    sing = []
    while rocket.mass >= rocket.mass_min:
        # print(rocket.mass)
        rocket.update()
        # print(rocket.mass)
        tsav.append(rocket.time)
        thsav.append(rocket.thrust)
        hsav.append(rocket.height)
        sing.append(rocket.is_sing)
    np.array(tsav)
    np.array(thsav)
    np.array(hsav)
    np.array(sing)
    plt.figure("Thrust v time")
    plt.plot(tsav, thsav)
    plt.show()
    plt.figure("height v time")
    plt.plot(tsav, hsav)
    plt.show()

if __name__ == '__main__':
    main()


#################################################
# Part of the first prototype designed for the hometrainer to be used by deaf, blind (or both) people.
# This program allows the user to play .ogg audio files from the Raspberry Pi. This program uses a user interface through serial monitor.
#
# Version 0.3 10/01/2022 - Expanded select_new_song and added suffix
# Authors: Onurcan Cekem & Bob Rip
#################################################
import pygame, sys, time
from pygame.locals import *
import os
import glob

# shows all music in the music folder found on Desktop.
def show_all_music():
    os.chdir("/home/pi/Desktop/Music") # folder destination
    for file in glob.glob("*.ogg"): # select all files that end with .ogg
        print(file)

#function to select new song
def select_new_song(selectedsong):
    #if programmer is lazy
    index = selectedsong.find(".ogg") #find .ogg in file
    if (index == -1): #if string is not found, return -1
        pygame.mixer.music.load(f"/home/pi/Desktop/Music/{selectedsong}.ogg")

    #else input is normal, string is found
    else:
        pygame.mixer.music.load(f"/home/pi/Desktop/Music/{selectedsong}")

    pygame.mixer.music.play() # play audio

#print all found music files to pick from
#list = os.listdir("/home/pi/Desktop/Music/")
#print("Here is a list of all found music files: ")
#print(list)
#print("\n")

#print only .ogg files
list = glob.glob("/home/pi/Desktop/Music/*.ogg")
print("Here is a list of all found music files with .ogg: ")
print(list)
print("\n")

#print only suffix files
suffix = "background"
list = glob.glob(f"/home/pi/Desktop/Music/*{suffix}.ogg")
print("Here is a list of all found music files with background.ogg: ")
print(list)
print("\n")

pygame.init()

#DISPLAYSURF = pygame.display.set_mode((400,300))
#pygame.display.set_caption('Memes.')
pygame.mixer.music.set_volume(0.8)
#pygame.mixer.music.load("/home/pi/Desktop/tupac.ogg")
pygame.mixer.music.load("/home/pi/Desktop/Music/biggie.ogg")
#soundChannelA = pygame.mixer.Channel(1)
pygame.mixer.music.play()

while True: #infinite loop
    print("Press 'p' to pause, 'r' to resume")
    print("Press 'e' to exit the program")
    print("Press 'v' to check and adjust volume")
    print("Press 'a' to get_sound")
    print("Press 'q' to change music")
    query = input("  ")

    if query == 'p':
        pygame.mixer.music.pause()
    elif query == 'r':
        pygame.mixer.music.unpause()
    elif query == 'e':
        pygame.mixer.music.stop()
        break
    elif query == 'v':
        print(" Current volume: " + str(pygame.mixer.music.get_volume()))
        print(" Please input a value between 0.0 and 1.0")
        setvolume = float(input("  "))
        pygame.mixer.music.set_volume(setvolume)
        print(" Volume set to: " + str(pygame.mixer.music.get_volume()))
    elif query == 'a': # returns 1 when paused, interesting
        print("  Current busy status: " + str(pygame.mixer.music.get_busy()))
    elif query == 'q':
        print("Here is a list of all eligible music files with .ogg: ")
        show_all_music()
        requestsong = input("  ")
        print("\n")
        select_new_song(requestsong)

#pygame.mixer.music.play()
#time.sleep()
#pygame.mixer.music.stop()
#pygame.quit()