# This package will contain the spiders of your Scrapy project
#
# Please refer to the documentation for information on how to create and manage
# your spiders.
# -*- coding: utf-8 -*-
import requests
import json
import logging
import time
import os
import scrapy
from scrapy.selector import Selector
from scrapy.utils.log import configure_logging

logger = logging.getLogger('utils')
req_logger = logger.getChild('request')
law_logger = logger.getChild('law')

def config_logging():
    configure_logging(install_root_handler=False,)
    logging.config.fileConfig(
        os.path.join(os.path.dirname(__file__), '..', '..', '..', 'logging.ini'),
        disable_existing_loggers=False,
    )

def request_url(url='', method='get', retries=3, **kwargs):
    """ Request url, if fail retry max retries time."""
    try:
        response = eval(f'requests.{method}(url, **kwargs)')

        req_logger.info(f'requests - {url} - status code {response.status_code}')
        datajson = response.json() if response.status_code == 200 else None
    except Exception as err:

        if retries:
            return request_url(url, method, retries - 1, **kwargs)

        datajson = None
        req_logger.error(f'request {url} - ERROR - {err}')

    return datajson

def set_law(item, arr_law, selector):
    """ item must dict or scrapy items
        arr_law get from api
        selector: html response or selector."""
    for key, law in arr_law.items():
        if not int(law['array']):
            try:
                if int(law['href']) == 0 and int(law['img']) == 0 and int(law['text']) == 0\
                        and int(law['content_text']) == 0 and law['other'] == "":
                    item[key] = law['value']
                elif int(law['img']):
                    item[key] = selector.css(f"{law['value']}::attr(src)").extract_first()
                elif int(law['text']):
                    item[key] = selector.css(f"{law['value']}::text").extract_first()
                elif int(law['href']):
                    item[key] = selector.css(f"{law['value']}::attr(href)").extract_first()
                elif int(law['content_text']):
                    item[key] = selector.css(law['value']).extract_first()
                elif law['other']:
                    item[key] = selector.css(law['value']).re_first(r'url\(([^\)]+)')
            except Exception as err:
                law_logger.error(err)
                item[key] = None

        elif int(law['array']):
            if int(law['img']):
                item[key] = selector.css(f"{law['value']}::attr(src)").extract()
            elif int(law['text']):
                item[key] = selector.css(f"{law['value']}::text").extract()
            elif int(law['href']):
                item[key] = selector.css(f"{law['value']}::attr(href)").extract()
            elif int(law['content_text']):
                item[key] = selector.css(law['value']).extract()
            elif law['other']:
                item[key] = selector.css(law['value']).re(r'url\(([^\)]+)')

    return item

def cookie_to_har(cookie):
    """
    Convert a Cookie instance to a dict in HAR cookie format.
    """
    c = {
        'name': cookie.name,
        'value': cookie.value,
        'secure': cookie.secure,
    }
    if cookie.path_specified:
        c['path'] = cookie.path

    if cookie.domain_specified:
        c['domain'] = cookie.domain

    if cookie.expires:
        tm = time.gmtime(cookie.expires)
        c['expires'] = time.strftime("%Y-%m-%dT%H:%M:%SZ", tm)

    http_only = cookie.get_nonstandard_attr('HttpOnly')
    if http_only is not None:
        c['httpOnly'] = bool(http_only)

    if cookie.comment:
        c['comment'] = cookie.comment

    return c

class obj(dict):

    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, attr):
        if attr in self.keys():
            data = self.__getitem__(attr)

            if type(data) is dict:
                object_converted =  obj(data)
            elif type(data) is list:
                object_converted =  array_obj(data)
            else:
                return data

            self.__setitem__(attr, object_converted)
            return object_converted
        else:
            return obj(dict())

class array_obj(list):

    def __getitem__(self, attr):
        data = super().__getitem__(attr)

        if type(data) is dict:
            object_converted =  obj(data)
        elif type(data) is list:
            object_converted =  array_obj(data)
        else:
            return data

        self.__setitem__(attr, object_converted)
        return object_converted

    def __iter__(self, *args, **kwargs):
        data = super().__iter__(*args, **kwargs)

        for d in data:
            if type(d) is list:
                yield array_obj(d)

            elif type(d) is dict:
                yield obj(d)

            else:
                yield d


__author__  = 'JPaschoal'
__version__ = '1.0.0'
__email__   = 'jonfisik@hotmail.com'
__status__  = 'Criando Classes'
__date__    = '08/06/2021'

#-----------------------------------------------------------
def traco():
    return print('-----'*10)

# Class
class Computador:
    def __init__(self, marca, memoria_ram, placa_de_video):
        self.marca = marca
        self.memoria_ram = memoria_ram
        self.placa_de_video = placa_de_video
    #pass

print('')
print("Classe computadores - ")
traco()
#-----------------------------------------------------------
Computador1 = Computador('Asus','8gb','Nvidia')
Computador2 = Computador('Dell','10gb','Gforce')
Computador3 = Computador('Acer','16gb','ATM')
#-----------------------------------------------------------
print(f'Computador 1 - {Computador1.marca,Computador1.memoria_ram,Computador1.placa_de_video}')
print(f'Computador 2 - {Computador2.marca,Computador2.memoria_ram,Computador2.placa_de_video}')
print(f'Computador 3 - {Computador3.marca,Computador3.memoria_ram,Computador3.placa_de_video}')
traco()
print('')
# END


import torch
import torch.nn as nn
import torch.nn.functional as F # for the activation function
import time
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(3, 6, 5)
        self.pool = nn.MaxPool2d(2, 2)
        self.conv2 = nn.Conv2d(6, 16, 5)
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 16 * 5 * 5)
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

class CNNModel(nn.Module):
    def __init__(self,numclass=2):
        super(CNNModel, self).__init__()
        self.conv1 = nn.Conv2d(3, 32, 5)
        self.conv2 = nn.Conv2d(32, 64, 5)
        self.conv3 = nn.Conv2d(64, 128, 3)
        self.conv4 = nn.Conv2d(128, 256, 5)
        self.fc1 = nn.Linear(256, numclass)
        self.pool = nn.MaxPool2d(2, 2)

    def forward(self, x):
        x = self.pool(F.relu(self.conv1(x)))
        x = self.pool(F.relu(self.conv2(x)))
        x = self.pool(F.relu(self.conv3(x)))
        x = self.pool(F.relu(self.conv4(x)))
        bs, _, _, _ = x.shape
        x = F.adaptive_avg_pool2d(x, 1).reshape(bs, -1)
        x = self.fc1(x)
        return x


# -*- coding: utf-8 -*-
"""
Author: Mario Königbauer (mkoenigb@gmx.de)
(C) 2022 - today by Mario Koenigbauer
License: GNU General Public License v3.0

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 3 of the License, or     *
 *   any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""

import operator, processing
from PyQt5.QtCore import QCoreApplication, QVariant
from qgis.core import (QgsField, QgsFeature, QgsProcessing, QgsExpression, QgsSpatialIndex, QgsSpatialIndexKDBush, QgsGeometry, QgsWkbTypes,
                       QgsFeatureSink, QgsFeatureRequest, QgsProcessingAlgorithm, QgsExpressionContext, QgsExpressionContextUtils,
                       QgsProcessingParameterVectorLayer, QgsProcessingParameterFeatureSink, QgsProcessingParameterField, QgsProcessingParameterDistance,
                       QgsProcessingParameterFeatureSource, QgsProcessingParameterEnum, QgsProcessingParameterExpression, QgsProcessingParameterNumber,
                       QgsProcessingParameterString, QgsProcessingParameterBoolean)

class CountNearestFeaturesByCondition(QgsProcessingAlgorithm):
    SOURCE_LYR = 'SOURCE_LYR'
    SOURCE_FILTER_EXPRESSION = 'SOURCE_FILTER_EXPRESSION'
    SOURCE_COMPARE_EXPRESSION = 'SOURCE_COMPARE_EXPRESSION'
    SOURCE_COMPARE_EXPRESSION2 = 'SOURCE_COMPARE_EXPRESSION2'
    OVERLAY_LYR = 'OVERLAY_LYR'
    OVERLAY_FILTER_EXPRESSION = 'OVERLAY_FILTER_EXPRESSION'
    OVERLAY_COMPARE_EXPRESSION = 'OVERLAY_COMPARE_EXPRESSION'
    OVERLAY_COMPARE_EXPRESSION2 = 'OVERLAY_COMPARE_EXPRESSION2'
    COUNT_FIELDNAME = 'COUNT_FIELDNAME'
    OPERATION = 'OPERATION'
    OPERATION2 = 'OPERATION2'
    CONCAT_OPERATION = 'CONCAT_OPERATION'
    COUNT_MULTIPLE = 'COUNT_MULTIPLE'
    MAX_DIST = 'MAX_DIST'
    OUTPUT = 'OUTPUT'

    def initAlgorithm(self, config=None):
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.SOURCE_LYR, self.tr('Source Layer (Features to add count to)')))
        self.addParameter(
            QgsProcessingParameterExpression(
                self.SOURCE_FILTER_EXPRESSION, self.tr('Filter-Expression for Source-Layer'), parentLayerParameterName = 'SOURCE_LYR', optional = True))
        self.addParameter(
            QgsProcessingParameterVectorLayer(
                self.OVERLAY_LYR, self.tr('Overlay Layer (Features to count)')))
        self.addParameter(
            QgsProcessingParameterExpression(
                self.OVERLAY_FILTER_EXPRESSION, self.tr('Filter-Expression for Overlay-Layer'), parentLayerParameterName = 'OVERLAY_LYR', optional = True))
        self.addParameter(
            QgsProcessingParameterDistance(
                self.MAX_DIST, self.tr('Maximum search distance (0 means unlimited)'), parentParameterName = 'SOURCE_LYR', optional = False))
        self.addParameter(
            QgsProcessingParameterBoolean(
                self.COUNT_MULTIPLE, self.tr('Count Features more than once\n(if not checked, a feature is only counted for the nearest feature.\nIn case more than one feature has the same minimum distance, it takes the first one)'), optional = True, defaultValue = True))
        self.addParameter(
            QgsProcessingParameterString(
                self.COUNT_FIELDNAME, self.tr('Count Fieldname'), defaultValue = 'count_n', optional = False))
        self.addParameter(
            QgsProcessingParameterExpression(
                self.SOURCE_COMPARE_EXPRESSION, self.tr('Compare-Expression for Source-Layer'), parentLayerParameterName = 'SOURCE_LYR', optional = True))
        self.addParameter(
            QgsProcessingParameterEnum(
                self.OPERATION, self.tr('Comparison operator (if no operator is set, the comparison expressions/fields remain unused) [optional]'), [None,'!=','=','<','>','<=','>=','is','is not','contains (overlay in source)'], defaultValue = 0, allowMultiple = False))
        self.addParameter(
            QgsProcessingParameterExpression(
                self.OVERLAY_COMPARE_EXPRESSION, self.tr('Compare-Expression for Overlay-Layer'), parentLayerParameterName = 'OVERLAY_LYR', optional = True))
        self.addParameter(
            QgsProcessingParameterEnum(
                self.CONCAT_OPERATION, self.tr('And / Or a second condition. (To only use one condition, leave this to AND)'), ['AND','OR','XOR','iAND','iOR','iXOR','IS','IS NOT'], defaultValue = 0, allowMultiple = False))
        self.addParameter(
            QgsProcessingParameterExpression(
                self.SOURCE_COMPARE_EXPRESSION2, self.tr('Second compare-Expression for Source-Layer'), parentLayerParameterName = 'SOURCE_LYR', optional = True))
        self.addParameter(
            QgsProcessingParameterEnum(
                self.OPERATION2, self.tr('Second comparison operator (if no operator is set, the comparison expressions/fields remain unused) [optional]'), [None,'!=','=','<','>','<=','>=','is','is not','contains (overlay in source)'], defaultValue = 0, allowMultiple = False))
        self.addParameter(
            QgsProcessingParameterExpression(
                self.OVERLAY_COMPARE_EXPRESSION2, self.tr('Second compare-Expression for Overlay-Layer'), parentLayerParameterName = 'OVERLAY_LYR', optional = True))
        self.addParameter(
            QgsProcessingParameterFeatureSink(
                self.OUTPUT, self.tr('Count')))

    def processAlgorithm(self, parameters, context, feedback):
        feedback.setProgressText('Prepare processing...')
        source_layer = self.parameterAsSource(parameters, self.SOURCE_LYR, context)
        source_layer_vl = self.parameterAsLayer(parameters, self.SOURCE_LYR, context)
        source_compare_expression = self.parameterAsExpression(parameters, self.SOURCE_COMPARE_EXPRESSION, context)
        source_compare_expression = QgsExpression(source_compare_expression)
        source_compare_expression2 = self.parameterAsExpression(parameters, self.SOURCE_COMPARE_EXPRESSION2, context)
        source_compare_expression2 = QgsExpression(source_compare_expression2)
        overlay_layer_vl = self.parameterAsLayer(parameters, self.OVERLAY_LYR, context)
        overlay_compare_expression = self.parameterAsExpression(parameters, self.OVERLAY_COMPARE_EXPRESSION, context)
        overlay_compare_expression = QgsExpression(overlay_compare_expression)
        overlay_compare_expression2 = self.parameterAsExpression(parameters, self.OVERLAY_COMPARE_EXPRESSION2, context)
        overlay_compare_expression2 = QgsExpression(overlay_compare_expression2)
        operation = self.parameterAsInt(parameters, self.OPERATION, context)
        operation2 = self.parameterAsInt(parameters, self.OPERATION2, context)
        concat_operation = self.parameterAsInt(parameters, self.CONCAT_OPERATION, context)
        ops = {
            0: None,
            1: operator.ne,
            2: operator.eq,
            3: operator.lt,
            4: operator.gt,
            5: operator.le,
            6: operator.ge,
            7: operator.is_,
            8: operator.is_not,
            9: operator.contains
            }
        op = ops[operation]
        op2 = ops[operation2]
        cops = {
            0: operator.and_, # None is equal to AND: easier to implement, the second condition then is just '' == '', so always true.
            1: operator.or_,
            2: operator.xor,
            3: operator.iand,
            4: operator.ior,
            5: operator.ixor,
            6: operator.is_,
            7: operator.is_not
            }
        concat_op = cops[concat_operation]

        comparisons = False
        if op is not None and op2 is not None:
            comparisons = True
        elif op is None and op2 is None:
            comparisons = False
        elif op is None and op2 is not None:
            op = operator.eq # None is equal to ==: easier to implement, the second condtion then is just '' == '', so always true.
            overlay_compare_expression = QgsExpression('') # Ignore eventually set fields/expressions!
            source_compare_expression = QgsExpression('') # Ignore eventually set fields/expressions!
            comparisons = True
        elif op2 is None and op is not None:
            op2 = operator.eq # None is equal to ==: easier to implement, the second condtion then is just '' == '', so always true.
            overlay_compare_expression2 = QgsExpression('') # Ignore eventually set fields/expressions!
            source_compare_expression2 = QgsExpression('') # Ignore eventually set fields/expressions!
            comparisons = True

        source_filter_expression = self.parameterAsExpression(parameters, self.SOURCE_FILTER_EXPRESSION, context)
        source_filter_expression = QgsExpression(source_filter_expression)
        overlay_filter_expression = self.parameterAsExpression(parameters, self.OVERLAY_FILTER_EXPRESSION, context)
        overlay_filter_expression = QgsExpression(overlay_filter_expression)
        count_fieldname = self.parameterAsString(parameters, self.COUNT_FIELDNAME, context)
        count_multiple = self.parameterAsBool(parameters, self.COUNT_MULTIPLE, context)
        max_dist = self.parameterAsDouble(parameters, self.MAX_DIST, context)

        sourceoverlayequal = False
        if source_layer_vl == overlay_layer_vl:
            sourceoverlayequal = True

        source_layer_fields = source_layer_vl.fields()
        output_layer_fields = source_layer_fields
        whilecounter = 0
        while count_fieldname in output_layer_fields.names():
            whilecounter += 1
            count_fieldname = count_fieldname + '_2'
            if whilecounter > 9:
                feedback.setProgressText('You should clean up your fieldnames!')
                break

        output_layer_fields.append(QgsField(count_fieldname, QVariant.Int))

        (sink, dest_id) = self.parameterAsSink(parameters, self.OUTPUT, context,
                                               output_layer_fields, source_layer_vl.wkbType(),
                                               source_layer_vl.sourceCrs())

        if source_filter_expression not in (QgsExpression(''),QgsExpression(None)):
            source_layer_vl = source_layer_vl.materialize(QgsFeatureRequest(source_filter_expression))
        if overlay_filter_expression not in (QgsExpression(''),QgsExpression(None)):
            overlay_layer_vl = overlay_layer_vl.materialize(QgsFeatureRequest(overlay_filter_expression))

        if comparisons:
            if source_layer_vl.featureCount() * 2 + overlay_layer_vl.featureCount() > 0:
                total = 100.0 / (source_layer_vl.featureCount() * 2 + overlay_layer_vl.featureCount())
            else:
                total = 0
        else:
            total = 100.0 / (source_layer_vl.featureCount() + overlay_layer_vl.featureCount()) if (source_layer_vl.featureCount() + overlay_layer_vl.featureCount()) > 0 else 0
        current = 0

        if source_layer_vl.sourceCrs() != overlay_layer_vl.sourceCrs():
            feedback.setProgressText('Reprojecting Overlay Layer...')
            reproject_params = {'INPUT': overlay_layer_vl, 'TARGET_CRS': source_layer_vl.sourceCrs(), 'OUTPUT': 'memory:Reprojected'}
            reproject_result = processing.run('native:reprojectlayer', reproject_params)
            overlay_layer_vl = reproject_result['OUTPUT']

        feedback.setProgressText('Building spatial index...')
        source_layer_idx = QgsSpatialIndex(source_layer_vl.getFeatures(), flags=QgsSpatialIndex.FlagStoreFeatureGeometries)

        if comparisons: # dictonaries are a lot faster than featurerequests; https://gis.stackexchange.com/q/434768/107424
            feedback.setProgressText('Evaluating expressions...')
            source_layer_dict = {}
            source_layer_dict2 = {}
            source_compare_expression_context = QgsExpressionContext()
            source_compare_expression_context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(source_layer_vl))
            source_compare_expression_context2 = QgsExpressionContext()
            source_compare_expression_context2.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(source_layer_vl))
            for source_feat in source_layer_vl.getFeatures():
                current += 1
                if feedback.isCanceled():
                    break
                source_compare_expression_context.setFeature(source_feat)
                source_compare_expression_result = source_compare_expression.evaluate(source_compare_expression_context)
                source_layer_dict[source_feat.id()] = source_compare_expression_result
                source_compare_expression_context2.setFeature(source_feat)
                source_compare_expression_result2 = source_compare_expression2.evaluate(source_compare_expression_context2)
                source_layer_dict2[source_feat.id()] = source_compare_expression_result2
                feedback.setProgress(int(current * total))
        result_dict = {}

        feedback.setProgressText('Start processing...')
        overlay_compare_expression_context = QgsExpressionContext()
        overlay_compare_expression_context.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(overlay_layer_vl))
        overlay_compare_expression_context2 = QgsExpressionContext()
        overlay_compare_expression_context2.appendScopes(QgsExpressionContextUtils.globalProjectLayerScopes(overlay_layer_vl))
        for overlay_feat in overlay_layer_vl.getFeatures():
            current += 1
            if feedback.isCanceled():
                break

            nearest_source_features = source_layer_idx.nearestNeighbor(overlay_feat.geometry(), neighbors = -1, maxDistance = max_dist)
            if sourceoverlayequal:
                nearest_source_features.remove(overlay_feat.id())

            if comparisons:
                overlay_compare_expression_context.setFeature(overlay_feat)
                overlay_compare_expression_result = overlay_compare_expression.evaluate(overlay_compare_expression_context)
                overlay_compare_expression_context2.setFeature(overlay_feat)
                overlay_compare_expression_result2 = overlay_compare_expression2.evaluate(overlay_compare_expression_context2)

            for source_feat_id in nearest_source_features:
                if feedback.isCanceled():
                    break

                doit = False
                if comparisons:
                    source_compare_expression_result = source_layer_dict[source_feat_id]
                    source_compare_expression_result2 = source_layer_dict2[source_feat_id]
                    if concat_op(op(source_compare_expression_result, overlay_compare_expression_result),op2(source_compare_expression_result2, overlay_compare_expression_result2)):
                        doit = True
                else:
                    doit = True

                if doit:
                    if source_feat_id not in result_dict:
                        result_dict[source_feat_id] = 0
                    result_dict[source_feat_id] += 1
                    if not count_multiple:
                        break
            feedback.setProgress(int(current * total))

        feedback.setProgressText('Creating result layer...')
        for source_feat in source_layer_vl.getFeatures():
            if feedback.isCanceled():
                break
            new_feat = QgsFeature(output_layer_fields)
            new_feat.setGeometry(source_feat.geometry())
            attridx = 0
            for attr in source_feat.attributes():
                new_feat[attridx] = attr
                attridx += 1
            if source_feat.id() not in result_dict:
                new_feat[count_fieldname] = 0
            else:
                new_feat[count_fieldname] = result_dict[source_feat.id()]
            sink.addFeature(new_feat, QgsFeatureSink.FastInsert)
            feedback.setProgress(int(current * total))

        return {self.OUTPUT: dest_id}

    def tr(self, string):
        return QCoreApplication.translate('Processing', string)

    def createInstance(self):
        return CountNearestFeaturesByCondition()

    def name(self):
        return 'CountNearestFeaturesByCondition'

    def displayName(self):
        return self.tr('Count Nearest Features by Condition')

    def group(self):
        return self.tr(self.groupId())

    def groupId(self):
        return 'Vector - Conditional'

    def shortHelpString(self):
        return self.tr('This algorithm counts nearest features by a maximum search distance and optional attribute condition(s).\nYou may choose whether a feature should be counted more than once, if you deny, that feature is only counted to the nearest match.')


#!/usr/bin/python
# Imports to support python 3 compatibility
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

from collections import namedtuple
import pandas as pd
import datetime
import re
import numpy as np
import numpy.linalg as la

from LINZ.Geodetic.Ellipsoid import GRS80

from . import Util
from .Fortran import Format

class StationCoord( object ):
    '''
    Class representing station coordinate information read from Bernese station file
    '''

    def __init__(self, id, code, name, datum, crddate, xyz, vxyz, flag):
        self.id=id
        self.code=code
        self.name=name
        self.datum=datum
        self.crddate=crddate
        self.xyz=xyz
        self.vxyz=vxyz
        self.flag=flag

    def epochXyz( self, date=None ):
        '''
        Function to calculate the coordinate at a specific date.
        Returns a vector [X,Y,Z]
        '''
        if date is None or self.crddate is None or self.vxyz is None:
            return list(self.xyz)
        ydiff=(date-self.crddate).days/365.242
        xyz=self.xyz
        vxyz=self.vxyz
        return [xyz[0]+vxyz[0]*ydiff,xyz[1]+vxyz[1]*ydiff,xyz[2]+vxyz[2]*ydiff]

def read( filename, velocityFilename=None, velocities=False, tryVelocities=False, skipError=False, useCode=False ):
    '''
    Read a bernese coordinate file and returns a dictionary of StationData
    keyed on station code.  If velocities is True then a matching .VEL file will be loaded.
    If tryVelocities is True then a velocity file will be tried, but the routine will not fail
    if it cannot be read.  If velocityFilename is specified then a velocity file will be loaded.
    '''

    filename=Util.expandpath(filename)

    if tryVelocities or velocityFilename is not None:
        velocities=True

    dtmfmt=Format('22X,A18,7X,A20','datum epoch',True)
    crdfmt=Format('I3,2X,A16,3F15.4,4X,A1','id name X Y Z flag',True)

    veldata={}
    if velocities:
        try:
            if velocityFilename is None:
                velocityFilename=re.sub(r'(?:\.CRD((?:\.gz)?))?$',r'.VEL\1',filename)
            for data in crdfmt.readfile(velocityFilename,skipLines=6,skipBlanks=True,skipErrors=True):
                code=data.name[:4]
                key=code if useCode else data.name
                veldata[key]=[data.X,data.Y,data.Z]
        except:
            if not tryVelocities:
                raise

    coords={}

    if filename.endswith('.gz'):
        import gzip
        f=gzip.open(filename,'rb')
    else:
        f=open(filename)
    try:
        # Skip two header lines
        f.readline()
        f.readline()
        # Read datum line
        dtm=dtmfmt.read(f.readline())
        datum=dtm.datum
        match=re.match(r'(\d{4})\-(\d\d)-(\d\d)\s+(\d\d)\:(\d\d)\:(\d\d)',dtm.epoch)
        if match is None:
            raise RuntimeError('Invalid datum epoch '+dtm.epoch+' in '+filename)
        year,mon,day,hour,min,sec=(int(x) for x in match.groups())
        crddate=datetime.datetime(year,mon,day,hour,min,sec)
        try:
            for data in crdfmt.readiter(f,skipBlanks=True,skipErrors=True):
                code=data.name[:4]
                key=code if useCode else data.name
                xyz=[data.X,data.Y,data.Z]
                vxyz=veldata.get(key)
                coords[key]=StationCoord(data.id,code,data.name,datum,crddate,xyz,vxyz,data.flag)
        except:
            if not skipError:
                raise
    finally:
        f.close()
    return coords

def compare( codes=None, codesCoordFile=None, useCode=False, velocities=False, skipError=False, **files ):
    '''
    Compare two or more bernese coordinate files, and return a pandas DataFrame of
    common codes.

    File names or coord data are entered as key/value pairs where the key is used to identify
    the data in the Dataframe (ie coordinate columns are key_X, key_Y, key_Z)

    Can take a list of codes to include in the comparison as either a list [codes],
    string [codes], or bernese coordinate file containing the codes [codesCoordFile]

    If just two files are compared then the differences are included in the data frame.
    '''
    coords={}
    usecodes=None
    nfiles=0
    for f in files:
        nfiles += 1
        crddata=files[f]
        if isinstance(crddata,basestring):
            crddata=read(crddata,useCode=useCode,skipError=skipError,velocities=velocities)
        coords[f]=crddata
        fcodes=set(crddata)
        if usecodes is None:
            usecodes=fcodes
        else:
            usecodes=usecodes.intersection(fcodes)

    if nfiles == 0:
        raise RuntimeError("No files specified in CoordFile.Compare")
    if usecodes is None or len(usecodes) == 0:
        raise RuntimeError("No common codes to compare in CoordFile.Compare")

    codelist=None
    if codes is not None:
        if isinstance(codes,basestring):
            codes=codes.split()
        usecodes=usecodes.intersection(set(codes))

    if codesCoordFile is not None:
        cfcodes=read(codesCoordFile,useCode=useCode,skipError=skipError)
        usecodes=usecodes.intersection(set(cfcodes))

    if len(usecodes) == 0:
        raise RuntimeError("No common codes selected in CoordFile.Compare")

    data=[]
    usecodes=sorted(usecodes)
    crdtypes=sorted(coords)
    calcdiff=len(crdtypes) == 2
    for code in sorted(usecodes):
        codedata=[code]
        cdata=[coords[t][code] for t in crdtypes]
        lon,lat,hgt=GRS80.geodetic(cdata[0].xyz)
        if lon < 0:
            lon += 360.0
        codedata.extend((lon,lat,hgt))
        codedata.extend((c.flag for c in cdata))
        for c in cdata:
            codedata.extend(c.xyz)
            if velocities:
                codedata.extend(c.vxyz or [np.Nan,np.Nan,np.Nan])
        if calcdiff:
            xyz0=np.array(cdata[0].xyz)
            xyz1=np.array(cdata[1].xyz)
            dxyz=xyz1-xyz0
            denu=GRS80.enu_axes(lon,lat).dot(dxyz)
            codedata.extend(dxyz)
            codedata.extend(denu)
            codedata.append(la.norm(denu))
            if velocities:
                xyz0=np.array(cdata[0].vxyz or [np.NaN,np.NaN,np.NaN])
                xyz1=np.array(cdata[1].vxyz or [np.NaN,np.NaN,np.NaN])
                dxyz=xyz1-xyz0
                denu=GRS80.enu_axes(lon,lat).dot(dxyz)
                codedata.extend(dxyz)
                codedata.extend(denu)
                codedata.append(la.norm(denu))
        data.append(codedata)

    columns=['code','lon','lat','hgt']
    columns.extend((t+'_flg' for t in crdtypes))
    for  t in crdtypes:
        columns.extend((t+'_X',t+'_Y',t+'_Z'))
        if velocities:
            columns.extend((t+'_VX',t+'_VY',t+'_VZ'))
    if calcdiff:
        columns.extend(('diff_X','diff_Y','diff_Z','diff_E','diff_N','diff_U','offset'))
        if velocities:
            columns.extend(('diff_VX','diff_VY','diff_VZ','diff_VE','diff_VN','diff_VU','offsetV'))
    df=pd.DataFrame(data,columns=columns)
    df.set_index(df.code,inplace=True)
    return df

def compare_main():
    import argparse
    parser=argparse.ArgumentParser(description='Compare two bernese coordinate files')
    parser.add_argument('crd_file_1',help='Name of first CRD file (can enter as type=filename)')
    parser.add_argument('crd_file_2',help='Name of second CRD file (can enter as type=filename)')
    parser.add_argument('csv_file',nargs='?',help='Name of output CSV file of differences')
    parser.add_argument('-c','--use-code',action='store_true',help='Use station code rather than full name')
    parser.add_argument('-v','--use-velocities',action='store_true',help='Compare velocities as well as ')
    args=parser.parse_args()

    cmpfiles={}
    for i,f in enumerate((args.crd_file_1,args.crd_file_2)):
        if '=' in f:
            k,v=f.split('=',1)
            cmpfiles[k]=v
        else:
            cmpfiles['crd'+str(i+1)]=f

    cmpdata=compare(useCode=args.use_code,skipError=True,velocities=args.use_velocities,**cmpfiles)
    if args.csv_file is not None:
        cmpdata.to_csv(args.csv_file,index=False,float_format="%.6f")
    else:
        print(cmpdata.loc[:,('diff_X','diff_Y','diff_Z','diff_E','diff_N','diff_U')].describe());

if __name__=='__main__':
    compare_main()


from __future__ import annotations
from typing import List, Optional
from generic_funcs.search.generic_search import bfs, Node, node_to_path

MAX_NUM: int = 3

class MCState:
    def __init__(self, missionaries: int, cannibals: int, boat: bool) -> None:
        self.wm: int = missionaries  # west missionaries
        self.wc: int = cannibals
        self.em: int = MAX_NUM - self.wm  # east missionaries
        self.ec: int = MAX_NUM - self.wc
        self.boat: bool = boat

    def __str__(self) -> str:
        place = "west" if self.boat else "east"
        return (
            f"Missionaries at west: {self.wm}\n"
            f"Missionaries at east: {self.em}\n"
            f"Cannibals at west: {self.wc}\n"
            f"Cannibals at east: {self.ec}\n"
            f"The boat is at the {place} bank"
        )

    def goal_test(self) -> bool:
        return self.is_legal and self.em == MAX_NUM and self.ec == MAX_NUM

    @property
    def is_legal(self) -> bool:
        if self.wc > self.wm > 0:
            return False
        if self.ec > self.em > 0:
            return False
        return True

    def successors(self) -> List[MCState]:
        sucs: List[MCState] = []
        if self.boat:  # boat on the west
            if self.wm > 1:
                sucs.append(MCState(self.wm - 2, self.wc, not self.boat))
            if self.wm > 0:
                sucs.append(MCState(self.wm - 1, self.wc, not self.boat))
            if self.wc > 1:
                sucs.append(MCState(self.wm, self.wc - 2, not self.boat))
            if self.wc > 0:
                sucs.append(MCState(self.wm, self.wc - 1, not self.boat))
            if (self.wc > 0) and (self.wm > 0):
                sucs.append(MCState(self.wm - 1, self.wc - 1, not self.boat))
        else:  # boat on the east
            if self.em > 1:
                sucs.append(MCState(self.wm + 2, self.wc, not self.boat))
            if self.em > 0:
                sucs.append(MCState(self.wm + 1, self.wc, not self.boat))
            if self.ec > 1:
                sucs.append(MCState(self.wm, self.wc + 2, not self.boat))
            if self.ec > 0:
                sucs.append(MCState(self.wm, self.wc + 1, not self.boat))
            if (self.ec > 0) and (self.em > 0):
                sucs.append(MCState(self.wm + 1, self.wc + 1, not self.boat))
        return [x for x in sucs if x.is_legal]

def display_solution(path_to_display: List[MCState]):
    if len(path_to_display) == 0:  # sanity check
        return
    old_state: MCState = path_to_display[0]
    print(old_state)
    for current_state in path_to_display[1:]:
        if current_state.boat:
            print(f"{old_state.em - current_state.em} missionaries "
                  f"and {old_state.ec - current_state.ec} cannibals "
                  f"moved from the east to west.")
        else:
            print(f"{old_state.wm - current_state.wm} missionaries "
                  f"and {old_state.wc - current_state.wc} cannibals "
                  f"moved from the west to east.")
        # print(current_state)
        old_state = current_state

if __name__ == "__main__":
    start: MCState = MCState(MAX_NUM, MAX_NUM, True)
    solution: Optional[Node[MCState]] = bfs(start, MCState.goal_test,
                                            MCState.successors)
    if solution is None:
        print("No solution found!")
    else:
        path: List[MCState] = node_to_path(solution)
        display_solution(path)


from PySimpleGUI import PySimpleGUI as sg
from modulos.moedas_cotacao import *

sg.theme("Reddit")
# pegando cotações
cotacoes = [str(dolar()),
            str(euro()),
            str(bitcoin())]

#layout do menu
menu_layout = [['Arquivo',['Salvar', 'Sair']],
               ['Ajuda', ['Sobre']]]

# layout da janela toda
layout = [
    # layout menu
    [sg.Menu(menu_layout)],
    # visor de entrada e respostas
    [sg.Input(key='entrada',size=(25,3), background_color='gray',font=('Arial 22'))],
    # cotações das moedas
    [sg.Text(text='Cotação Dólar    R$',font=('Arial 12')),sg.Text(text=cotacoes[0],font=('Arial 12'))],
    [sg.Text(text='Cotação Euro     R$',font=('Arial 12')),sg.Text(text=cotacoes[1],font=('Arial 12'))],
    [sg.Text(text='Cotação Bitcoin  R$',font=('Arial 12')),sg.Text(text=cotacoes[2],font=('Arial 12'))],
    # primeira linha de botões
    [sg.Button('/',size=(3,1),font=('Arial 20'),key='dividir'),
        sg.Button('x',size=(3,1),font=('Arial 20'),key='multiplicar'),
        sg.Button('-',size=(3,1),font=('Arial 20'),key='subtrair'),
        sg.Button('+',size=(3,1),font=('Arial 20'),key='somar')],
    # segunda linha de botões
    [sg.Button('7',size=(3,1),font=('Arial 20'),key='sete'),
        sg.Button('8',size=(3,1),font=('Arial 20'),key='oito'),
        sg.Button('9',size=(3,1),font=('Arial 20'),key='nove'),
        sg.Button('%',size=(3,1),font=('Arial 20'),key='porcentagem')],
    # terceira linha de botões
    [sg.Button('4',size=(3,1),font=('Arial 20'),key='quatro'),
        sg.Button('5',size=(3,1),font=('Arial 20'),key='cinco'),
        sg.Button('6',size=(3,1),font=('Arial 20'),key='seis'),
        sg.Button('C',size=(3,1),font=('Arial 20'),key='clear')],
    # quarta linha de botões
    [sg.Button('1',size=(3,1),font=('Arial 20'),key='um'),
        sg.Button('2',size=(3,1),font=('Arial 20'),key='dois'),
        sg.Button('3',size=(3,1),font=('Arial 20'),key='tres'),
        sg.Button('<<',size=(3,1),font=('Arial 20'),key='backspace')],
    # quinta linha de botões
    [sg.Button('^',size=(3,1),font=('Arial 20'),key='potencia'),
        sg.Button('0',size=(3,1),font=('Arial 20'),key='zero'),
        sg.Button(',',size=(3,1),font=('Arial 20'),key='virgula'),
        sg.Button('=',size=(3,1),font=('Arial 20'),key='igual')]
]

Programas Simples/Calculadora com Cotações/layout.py


def quick_sort(sequence):
    length = len(sequence)
    if length <= 1:
        return sequence
    else:
        pivot = sequence.pop()

    items_greater = []
    items_lower = []

    for item in sequence:
        if item > pivot:
            items_greater.append(item)
        else:
            items_lower.append(item)

    return(quick_sort(items_lower) + [pivot] + quick_sort(items_greater))

''' QUICK_SORT ALGORITHM EXAMPLE
list = []
for i in range(11):
    import random
    i = random.randrange(0, 11)
    list.append(i)

print(quick_sort(list))
'''


import logging
import threading
import time
import PySide2

from PySide2.QtWidgets import *
from PySide2.QtWebEngineWidgets import *
from PySide2.QtCore import *
from ..Event import Event

class Alert(QMessageBox):

    def __init__(self, *__args):
        QMessageBox.__init__(self)
        self.timeout = 0
        self.autoclose = False
        self.currentTime = 0

    def showEvent(self, QShowEvent):
        self.currentTime = 0
        if self.autoclose:
            self.startTimer(1000)

    def timerEvent(self, *args, **kwargs):
        self.currentTime += 1
        if self.currentTime >= self.timeout:
            self.done(0)

    @staticmethod
    def showWithTimeout(message):
        w = Alert()
        w.autoclose = True
        w.timeout = 10
        w.setText(message)
        w.setWindowTitle("Error")
        w.setIcon(QMessageBox.Critical)
        w.setStandardButtons(QMessageBox.NoButton)
        w.exec_()

class Worker(QObject):
    finished = Signal()

    def run(self):
        for i in range(10):
            time.sleep(1)
        self.finished.emit()

class NetworkController():
    def __init__(self, ruta, webview, speech_synthesis):
        self.webview = webview
        self.ruta = ruta
        self.event = Event("")
        self.speech_synthesis = speech_synthesis

    def disconnected(self):
        logging.error("Desconexión de internet")
        self.speech_synthesis.cancel_speech()
        Alert.showWithTimeout("El Equipo se desconectó de internet")

    def connected(self):
        self.thread = QThread()
        self.worker = Worker()
        self.worker.moveToThread(self.thread)
        self.thread.started.connect(self.worker.run)
        self.worker.finished.connect(self.thread.quit)
        self.worker.finished.connect(self.worker.deleteLater)
        self.thread.finished.connect(self.thread.deleteLater)
        self.thread.start()
        print("Start thread")
        self.thread.finished.connect(self.reload_view)

    def reload_view(self):
        self.webview.load(QUrl(self.ruta))
        print("Load")

    def get_event(self):
        return self.event


'''Real example (API level, out-of-line)

https://cffi.readthedocs.io/en/latest/overview.html#real-example-api-level-out-of-line
'''

from cffi import FFI

def create_ffibuilder():
    ffibuilder = FFI()

    module_name = 'pyopenssl_examples.cffi.openssl.bio_01_connect_openssl'

    # c-source code (like *.c files)
    c_source = r'''\
        #include "stdio.h"  // FILE

        #include "openssl/bio.h"
        #include "openssl/err.h"
        #include "openssl/ssl.h"
    '''

    ffibuilder.set_source(module_name, c_source, libraries=['ssl', 'crypto'])

    # c-definitions: function declarations, types, macros, global variables
    # (like *.h files)
    c_defs = '''\
        typedef struct bio_st BIO;
        BIO *BIO_new_connect(const char *host_port);
        int BIO_do_connect(BIO *b);
        int BIO_puts(BIO *bp, const char *buf);
        BIO *BIO_new_fp(FILE *stream, int close_flag);
        int BIO_read(BIO *b, void *data, int dlen);
        int BIO_write(BIO *b, const void *data, int dlen);
        int BIO_free(BIO *a);
    '''

    ffibuilder.cdef(c_defs)

    return ffibuilder

def main():
    ffibuilder = create_ffibuilder()
    ffibuilder.compile(verbose=True)

if __name__ == '__main__':
    main()


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

import os, sys

def pdf_split(filename_base, first_page, last_page, length_item):
    """
    Counting from first_page to last_page, split into small PDF files of length_item pages, use pdftk
    """
    mainname, extname = os.path.splitext(filename_base)  # mainname is '123', extname is '.pdf'
    print('Start to split the file '+filename_base)
    for start_page in range(first_page, last_page, length_item):
        end_page = start_page + length_item - 1
        newfilename = mainname + '_' + str(start_page) + '-' + str(end_page) + extname
        os.system('pdftk '+filename_base+' cat '+str(start_page)+'-'+str(end_page)+' output '+newfilename)
        print('File ' + newfilename + ' created in the same directory with ' + filename_base)
    print('Finished splitting the file '+filename_base)

if __name__ == "__main__":
    filename_base = str(sys.argv[1])
    first_page = int(sys.argv[2])
    last_page = int(sys.argv[3])
    length_item = int(sys.argv[4])
    pdf_split(filename_base, first_page, last_page, length_item)


import sys
import heapq
from collections import deque

allow = [(-1, 0),(1, 0), (0, 1) , (0, -1)]

input = sys.stdin.readline

def bfs(n, startI, startJ, graph):
    q = deque([(startI, startJ)])
    visit = [[False] * (n) for _ in range(n)]
    prev = None
    while q:

        node = q.popleft()

        if visit[node[0]][node[1]] == False:
            visit[node[0]][node[1]] = True

            for i in range(4):
                ni = node[0] + allow[i][0]
                nj = node[1] + allow[i][1]
                if 0 <= ni < n and 0 <= nj < n and visit[ni][nj] == False:
                    q.append((ni, nj))
                    graph[ni][nj] = graph[node[0]][node[1]] + 100
                    isP = False; isC = False
                    if prev:
                        if prev in allow[:2]:isP = True
                        if prev in allow[2:]:isP = False
                    if (allow[i][0], allow[i][1]) in allow[:2]: isC = True
                    if (allow[i][0], allow[i][1]) in allow[2:]: isC = False
                    if isP != isC:
                        graph[ni][nj] + 500
                    prev = (allow[i][0], allow[i][1])

graph = [
    [0, 0, 0],
    [0, 0, 0],
    [0, 0, 0]
]
bfs(3, 0, 0, graph)
print(graph)


"""
Download Tweets using Tweepy.

Usage:
  tweet_downloader.py [options]
  tweet_downloader.py -h | --help

Options:
  -n <num>            Download <n> tweets
  -o <filename>       Metadata tweets to file (is a list) with format:
                          "<filename>_metadata.byte".
  -h --help           Show this screen.
"""
import os
import sys
import tweepy
import pickle
from docopt import docopt

consumer_key = os.environ['SEARCH_CONSUMER_KEY']
consumer_secret = os.environ['SEARCH_CONSUMER_SECRET']
access_token = os.environ['SEARCH_ACCESS_TOKEN']
access_token_secret = os.environ['SEARCH_ACCESS_TOKEN_SECRET']

AUTH_DATA = [
    dict(consumer_key=consumer_key,
         consumer_secret=consumer_secret,
         access_token=access_token,
         access_token_secret=access_token_secret),
]

def progress(msg, width=None):
    """Ouput the progress of something on the same line."""
    if not width:
        width = len(msg)
    print('\b' * width + msg, end='')
    sys.stdout.flush()

if __name__ == '__main__':
    opts = docopt(__doc__)

    # Opciones
    metadata_filename = opts['-o']
    if not metadata_filename:
        metadata_filename = "output"

    max_tweets = opts['-n']
    if not max_tweets:
        max_tweets = 1
    else:
        max_tweets = int(max_tweets)

    # API
    cred = AUTH_DATA[0]

    auth = tweepy.OAuthHandler(cred['consumer_key'],
                               cred['consumer_secret'])
    auth.set_access_token(cred['access_token'],
                          cred['access_token_secret'])

    api = tweepy.API(auth_handler=auth,
                     wait_on_rate_limit=True,
                     wait_on_rate_limit_notify=True)

    # ACA CAMBIA EL STRING POR LAS PALABRAS QUE QUIERAS BUSCAR
    search_kw = "*"

    with open(metadata_filename, 'wb') as f:
        try:
            tweets_count = 0  # Contador de tweets
            tw_ids = set()  # Para evitar tweets repetidos

            places = api.geo_search(query="Argentina", granularity="country")
            place_id = places[0].id
            cursor = tweepy.Cursor(api.search, q=search_kw,
                                   place_id=place_id, lang='es', tweet_mode='extended')

            tweets = []
            for tweet in cursor.items():

                size = 100
                x = int((float(tweets_count)/max_tweets)*size)
                perc = round((float(tweets_count)/max_tweets)*100, 1)
                msg = ("Downloading tweets..." +
                       "{}% ({}/{})".format(perc, tweets_count, max_tweets) +
                       ' '*(len(str(max_tweets)) + 6 - (len(str(perc))+len(str(tweets_count)))) +
                       '[' + '#'*x + ' '*(size-x) + ']')
                progress(msg)

                if tweets_count == max_tweets:
                    print("")
                    break
                retweeted = hasattr(tweet, "retweeted_status")
                truncated = tweet.truncated
                extended = hasattr(tweet, "extended_tweet")
                if not (retweeted or tweet.id in tw_ids or
                        (truncated and not extended)):
                    tw_ids.add(tweet.id)
                    tweets.append(tweet)
                    tweets_count += 1
            pickle.dump(tweets, f)

        except Exception as e:
            print("### Warning: Error durante la descarga de tweets ###")
            raise e


import itertools

class Node:
    """Node Object.

    Store weight used as bias. Holds indecies of it's location in
    a genome.
    """

    innov_iter = itertools.count()
    registry = {}

    def __init__(self, layer_num, layer_ind, weight, type='hidden'):
        """Create new Node.

        :param layer_num: genome layer.
        :param layer_ind: Location in genome layer
        :param weight: Bias weight.
        :param type: 'input', 'output' or 'hidden'
        """
        innov = Node.registry.get((layer_num, layer_ind), None)
        innov = innov if innov is not None else next(Node.innov_iter)
        Node.registry[(layer_num, layer_ind)] = innov
        self.innov = innov
        self.layer_num = layer_num
        self.layer_ind = layer_ind
        self.weight = weight
        self.edges_out = []
        self.edges_in = []
        self.type = type

    @classmethod
    def copy(cls, node):
        """Deep copy of Node.

        Note the edges_out and edges_in are not copied. This is taken care of
        in the Edge initialization step itself.

        :param node: Node to be copied.
        :return: Copied Node.
        """
        return cls(
            node.layer_num,
            node.layer_ind,
            node.weight)

    @property
    def bias(self):
        return self.weight

    @property
    def to_reduced_repr(self):
        """Returns compact serializable data structure representing Node.

        :return: Tuple like: (layer_num, layer_ind, innov, weight, type)
        """
        return self.layer_num, self.layer_ind, self.innov, self.weight, self.type


import json
from flask import Blueprint, render_template, redirect, jsonify, request, flash
from .form import CaseForm, CaseEditForm, AddOrgsCase, RecurringForm
from flask_login import login_required, current_user
from . import case_core as CaseModel
from . import common_core as CommonModel
from . import task_core as TaskModel
from ..db_class.db import Task_Template, Case_Template
from ..decorators import editor_required
from ..utils.utils import form_to_dict, check_tag

case_blueprint = Blueprint(
    'case',
    __name__,
    template_folder='templates',
    static_folder='static'
)

from .task import task_blueprint
case_blueprint.register_blueprint(task_blueprint)

##########
# Render #
##########

@case_blueprint.route("/", methods=['GET', 'POST'])
@login_required
def index():
    """List all cases"""
    return render_template("case/case_index.html")

@case_blueprint.route("/create_case", methods=['GET', 'POST'])
@login_required
def create_case():
    """Create a case"""
    form = CaseForm()
    form.template_select.choices = [(template.id, template.title) for template in Case_Template.query.all()]
    form.template_select.choices.insert(0, (0," "))

    form.tasks_templates.choices = [(template.id, template.title) for template in Task_Template.query.all()]
    form.tasks_templates.choices.insert(0, (0," "))

    if form.validate_on_submit():
        tag_list = request.form.getlist("tags_select")
        cluster_list = request.form.getlist("clusters_select")
        if CommonModel.check_tag(tag_list):
            if CommonModel.check_cluster(cluster_list):
                form_dict = form_to_dict(form)
                form_dict["tags"] = tag_list
                form_dict["clusters"] = cluster_list
                case = CaseModel.create_case(form_dict, current_user)
                flash("Case created", "success")
                return redirect(f"/case/{case.id}")
            return render_template("case/create_case.html", form=form)
        return render_template("case/create_case.html", form=form)
    return render_template("case/create_case.html", form=form)

@case_blueprint.route("/<cid>", methods=['GET', 'POST'])
@login_required
def view(cid):
    """View a case"""
    case = CommonModel.get_case(cid)
    if case:
        present_in_case = CaseModel.get_present_in_case(cid, current_user)
        return render_template("case/case_view.html", id=cid, case=case.to_json(), present_in_case=present_in_case)
    return render_template("404.html")

@case_blueprint.route("/edit/<cid>", methods=['GET','POST'])
@login_required
@editor_required
def edit_case(cid):
    """Edit the case"""
    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            form = CaseEditForm()

            if form.validate_on_submit():
                tag_list = request.form.getlist("tags_select")
                cluster_list = request.form.getlist("clusters_select")
                if CommonModel.check_tag(tag_list):
                    if CommonModel.check_cluster(cluster_list):
                        form_dict = form_to_dict(form)
                        form_dict["tags"] = tag_list
                        form_dict["clusters"] = cluster_list
                        CaseModel.edit_case(form_dict, cid, current_user)
                        flash("Case edited", "success")
                        return redirect(f"/case/{cid}")
                    return render_template("case/edit_case.html", form=form)
                return render_template("case/edit_case.html", form=form)
            else:
                case_modif = CommonModel.get_case(cid)
                form.description.data = case_modif.description
                form.title.data = case_modif.title
                form.deadline_date.data = case_modif.deadline
                form.deadline_time.data = case_modif.deadline

            return render_template("case/edit_case.html", form=form)
        else:
            flash("Access denied", "error")
    else:
        return render_template("404.html")
    return redirect(f"/case/{id}")

@case_blueprint.route("/<cid>/add_orgs", methods=['GET', 'POST'])
@login_required
@editor_required
def add_orgs(cid):
    """Add orgs to the case"""

    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            form = AddOrgsCase()
            case_org = CommonModel.get_org_in_case_by_case_id(cid)
            org_list = list()
            for org in CommonModel.get_org_order_by_name():
                if case_org:
                    flag = False
                    for c_o in case_org:
                        if c_o.org_id == org.id:
                            flag = True
                    if not flag:
                        org_list.append((org.id, f"{org.name}"))
                else:
                    org_list.append((org.id, f"{org.name}"))

            form.org_id.choices = org_list
            form.case_id.data = cid

            if form.validate_on_submit():
                form_dict = form_to_dict(form)
                CaseModel.add_orgs_case(form_dict, cid, current_user)
                flash("Orgs added", "success")
                return redirect(f"/case/{cid}")

            return render_template("case/add_orgs.html", form=form)
        else:
            flash("Access denied", "error")
    else:
        return render_template("404.html")
    return redirect(f"/case/{cid}")

@case_blueprint.route("/<cid>/recurring", methods=['GET', 'POST'])
@login_required
@editor_required
def recurring(cid):
    """Recurring form"""

    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            form = RecurringForm()
            form.case_id.data = cid

            # List orgs and users in and verify if all users of an org are currently notify
            orgs_in_case = CommonModel.get_orgs_in_case(cid)
            orgs_to_return = list()
            for org in orgs_in_case:
                loc = org.to_json()
                loc["users"] = list()
                cp_checked_user = 0
                cp_users = 0
                for user in org.users:
                    cp_users += 1
                    loc_user = user.to_json()
                    if CommonModel.get_recu_notif_user(cid, user.id):
                        loc_user["checked"] = True
                        cp_checked_user += 1
                    else:
                        loc_user["checked"] = False
                    loc["users"].append(loc_user)
                # if all users in an org are notify, then check the org checkbox
                if cp_checked_user == cp_users:
                    loc["checked"] = True
                else:
                    loc["checked"] = False
                orgs_to_return.append(loc)

            if form.validate_on_submit():
                form_dict = form_to_dict(form)
                if not CaseModel.change_recurring(form_dict, cid, current_user):
                    flash("Recurring empty", "error")
                    return redirect(f"/case/{cid}/recurring")
                if not form_dict["remove"]:
                    CaseModel.notify_user_recurring(request.form.to_dict(), cid, orgs_in_case)
                flash("Recurring set", "success")
                return redirect(f"/case/{cid}")

            return render_template("case/case_recurring.html", form=form, orgs=orgs_to_return)

        flash("Action not allowed", "warning")
        return redirect(f"/case/{cid}")

    return render_template("404.html")

############
# Function #
#  Route   #
############

@case_blueprint.route("/get_cases_page", methods=['GET'])
@login_required
def get_cases():
    """Return all cases"""
    page = request.args.get('page', 1, type=int)
    tags = request.args.get('tags')
    taxonomies = request.args.get('taxonomies')
    or_and = request.args.get("or_and")

    cases = CaseModel.sort_by_status(page, tags, taxonomies, or_and, completed=False)
    role = CommonModel.get_role(current_user).to_json()

    loc = CaseModel.regroup_case_info(cases, current_user)
    return jsonify({"cases": loc["cases"], "role": role, "nb_pages": cases.pages}), 200

@case_blueprint.route("/search", methods=['GET'])
@login_required
def search():
    """Return cases matching search terms"""
    text_search = request.args.get("text")
    cases = CommonModel.search(text_search)
    if cases:
        return {"cases": [case.to_json() for case in cases]}, 200
    return {"message": "No case", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/delete", methods=['GET'])
@login_required
@editor_required
def delete(cid):
    """Delete the case"""

    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            if CaseModel.delete_case(cid, current_user):
                return {"message": "Case deleted", "toast_class": "success-subtle"}, 200
            else:
                return {"message": "Error case deleted", 'toast_class': "danger-subtle"}, 400
        return {"message": "Action not allowed", "toast_class": "warning-subtle"}, 401
    return {"message": "Case no found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/get_case_info", methods=['GET'])
@login_required
def get_case_info(cid):
    """Return all info of the case"""
    case = CommonModel.get_case(cid)
    if case:
        tasks = TaskModel.sort_by_status_task_core(case, current_user, completed=False)

        o_in_c = CommonModel.get_orgs_in_case(case.id)
        orgs_in_case = [o_c.to_json() for o_c in o_in_c]
        permission = CommonModel.get_role(current_user).to_json()
        present_in_case = CaseModel.get_present_in_case(cid, current_user)

        return jsonify({"case": case.to_json(), "tasks": tasks, "orgs_in_case": orgs_in_case, "permission": permission, "present_in_case": present_in_case, "current_user": current_user.to_json()}), 200
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/complete_case", methods=['GET'])
@login_required
@editor_required
def complete_case(cid):
    """Complete the case"""
    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            if CaseModel.complete_case(cid, current_user):
                flash("Case Completed")
                if request.args.get('revived', 1) == "true":
                    return {"message": "Case Revived", "toast_class": "success-subtle"}, 200
                return {"message": "Case completed", "toast_class": "success-subtle"}, 200
            else:
                if request.args.get('revived', 1) == "true":
                    return {"message": "Error case revived", 'toast_class': "danger-subtle"}, 400
                return {"message": "Error case completed", 'toast_class': "danger-subtle"}, 400
        return {"message": "Action not allowed", "toast_class": "warning-subtle"}, 401
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/remove_org/<oid>", methods=['GET'])
@login_required
@editor_required
def remove_org_case(cid, oid):
    """Remove an org to the case"""

    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            if CaseModel.remove_org_case(cid, oid, current_user):
                return {"message": "Org removed from case", "toast_class": "success-subtle"}, 200
            return {"message": "Error removing org from case", "toast_class": "danger-subtle"}, 400
        return {"message": "Action not allowed", "toast_class": "warning-subtle"}, 401
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/change_status", methods=['POST'])
@login_required
@editor_required
def change_status(cid):
    """Change the status of the case"""

    status = request.json["status"]
    case = CommonModel.get_case(cid)

    if CommonModel.get_case(cid):
        if CaseModel.get_present_in_case(cid, current_user) or current_user.is_admin():
            CaseModel.change_status_core(status, case, current_user)
            return {"message": "Status changed", "toast_class": "success-subtle"}, 200
        return {"message": "Action not allowed", "toast_class": "warning-subtle"}, 401
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/get_status", methods=['GET'])
@login_required
def get_status():
    """Get status"""

    status = CommonModel.get_all_status()
    status_list = list()
    for s in status:
        status_list.append(s.to_json())
    return jsonify({"status": status_list}), 200

@case_blueprint.route("/sort_by_ongoing", methods=['GET'])
@login_required
def sort_by_ongoing():
    """Sort Case by living one"""
    page = request.args.get('page', 1, type=int)
    tags = request.args.get('tags')
    taxonomies = request.args.get('taxonomies')
    or_and_taxo = request.args.get("or_and_taxo")

    galaxies = request.args.get('galaxies')
    clusters = request.args.get('clusters')
    or_and_galaxies = request.args.get("or_and_galaxies")

    cases_list = CaseModel.sort_by_status(page, taxonomies, galaxies, tags, clusters, or_and_taxo, or_and_galaxies, completed=False)
    return CaseModel.regroup_case_info(cases_list, current_user)

@case_blueprint.route("/sort_by_finished", methods=['GET'])
@login_required
def sort_by_finished():
    """Sort Case by finished one"""
    page = request.args.get('page', 1, type=int)
    tags = request.args.get('tags')
    taxonomies = request.args.get('taxonomies')
    or_and_taxo = request.args.get("or_and_taxo")

    galaxies = request.args.get('galaxies')
    clusters = request.args.get('clusters')
    or_and_galaxies = request.args.get("or_and_galaxies")

    cases_list = CaseModel.sort_by_status(page, taxonomies, galaxies, tags, clusters, or_and_taxo, or_and_galaxies, completed=True)
    return CaseModel.regroup_case_info(cases_list, current_user)

@case_blueprint.route("/ongoing", methods=['GET'])
@login_required
def ongoing_sort_by_filter():
    """Sort by filter for living case"""
    page = request.args.get('page', 1, type=int)
    filter = request.args.get('filter')
    tags = request.args.get('tags')
    taxonomies = request.args.get('taxonomies')
    or_and_taxo = request.args.get("or_and_taxo")

    galaxies = request.args.get('galaxies')
    clusters = request.args.get('clusters')
    or_and_galaxies = request.args.get("or_and_galaxies")

    if filter:
        cases_list, nb_pages = CaseModel.sort_by_filter(filter, page, taxonomies, galaxies, tags, clusters, or_and_taxo, or_and_galaxies, completed=False)
        return CaseModel.regroup_case_info(cases_list, current_user, nb_pages)
    return {"message": "No filter pass"}

@case_blueprint.route("/finished", methods=['GET'])
@login_required
def finished_sort_by_filter():
    """Sort by filter for finished task"""
    page = request.args.get('page', 1, type=int)
    filter = request.args.get('filter')
    tags = request.args.get('tags')
    taxonomies = request.args.get('taxonomies')
    or_and_taxo = request.args.get("or_and_taxo")

    galaxies = request.args.get('galaxies')
    clusters = request.args.get('clusters')
    or_and_galaxies = request.args.get("or_and_galaxies")

    if filter:
        cases_list, nb_pages = CaseModel.sort_by_filter(filter, page, taxonomies, galaxies, tags, clusters, or_and_taxo, or_and_galaxies, completed=True)
        return CaseModel.regroup_case_info(cases_list, current_user, nb_pages)
    return {"message": "No filter pass"}

@case_blueprint.route("/<cid>/get_all_users", methods=['GET'])
@login_required
def get_all_users(cid):
    """Get all user in case"""

    case = CommonModel.get_case(cid)
    if case:
        users_list = list()
        orgs = CommonModel.get_all_users_core(case)
        for org in orgs:
            for user in org.users:
                if not user == current_user:
                    users_list.append(user.to_json())
        return {"users_list": users_list}
    return {"message": "Case not found"}, 404

@case_blueprint.route("/<cid>/get_assigned_users/<tid>", methods=['GET'])
@login_required
def get_assigned_users(cid, tid):
    """Get assigned users to the task"""

    if CommonModel.get_case(cid):
        users, _ = TaskModel.get_users_assign_task(tid, current_user)
        return users
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/download", methods=['GET'])
@login_required
def download_case(cid):
    """Download a case"""

    case = CommonModel.get_case(cid)
    if case:
        task_list = list()
        for task in case.tasks:
            task_list.append(task.download())
        return_dict = case.download()
        return_dict["tasks"] = task_list
        return jsonify(return_dict), 200, {'Content-Disposition': f'attachment; filename=case_{case.title}.json'}
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/<cid>/fork", methods=['POST'])
@login_required
def fork_case(cid):
    """Assign current user to the task"""

    if CommonModel.get_case(cid):
        if "case_title_fork" in request.json:
            case_title_fork = request.json["case_title_fork"]

            new_case = CaseModel.fork_case_core(cid, case_title_fork, current_user)
            if type(new_case) == dict:
                return new_case
            return {"new_case_id": new_case.id}, 201
        return {"message": "'case_title_fork' is missing", 'toast_class': "danger-subtle"}, 400
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/get_all_case_title", methods=['GET'])
@login_required
def get_all_case_title():
    data_dict = dict(request.args)
    if CommonModel.get_case_by_title(data_dict["title"]):
        flag = True
    else:
        flag = False

    return {"title_already_exist": flag}

@case_blueprint.route("/<cid>/create_template", methods=['POST'])
@login_required
@editor_required
def create_template(cid):
    if CommonModel.get_case(cid):
        if "case_title_template" in request.json:
            case_title_template = request.json["case_title_template"]

            new_template = CaseModel.create_template_from_case(cid, case_title_template)
            if type(new_template) == dict:
                return new_template
            return {"template_id": new_template.id}, 201
        return {"message": "'case_title_template' is missing", 'toast_class': "danger-subtle"}, 400
    return {"message": "Case not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/get_all_case_template_title", methods=['GET'])
@login_required
def get_all_case_template_title():
    data_dict = dict(request.args)
    if CommonModel.get_case_template_by_title(data_dict["title"]):
        flag = True
    else:
        flag = False

    return {"title_already_exist": flag}

@case_blueprint.route("/history/<cid>", methods=['GET'])
@login_required
def history(cid):
    case = CommonModel.get_case(cid)
    if case:
        history = CommonModel.get_history(case.uuid)
        if history:
            return {"history": history}
        return {"history": None}
    return {"message": "Case Not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/get_taxonomies", methods=['GET'])
@login_required
def get_taxonomies():
    return {"taxonomies": CommonModel.get_taxonomies()}, 200

@case_blueprint.route("/get_tags", methods=['GET'])
@login_required
def get_tags():
    data_dict = dict(request.args)
    if "taxonomies" in data_dict:
        taxos = json.loads(data_dict["taxonomies"])
        return {"tags": CommonModel.get_tags(taxos)}, 200
    return {"message": "'taxonomies' is missing", 'toast_class': "warning-subtle"}, 400

@case_blueprint.route("/get_taxonomies_case/<cid>", methods=['GET'])
@login_required
def get_taxonomies_case(cid):
    case = CommonModel.get_case(cid)
    if case:
        tags = CommonModel.get_case_tags(case.id)
        taxonomies = []
        if tags:
            taxonomies = [tag.split(":")[0] for tag in tags]
        return {"tags": tags, "taxonomies": taxonomies}
    return {"message": "Case Not found", 'toast_class': "danger-subtle"}, 404

@case_blueprint.route("/get_galaxies", methods=['GET'])
@login_required
def get_galaxies():
    return {"galaxies": CommonModel.get_galaxies()}, 200

@case_blueprint.route("/get_clusters", methods=['GET'])
@login_required
def get_clusters():
    if "galaxies" in request.args:
        galaxies = request.args.get("galaxies")
        galaxies = json.loads(galaxies)
        return {"clusters": CommonModel.get_clusters_galaxy(galaxies)}, 200
    return {"message": "'galaxies' is missing", 'toast_class': "warning-subtle"}, 400

@case_blueprint.route("/get_galaxies_case/<cid>", methods=['GET'])
@login_required
def get_galaxies_case(cid):
    case = CommonModel.get_case(cid)
    if case:
        clusters = CommonModel.get_case_clusters(case.id)
        galaxies = []
        if clusters:
            for cluster in clusters:
                loc_g = CommonModel.get_galaxy(cluster.galaxy_id)
                if not loc_g.name in galaxies:
                    galaxies.append(loc_g.name)
                index = clusters.index(cluster)
                clusters[index] = cluster.tag
        return {"clusters": clusters, "galaxies": galaxies}
    return {"message": "Case Not found", 'toast_class': "danger-subtle"}, 404


'''
242. Valid Anagram
Given two strings s and t , write a function to determine if t is an anagram of s.
Example 1:
Input: s = "anagram", t = "nagaram"
Output: true
Example 2:
Input: s = "rat", t = "car"
Output: false
Note:
You may assume the string contains only lowercase alphabets.
'''
def anagram(s,t):
    s = s.replace(' ','').lower()
    t = t.replace(' ','').lower()
    return (sorted(s) == sorted(t))

print(anagram('rat','tar') )

def anagram_2(s,t):
    s = s.replace(' ','').lower()
    t = t.replace(' ','').lower()
    d = {}
    for char in s:
        if char not in d:
            d[char] =1
        else:
            d[char]+=1

    t = 'tar'
    for char in t:
        if char in d:
            d[char] -=1
        else:
            return False
    for char in d:
        if d[char] !=0:
            return False
    else:
        return True

print(anagram_2('rat','tar') )


# here we are using pytube module for the project
from ast import Delete
from pytube import YouTube
link = input("Enter the link of Youtube video")
youtube = YouTube(link)
print(youtube.title)
print(youtube.thumbnail_url)
cleaity = youtube.streams.all()
vid = list(enumerate(cleaity))
print("Press 1 for 1080")
print("Press 2 for 720")
print("Press 3 for 360")
print("Press 4 for 144")
dics = {
    1:1080,
    2:720,
    3:360,
    4:144
}
received = -1
user  = int(input())
for i in vid:
    if(int(i.resolution)==dics[user]):
        received= i
        break
if(received!=-1):
    cleaity[received].download()
    print("Succesfully donloaded")
else:
    print("Not Avilable")


# -*- coding: utf-8 -*-
"""
Created on Sun Nov 18 15:12:06 2018

@author: Administrator
"""

import pandas as pd
import numpy as np
from math import radians, atan, tan, sin, acos, cos
from sklearn.cluster import DBSCAN
from sklearn import metrics
from sklearn.datasets.samples_generator import make_blobs
from sklearn.preprocessing import StandardScaler

train = pd.read_csv('good_train.csv', low_memory=False)
test = pd.read_csv('good_test.csv', low_memory=False)

# 根据训练集 计算朴素贝叶斯算法需要使用的 条件概率
Probability = {}
## P(start_block|end_block)
name = 'start_block'
pname = 'P(start_block|end_block)'
print('calculating %s' % pname)
tmp_func = lambda g: (1.0 * g[name].value_counts()) / (len(g) + 10)
tmp = train.groupby('end_block').apply(tmp_func).reset_index()
tmp.columns = ['end_block', name, pname]
print(tmp.head())
Probability[pname] = tmp
## P(out_id|end_block)
name = 'out_id'
pname = 'P(out_id|end_block)'
print('calculating %s' % pname)
tmp_func = lambda g: (1.0 * g[name].value_counts()) / (len(g) + 10)
tmp = train.groupby('end_block').apply(tmp_func).reset_index()
tmp.columns = ['end_block', name, pname]
Probability[pname] = tmp
## P(is_holiday|end_block)
name = 'is_holiday'
pname = 'P(is_holiday|end_block)'
print('calculating %s' % pname)
tmp_func = lambda g: (1.0 * g[name].value_counts() + 3.) / (len(g) + 10)
tmp = train.groupby('end_block').apply(tmp_func).reset_index()
tmp.columns = ['end_block', name, pname]
Probability[pname] = tmp
## P((is_holiday, hour)|end_block)
pname = 'P((is_holiday, hour)|end_block)'
print('calculating %s' % pname)
tmp_func = lambda g: (5 + 1.0 * g.groupby(['is_holiday', 'hour']).size()) / (len(g))
tmp = train.groupby('end_block').apply(tmp_func).reset_index().rename(columns={0: pname})
print(tmp.head())
Probability[pname] = tmp
## P(day|end_block)
name = 'day'
pname = 'P(day|end_block)'
print('calculating %s' % pname)
tmp_func = lambda g: 1.0 * g[name].value_counts() / len(g)
tmp = train.groupby('end_block').apply(tmp_func).reset_index()
tmp.columns = ['end_block', name, pname]
Probability[pname] = tmp
## P(hour|end_block)
name = 'hour'
pname = 'P(hour|end_block)'
print('calculating %s' % pname)
tmp_func = lambda g: 1.0 * g[name].value_counts() / len(g)
tmp = train.groupby('end_block').apply(tmp_func).reset_index()
tmp.columns = ['end_block', name, pname]
Probability[pname] = tmp
# 根据训练集 计算先验概率
pname = 'P(end_block)'
print('calculating %s' % pname)
tmp = train.end_block.value_counts().reset_index()
tmp.columns = ['end_block', pname]
Probability[pname] = tmp
## 计算后验概率
## P(end_block|(start_block, out_id, is_holiday, hour)) = P(end_block) *
##                         P(start_block|end_block) * P(out_id|end_block) * P((is_holiday, hour)|end_block)
is_local = False  # 是否线下验证
if is_local:
    predict_info = train.copy()
    predict_info = predict_info.rename(columns={'end_block': 'true_end_block', 'end_lat': 'true_end_lat', 'end_lon': 'true_end_lon'})
else:
    predict_info = test.copy()
##
predict_info = predict_info.merge(Probability['P(out_id|end_block)'], on='out_id', how='left')
print(predict_info['P(out_id|end_block)'].isnull().sum())
predict_info['P(out_id|end_block)'] = predict_info['P(out_id|end_block)'].fillna(1e-5)
##
predict_info = predict_info.merge(Probability['P(is_holiday|end_block)'], on=['is_holiday', 'end_block'], how='left')
print(predict_info['P(is_holiday|end_block)'].isnull().sum())
predict_info['P(is_holiday|end_block)'] = predict_info['P(is_holiday|end_block)'].fillna(1e-4)
##
predict_info = predict_info.merge(Probability['P(day|end_block)'], on=['day', 'end_block'], how='left')
print(predict_info['P(day|end_block)'].min(), predict_info['P(day|end_block)'].isnull().sum())
predict_info['P(day|end_block)'] = predict_info['P(day|end_block)'].fillna(1e-4)
##
predict_info = predict_info.merge(Probability['P((is_holiday, hour)|end_block)'], on=['is_holiday', 'hour', 'end_block'], how='left')
print(predict_info['P((is_holiday, hour)|end_block)'].isnull().sum())
predict_info['P((is_holiday, hour)|end_block)'] = predict_info['P((is_holiday, hour)|end_block)'].fillna(1e-4)
##
predict_info = predict_info.merge(Probability['P(start_block|end_block)'], on=['start_block', 'end_block'], how='left')
print(predict_info['P(start_block|end_block)'].isnull().sum())
predict_info['P(start_block|end_block)'] = predict_info['P(start_block|end_block)'].fillna(1e-5)
##
predict_info = predict_info.merge(Probability['P(end_block)'], on='end_block', how='left')
print(predict_info['P(end_block)'].isnull().sum())
predict_info['P(end_block)'] = predict_info['P(end_block)'].fillna(1e-1)
predict_info['P(end_block|(start_block, out_id, is_holiday, hour))'] = predict_info['P((is_holiday, hour)|end_block)'] * \
                                                    predict_info['P(out_id|end_block)'] * \
                                                    predict_info['P(start_block|end_block)'] * \
                                                    predict_info['P(end_block)']
which_probability = 'P(end_block|(start_block, out_id, is_holiday, hour))'
# 生成每个聚类label的经纬度
block_lat_lon = train.groupby('end_block')[['end_lat', 'end_lon']].mean().reset_index()
#block_lat_lon = train.groupby('end_block')[['end_lat', 'end_lon']].agg(lambda x: np.mean(pd.Series.mode(x))).reset_index()
predict_info = predict_info.merge(block_lat_lon, on='end_block', how='left')
print(predict_info[['start_lat', 'start_lon', 'end_lat', 'end_lon']].describe())
predict_result = predict_info.groupby('r_key').apply(lambda g: g.loc[g[which_probability].idxmax(), :]).reset_index(drop=True)
if not is_local:
    output_result = test[['r_key', 'start_lat', 'start_lon']].merge(predict_result[['r_key', 'end_lat', 'end_lon']], on='r_key', how='left')
    print(output_result.end_lat.isnull().sum())
    # 冷启动暂时用其实经纬度作为预测结果
    nan_idx = output_result.end_lat.isnull()
    output_result.loc[nan_idx, 'end_lat'] = output_result['start_lat'][nan_idx]
    output_result.loc[nan_idx, 'end_lon'] = output_result['start_lon'][nan_idx]
    #output_result[['start_lat', 'end_lat', 'end_lon']].describe()
    print(output_result.head())
    print(output_result.info())
    output_result[['r_key', 'end_lat', 'end_lon']].to_csv('bayes4.csv', index=None)


def answer(l, t):

    broadcastList = l
    key = t
    messageLocation = []
    tempSum = 0
    endPosition = 0

    for i in range(len(broadcastList)):     # itterate through whole list
        if(i > 0):                          # removes checked start from the count
            tempSum -= broadcastList[i-1]
        for j in range(endPosition, len(broadcastList)):
            tempSum += broadcastList[j]
            if(tempSum > key):              # check next number is sum is to large
                tempSum -= broadcastList[j]
                endPosition = j
                break

            if(tempSum == key):             # return answer when found
              messageLocation = [i,j]
              return messageLocation

            if(j == len(broadcastList) -1): # no message is in this sequence
                messageLocation = [-1,-1]
                return messageLocation
            endPosition = j
    messageLocation = [-1,-1]               # no message is in this sequence
    return messageLocation

l = [1, 2, 3, 4]
t = 15
print (answer(l, t))
# answer(l,t) = [-1, -1]

l = [4, 3, 10, 2, 8]
t = 12
print (answer(l, t))
# answer(l,t) = [2, 3]

l = [4, 3, 5, 7, 8]
t = 12
print (answer(l, t))
# answer(l,t) = [0, 2]


from solcx import compile_standard
import json
from web3 import Web3
import os

#opening the file and storing it in a variable
with open("./sharedWallet.sol", "r") as file:
    shareWallet = file.read()

#compiling the opened file using solcx library
compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"sharedWallet.sol": {"content": shareWallet}},
        "settings": {
            "outputSelection": {
                "*": {
                    "*": ["abi", "metadata", "evm.bytecode", "evm.bytecode.sourceMap"]
                }
            }
        },
    },
    solc_version="0.8.0",
)

# storing the json output in a file
with open("compiled_Code.json", "w") as file:
    json.dump(compiled_sol, file)

# to get evm bytecode object
bytecode = compiled_sol["contracts"]["sharedWallet.sol"]["SharedWallet"]["evm"]["bytecode"]["object"]

#to get abi array
abi = compiled_sol["contracts"]["sharedWallet.sol"]["SharedWallet"]["abi"]

# connecting to ganache blockchain provider
connection_url = "HTTP://127.0.0.1:7545"
network_id = "5777"
account_address = "0x8ebAfd70A543755407E5E9d48496C123f21b8AB5"
private_key = os.environ.get('PRIVATE_KEY')

w3 = Web3(Web3.HTTPProvider(connection_url))

#getting the nonce value
nonce = w3.eth.get_transaction_count(account_address)

# creating contract object
contract_obj = w3.eth.contract(abi= abi, bytecode= bytecode)

# 1. Build a Transaction
# 2. sign a Transaction
# 3. send a Transaction

#buildig a Transaction
transaction_obj = contract_obj.constructor().build_transaction({
    "gasPrice": w3.eth.gas_price,"chainId": w3.eth.chain_id,"from":account_address,"nonce":nonce})

# signing a raw Transaction
signed_transaction = w3.eth.account.sign_transaction(transaction_obj,private_key= private_key)

# sending a transaction
tran_hash = w3.eth.send_raw_transaction(signed_transaction.rawTransaction)
# print("deploying contract...")

# wait for transaction to be mined
mined_hash = w3.eth.wait_for_transaction_receipt(tran_hash)
# print("contract Deployed !")

# interacting with a contractS
# 1. address of the contract
# 2. the abi of the contract

shareWallet = w3.eth.contract(address=mined_hash.contractAddress,abi= abi)


"""Provide tests for utils."""

# Authors: Federico Raimondo <f.raimondo@fz-juelich.de>
#          Synchon Mandal <s.mandal@fz-juelich.de>
# License: AGPL

from typing import Dict, Iterable, List, Tuple, Union

import numpy as np
import pytest
from numpy.testing import assert_array_equal

from junifer.storage.utils import (
    element_to_prefix,
    get_dependency_version,
    matrix_to_vector,
    process_meta,
    store_matrix_checks,
)

@pytest.mark.parametrize(
    "dependency, max_version",
    [
        ("click", "8.2"),
        ("numpy", "1.26"),
        ("datalad", "0.19"),
        ("pandas", "1.6"),
        ("nibabel", "4.1"),
        ("nilearn", "0.10.0"),
        ("sqlalchemy", "1.5.0"),
        ("ruamel.yaml", "0.18.0"),
    ],
)
def test_get_dependency_version(dependency: str, max_version: str) -> None:
    """Test dependency resolution for installed dependencies.

    Parameters
    ----------
    dependency : str
        The parametrized dependency name.
    max_version : str
        The parametrized maximum version of the dependency.

    """
    version = get_dependency_version(dependency)
    if len(version.split(".")) == 3:  # semver
        assert int(version.split(".")[1]) <= int(max_version.split(".")[1])
    else:
        assert version < max_version

def test_get_dependency_version_invalid() -> None:
    """Test invalid package name handling for dependency resolution."""
    with pytest.raises(ValueError, match="Could not obtain"):
        get_dependency_version("foobar")

def test_process_meta_invalid_metadata_type() -> None:
    """Test invalid metadata type check for metadata hash processing."""
    meta = None
    with pytest.raises(ValueError, match=r"`meta` must be a dict"):
        process_meta(meta)  # type: ignore

# TODO: parameterize
def test_process_meta_hash() -> None:
    """Test metadata hash processing."""
    meta = {
        "element": {"foo": "bar"},
        "A": 1,
        "B": [2, 3, 4, 5, 6],
        "dependencies": ["numpy"],
        "marker": {"name": "fc"},
        "type": "BOLD",
    }
    hash1, _, element1 = process_meta(meta)
    assert element1 == {"foo": "bar"}

    meta = {
        "element": {"foo": "baz"},
        "B": [2, 3, 4, 5, 6],
        "A": 1,
        "dependencies": ["numpy"],
        "marker": {"name": "fc"},
        "type": "BOLD",
    }
    hash2, _, element2 = process_meta(meta)
    assert hash1 == hash2
    assert element2 == {"foo": "baz"}

    meta = {
        "element": {"foo": "bar"},
        "A": 1,
        "B": [2, 3, 1, 5, 6],
        "dependencies": ["numpy"],
        "marker": {"name": "fc"},
        "type": "BOLD",
    }
    hash3, _, element3 = process_meta(meta)
    assert hash1 != hash3
    assert element3 == element1

    meta4 = {
        "element": {"foo": "bar"},
        "B": {
            "B2": [2, 3, 4, 5, 6],
            "B1": [9.22, 3.14, 1.41, 5.67, 6.28],
            "B3": (1, "car"),
        },
        "A": 1,
        "dependencies": ["numpy"],
        "marker": {"name": "fc"},
        "type": "BOLD",
    }

    meta5 = {
        "A": 1,
        "B": {
            "B3": (1, "car"),
            "B1": [9.22, 3.14, 1.41, 5.67, 6.28],
            "B2": [2, 3, 4, 5, 6],
        },
        "element": {"foo": "baz"},
        "dependencies": ["numpy"],
        "marker": {"name": "fc"},
        "type": "BOLD",
    }

    hash4, _, _ = process_meta(meta4)
    hash5, _, _ = process_meta(meta5)
    assert hash4 == hash5

    # Different element keys should give a different hash
    meta6 = {
        "A": 1,
        "B": {
            "B3": (1, "car"),
            "B1": [9.22, 3.14, 1.41, 5.67, 6.28],
            "B2": [2, 3, 4, 5, 6],
        },
        "element": {"bar": "baz"},
        "dependencies": ["numpy"],
        "marker": {"name": "fc"},
        "type": "BOLD",
    }
    hash6, _, _ = process_meta(meta6)
    assert hash4 != hash6

def test_process_meta_invalid_metadata_key() -> None:
    """Test invalid metadata key check for metadata hash processing."""
    meta = {}
    with pytest.raises(ValueError, match=r"element"):
        process_meta(meta)

    meta = {"element": {}}
    with pytest.raises(ValueError, match=r"marker"):
        process_meta(meta)

    meta = {"element": {}, "marker": {}}
    with pytest.raises(ValueError, match=r"key 'name'"):
        process_meta(meta)

    meta = {"element": {}, "marker": {"name": "test"}}
    with pytest.raises(ValueError, match=r"key 'type'"):
        process_meta(meta)

    meta = {"element": {}, "marker": {"name": "test"}, "type": "BOLD"}
    with pytest.raises(ValueError, match=r"dependencies"):
        process_meta(meta)

@pytest.mark.parametrize(
    "meta,elements",
    [
        (
            {
                "element": {"foo": "bar"},
                "A": 1,
                "B": [2, 3, 4, 5, 6],
                "dependencies": ["numpy"],
                "marker": {"name": "fc"},
                "type": "BOLD",
            },
            ["foo"],
        ),
        (
            {
                "element": {"subject": "foo", "session": "bar"},
                "B": [2, 3, 4, 5, 6],
                "A": 1,
                "dependencies": ["numpy"],
                "marker": {"name": "fc"},
                "type": "BOLD",
            },
            ["subject", "session"],
        ),
    ],
)
def test_process_meta_element(meta: Dict, elements: List[str]) -> None:
    """Test metadata element after processing.

    Parameters
    ----------
    meta : dict
        The parametrized metadata dictionary.
    elements : list of str
        The parametrized elements to assert against.

    """
    hash1, processed_meta, _ = process_meta(meta)
    assert "_element_keys" in processed_meta
    assert processed_meta["_element_keys"] == elements
    assert "A" in processed_meta
    assert "B" in processed_meta
    assert "element" not in processed_meta
    assert isinstance(processed_meta["dependencies"], Dict)
    assert all(
        x in processed_meta["dependencies"] for x in meta["dependencies"]
    )
    assert "name" in processed_meta
    assert processed_meta["name"] == f"{meta['type']}_{meta['marker']['name']}"

@pytest.mark.parametrize(
    "element,prefix",
    [
        ({"subject": "sub-01"}, "element_sub-01_"),
        ({"subject": 1}, "element_1_"),
        ({"subject": "sub-01", "session": "ses-02"}, "element_sub-01_ses-02_"),
        ({"subject": 1, "session": 2}, "element_1_2_"),
    ],
)
def test_element_to_prefix(element: Dict, prefix: str) -> None:
    """Test converting element to prefix (for file naming).

    Parameters
    ----------
    element : str, int, dict or tuple
        The parameterized element.
    prefix : str
        The parametrized prefix to assert against.

    """
    prefix_generated = element_to_prefix(element)
    assert prefix_generated == prefix

def test_element_to_prefix_invalid_type() -> None:
    """Test element to prefix type checking."""
    element = 2.3
    with pytest.raises(ValueError, match=r"must be a dict"):
        element_to_prefix(element)  # type: ignore

@pytest.mark.parametrize(
    "params, err_msg",
    [
        (
            {
                "matrix_kind": "half",
                "diagonal": True,
                "data_shape": (1, 1),
                "row_names_len": 1,
                "col_names_len": 1,
            },
            "Invalid kind",
        ),
        (
            {
                "matrix_kind": "full",
                "diagonal": False,
                "data_shape": (1, 1),
                "row_names_len": 1,
                "col_names_len": 1,
            },
            "Diagonal cannot",
        ),
        (
            {
                "matrix_kind": "triu",
                "diagonal": False,
                "data_shape": (2, 1),
                "row_names_len": 2,
                "col_names_len": 1,
            },
            "Cannot store a non-square",
        ),
        (
            {
                "matrix_kind": "tril",
                "diagonal": False,
                "data_shape": (1, 2),
                "row_names_len": 1,
                "col_names_len": 2,
            },
            "Cannot store a non-square",
        ),
        (
            {
                "matrix_kind": "full",
                "diagonal": True,
                "data_shape": (2, 2),
                "row_names_len": 1,
                "col_names_len": 2,
            },
            "Number of row names",
        ),
        (
            {
                "matrix_kind": "full",
                "diagonal": True,
                "data_shape": (2, 2),
                "row_names_len": 2,
                "col_names_len": 1,
            },
            "Number of column names",
        ),
    ],
)
def test_store_matrix_checks(
    params: Dict[str, Union[str, bool, Tuple[int, int], int]], err_msg: str
) -> None:
    """Test matrix storing parameter checks.

    Parameters
    ----------
    params : dict
        The parametrized parameters for the function.
    err_msg : str
        The parametrized substring of expected error message.

    """
    with pytest.raises(ValueError, match=f"{err_msg}"):
        store_matrix_checks(**params)  # type: ignore

@pytest.mark.parametrize(
    "params, expected_data, expected_columns",
    [
        (
            {
                "data": np.arange(9).reshape(3, 3),
                "col_names": ["c0", "c1", "c2"],
                "row_names": ("r0", "r1", "r2"),
                "matrix_kind": "triu",
                "diagonal": True,
            },
            np.array([0, 1, 2, 4, 5, 8]),
            ["r0~c0", "r0~c1", "r0~c2", "r1~c1", "r1~c2", "r2~c2"],
        ),
        (
            {
                "data": np.arange(9).reshape(3, 3),
                "col_names": ("c0", "c1", "c2"),
                "row_names": ["r0", "r1", "r2"],
                "matrix_kind": "triu",
                "diagonal": False,
            },
            np.array([1, 2, 5]),
            ["r0~c1", "r0~c2", "r1~c2"],
        ),
        (
            {
                "data": np.arange(9).reshape(3, 3),
                "col_names": ("c0", "c1", "c2"),
                "row_names": ["r0", "r1", "r2"],
                "matrix_kind": "tril",
                "diagonal": True,
            },
            np.array([0, 3, 4, 6, 7, 8]),
            ["r0~c0", "r1~c0", "r1~c1", "r2~c0", "r2~c1", "r2~c2"],
        ),
        (
            {
                "data": np.arange(9).reshape(3, 3),
                "col_names": ("c0", "c1", "c2"),
                "row_names": ["r0", "r1", "r2"],
                "matrix_kind": "tril",
                "diagonal": False,
            },
            np.array([3, 6, 7]),
            ["r1~c0", "r2~c0", "r2~c1"],
        ),
        (
            {
                "data": np.arange(9).reshape(3, 3),
                "col_names": ("c0", "c1", "c2"),
                "row_names": ["r0", "r1", "r2"],
                "matrix_kind": "full",
                "diagonal": False,
            },
            np.arange(9),
            [
                f"{r}~{c}"
                for r in ["r0", "r1", "r2"]
                for c in ["c0", "c1", "c2"]
            ],
        ),
    ],
)
def test_matrix_to_vector(
    params: Dict[str, Union[np.ndarray, Iterable[str], str, bool]],
    expected_data: np.ndarray,
    expected_columns: List[str],
) -> None:
    """Test matrix to vector.

    Parameters
    ----------
    params : dict
        The parametrized parameters for the function.
    expected_data : np.ndarray
        The parametrized vector data to expect.
    expected_columns : np.ndarray
        The parametrized columns labels to expect.

    """
    data, columns = matrix_to_vector(**params)  # type: ignore
    assert_array_equal(data, expected_data)
    assert columns == expected_columns


from turbogears import (controllers, identity, expose, validate, validators,
                        redirect, flash)

from turboaffiliate import model

class Account(controllers.Controller):
    """Controller for Accounts in Affiliate Program"""

    @identity.require(identity.not_anonymous())
    @expose(template="turboaffiliate.templates.account.index")
    def index(self):
        return dict(accounts=model.Account.select())

    @identity.require(identity.not_anonymous())
    #@expose(template="turboaffiliate.templates.account.account")
    @expose("json")
    @validate(validators=dict(code=validators.Int()))
    def default(self, code):
        account = model.Account.get(code)
        return dict(account=account)

    @identity.require(identity.not_anonymous())
    @expose(template="turboaffiliate.templates.account.add")
    def add(self):
        return dict()

    @identity.require(identity.All(identity.in_any_group('admin', 'operarios'),
                                   identity.not_anonymous()))
    @expose()
    @validate(validators=dict(name=validators.String()))
    def save(self, **kw):
        account = model.Account(**kw)
        flash(u"La cuenta ha sido grabada")

        log = dict()
        raise redirect('/account/{0}'.format(account.id))

    @identity.require(identity.All(identity.in_any_group('admin', 'operarios'),
                                   identity.not_anonymous()))
    @expose(template="turboaffiliate.templates.account.retrasada")
    def retrasada(self):
        return dict(accounts=model.Account.select())

    @identity.require(identity.All(identity.in_any_group('admin', 'operarios'),
                                   identity.not_anonymous()))
    @expose()
    @validate(validators=dict(mes=validators.Int(), anio=validators.Int(),
                              account=validators.Int()))
    def agregarRetrasada(self, account, **kw):
        account = model.Account.get(account)
        kw['account'] = account
        retrasada = model.CuentaRetrasada(**kw)
        retrasada.account = account

        flash(u"La cuenta para restradas ha sido grabada")
        raise redirect('/account/retrasada')

    @identity.require(identity.All(identity.in_any_group('admin', 'operarios'),
                                   identity.not_anonymous()))
    @expose()
    @validate(validators=dict(account=validators.Int(), amount=validators.Number(),
                              name=validators.String()))
    def distribution(self, account, **kwargs):

        kwargs['account'] = model.Account.get(account)
        distribucion = model.Distribution(**kwargs)

        flash(u"La distribucion ha sido grabada")

        redirect('/account/{0}'.format(kwargs['account'].id))


'''
* 유형
    연결 리스트, 구현

* 체감 난이도
    ***

* 풀이
    1. 처음에 리스트로 단순하게 풀었는데 당연히 효율성 테스트에서 막힘.
        O(N) 이 걸리는 insert, pop 하는 과정이 포함되다보니 오래 걸림.
    2. 리스트를 딕셔너리로 바꿔서 풀려고 했지만 로직 구성을 못했음.
    3. 스택과 이중 연결 리스트 이용해서 풀려고 했지만 로직 구성에 실패.

    해답은 이중 연결 리스트로 푸는 것이 맞는데
    중요한 건
        1. 스택에 삭제한 행을 push 할 때 노드 통째로 넣어줘야함.
        2. 링크드 리스트의 노드를 실제로 삭제하지 않아야 함.
        3. 현재 선택된 행을 정확하게 지정해야 함.

    노드의 링크 조작만 제대로 할 수 있으면 풀 수 있음.
    그리고 스택이기 때문에 되돌리기는 순서대로 수행되어 링크가 꼬일 일은 발생하지 않는다!!

'''

def solution(n, k, cmd):
    table = {i: [i - 1, i + 1] for i in range(1, n + 1)}
    current = k + 1
    stack = []
    result = ['O'] * n

    for c in cmd:
        if c[0] == 'D' or c[0] == 'U':
            direc = 1 if c[0] == 'D' else 0
            dist = int(c[2:])
            for i in range(dist):
                current = table[current][direc]
        elif c[0] == 'C':
            result[current - 1] = 'X'
            front, back = table[current]
            stack.append((front, back, current))
            current = table[current][0] if back == n + 1 else table[current][1]

            if front == 0:
                table[current][0] = front
            elif back == n + 1:
                table[current][1] = back
            else:
                table[front][1] = back
                table[back][0] = front

        elif c[0] == 'Z':
            front, back, saved = stack.pop()
            result[saved - 1] = 'O'
            if front == 0:
                table[back][0] = saved
            elif back == n + 1:
                table[front][1] = saved
            else:
                table[front][1] = saved
                table[back][0] = saved

    return ''.join(result)