import os
import json
import requests
from tqdm import tqdm
from slugify import slugify
from urllib.parse import urlparse

def get_moltin_access_token(client_secret, client_id):
    response = requests.post(
        'https://api.moltin.com/oauth/access_token',
        data={
            'client_id': client_id,
            'client_secret': client_secret,
            'grant_type': 'client_credentials'
        }
    )
    response.raise_for_status()
    moltin_token = response.json()
    return moltin_token['access_token'], moltin_token['expires']

def execute_get_request(url, headers={}, data={}):
    response = requests.get(url, headers=headers, data=data)
    response.raise_for_status()
    return response.json()['data']

def get_item_id(access_token, item_type, **kwargs):
    urls = {
        'products': 'https://api.moltin.com/v2/products',
        'customers': 'https://api.moltin.com/v2/customers',
        'flows': 'https://api.moltin.com/v2/flows',
        'fields': 'https://api.moltin.com/v2/flows/%s/fields',
        'entries': 'https://api.moltin.com/v2/flows/%s/entries'
    }
    found_items = execute_get_request(
        urls[item_type] % kwargs['slug'] if kwargs.get('slug') else urls[item_type],
        {'Authorization': access_token}
    )
    found_item = [item['id'] for item in found_items if item[kwargs['field']] == kwargs['value']]
    return found_item[0] if found_item else None

def get_products(access_token, offset=0, limit_products_per_page=0):
    response = requests.get(
        'https://api.moltin.com/v2/products?page[limit]=%s&page[offset]=%s' % (limit_products_per_page, offset),
        headers={'Authorization': access_token}
    )

    response.raise_for_status()
    products = response.json()
    return (
        products['data'],
        products['meta']['page']['total'],
        products['meta']['page']['current']
    )

def add_new_product(access_token, product_characteristic):
    response = requests.post(
        f'https://api.moltin.com/v2/products',
        headers={'Authorization': access_token, 'Content-Type': 'application/json'},
        json={'data': product_characteristic}
    )
    response.raise_for_status()
    return response.json()['data']['id']

def update_product(access_token, product_id, product_characteristic):
    product_characteristic['id'] = product_id
    response = requests.put(
        f'https://api.moltin.com/v2/products/{product_id}',
        headers={'Authorization': access_token, 'Content-Type': 'application/json'},
        json={'data': product_characteristic}
    )
    response.raise_for_status()

def load_file(access_token, product_id, image_file):
    response = requests.post(
        f'https://api.moltin.com/v2/files',
        headers={'Authorization': access_token},
        files={'file': open(image_file, 'rb'), 'public': True}
    )
    response.raise_for_status()
    add_product_image(access_token, product_id, response.json()['data']['id'])

def get_quantity_product_in_stock(access_token, product_id):
    product_data = execute_get_request(
        f'https://api.moltin.com/v2/inventories/{product_id}',
        headers={'Authorization': access_token}
    )
    return product_data['total']

def get_product_image(access_token, product_data):
    image_id = product_data['relationships']['main_image']['data']['id']
    product_data = execute_get_request(
        f'https://api.moltin.com/v2/files/{image_id}',
        headers={'Authorization': access_token}
    )
    return product_data['link']['href']

def add_product_image(access_token, product_id, image_id):
    response = requests.post(
        f'https://api.moltin.com/v2/products/{product_id}/relationships/main-image',
        headers={'Authorization': access_token, 'Content-Type': 'application/json'},
        json={'data': {'type': 'main_image', 'id': image_id}}
    )
    response.raise_for_status()

def get_product_info(access_token, product_id):
    product_data = execute_get_request(
        f'https://api.moltin.com/v2/products/{product_id}',
        headers={'Authorization': access_token}
    )
    product_image = get_product_image(access_token, product_data)
    name, description, currency, amount = (
        product_data['name'],
        product_data['description'],
        product_data['price'][0]['currency'],
        product_data['price'][0]['amount']
    )
    return (
        f'{name}\n\nстоимость: {amount} {currency}\n\n{description}',
        product_image
    )

def put_into_cart(access_token, cart_id, prod_id, quantity=1):
    response = requests.post(
        f'https://api.moltin.com/v2/carts/{cart_id}/items',
        headers={'Authorization': access_token, 'Content-Type': 'application/json'},
        json={'data': {'id': prod_id, 'type': 'cart_item', 'quantity': quantity}}
    )
    response.raise_for_status()

def delete_from_cart(access_token, cart_id, prod_id):
    response = requests.delete(
        f'https://api.moltin.com/v2/carts/{cart_id}/items/{prod_id}',
        headers={'Authorization': access_token}
    )
    response.raise_for_status()

def delete_the_cart(access_token, cart_id):
    response = requests.delete(
        f'https://api.moltin.com/v2/carts/{cart_id}',
        headers={'Authorization': access_token}
    )
    response.raise_for_status()

def get_cart_items(access_token, cart_id):
    return execute_get_request(
        f'https://api.moltin.com/v2/carts/{cart_id}/items',
        headers={'Authorization': access_token}
    )

def get_cart_info(access_token, cart_id):
    cart_info = []
    for cart_item in get_cart_items(access_token, cart_id):
        name, description, quantity, amount = (
            cart_item['name'],
            cart_item['description'],
            cart_item['quantity'],
            cart_item['meta']['display_price']['with_tax']['value']['formatted']
        )
        cart_info.append(f'{name}\n{description}\n{quantity} шт. на сумму: {amount}')
    cart_info.append(get_cart_amount(access_token, cart_id))
    return '\n\n'.join(cart_info)

def get_quantity_product_in_cart(access_token, cart_id, product_id):
    quantity_in_cart = [cart_item['quantity'] for cart_item in get_cart_items(access_token, cart_id) if cart_item['id'] == product_id]
    return quantity_in_cart[0] if quantity_in_cart else 0

def get_cart_amount(access_token, cart_id):
    cart_price = execute_get_request(
        f'https://api.moltin.com/v2/carts/{cart_id}',
        headers={'Authorization': access_token}
    )
    return 'Всего к оплате: %s' % cart_price['meta']['display_price']['with_tax']['formatted']

def get_payment_info(access_token, cart_id):
    cart_info = []
    for cart_item in get_cart_items(access_token, cart_id):
        name, quantity, amount = (
            cart_item['name'],
            cart_item['quantity'],
            cart_item['meta']['display_price']['with_tax']['value']['formatted']
        )
        cart_info.append(f'{name} - {quantity} шт. на сумму: {amount}')
    cart_description = '\n'.join(cart_info)
    cart_price = execute_get_request(
        f'https://api.moltin.com/v2/carts/{cart_id}',
        headers={'Authorization': access_token}
    )
    return (
        cart_description,
        cart_price['meta']['display_price']['with_tax']['currency'],
        cart_price['meta']['display_price']['with_tax']['amount']
    )

def add_new_customer(access_token, email):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {'data': {'type': 'customer', 'name': email.split('@')[0], 'email': email}}
    response = requests.post(
        'https://api.moltin.com/v2/customers',
        headers=headers,
        json=data
    )
    response.raise_for_status()

def add_new_flow(access_token, flow_name, flow_slug, flow_description):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'type': 'flow',
            'name': flow_name,
            'slug': flow_slug,
            'description': flow_description,
            'enabled': True
        }
    }
    response = requests.post(
        'https://api.moltin.com/v2/flows',
        headers=headers,
        json=data
    )
    response.raise_for_status()
    return response.json()['data']['id']

def update_flow(access_token, flow_id, flow_name, flow_slug, flow_description):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'id': flow_id,
            'type': 'flow',
            'name': flow_name,
            'slug': flow_slug,
            'description': flow_description,
            'enabled': True
        }
    }
    response = requests.post(
        f'https://api.moltin.com/v2/flows/{flow_id}',
        headers=headers,
        json=data
    )
    response.raise_for_status()

def add_new_field(access_token, flow_id, field_characteristics):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'type': 'field',
            'name': field_characteristics['name'],
            'slug': field_characteristics['slug'],
            'description': field_characteristics['description'],
            'field_type': field_characteristics['type'],
            'enabled': True,
            'required': False,
            'relationships': {
                'flow': {
                    'data': {
                        'type': 'flow',
                        'id': flow_id
                    }
                }
            }
        }
    }
    response = requests.post(
        'https://api.moltin.com/v2/fields',
        headers=headers,
        json=data
    )
    response.raise_for_status()
    return response.json()['data']['id']

def add_new_entry(access_token, flow_slug, fields):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'type': 'entry'
        }
    }
    data['data'].update(fields)
    response = requests.post(
        f'https://api.moltin.com/v2/flows/{flow_slug}/entries',
        headers=headers,
        json=data
    )
    response.raise_for_status()
    return response.json()['data']['id']

def update_entry(access_token, flow_slug, entry_id, fields):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'type': 'entry'
        }
    }
    data['data'].update(fields)
    response = requests.put(
        f'https://api.moltin.com/v2/flows/{flow_slug}/entries/{entry_id}',
        headers=headers,
        json=data
    )
    response.raise_for_status()

def get_pizzeria_entries(access_token):
    url = f'https://api.moltin.com/v2/flows/pizzeria/entries'
    entries = execute_get_request(
        url,
        {'Authorization': access_token}
    )
    return [{'address': entry['address'], 'longitude': entry['longitude'], 'latitude': entry['latitude']} for entry in entries]

def get_entry(access_token, flow_slug, entry_id):
    url = f'https://api.moltin.com/v2/flows/{flow_slug}/entries/{entry_id}'
    return execute_get_request(
        url,
        {'Authorization': access_token}
    )

def get_customer(access_token, field, value):
    return get_item_id(access_token, 'customers', field=field, value=value)

def get_address(access_token, slug, field, value):
    entry_id = get_item_id(access_token, 'entries', slug=slug, field=field, value=value)
    if entry_id:
        return get_entry(access_token, slug, entry_id)

def read_models_from_file(access_token, file_name):
    models = []
    with open(file_name, 'r') as file_handler:
        models_catalog = json.load(file_handler)

    for model in models_catalog:
        model_ids = {'flow_id': '', 'flow_slug': '', 'fields': {}}
        flow_id = get_item_id(
            access_token, 'flows', field='name',
            value=model['flow']['name']
        )
        if not flow_id:
            flow_id = add_new_flow(
                access_token,
                model['flow']['name'],
                model['flow']['slug'],
                model['flow']['description']
            )
        if flow_id:
            model_ids['flow_id'], model_ids['flow_slug'] = flow_id, model['flow']['slug']
        else:
            models.append(model_ids)
            continue
        for field in model['fields']:
            field_id = get_item_id(
                access_token,
                'fields',
                slug=model['flow']['slug'],
                field='slug',
                value=field['slug']
            )
            if field_id:
                model_ids['fields'][field['name']] = field_id
                continue
            model_ids['fields'][field['name']] = add_new_field(access_token, flow_id, field)
        models.append(model_ids)

    return models

def load_image(access_token, product_id, image_folder, image_url):
    url_path = urlparse(image_url).path
    image_file = url_path.split('/')[-1]

    response = requests.get(image_url)
    response.raise_for_status()

    image_path = os.path.join(image_folder, image_file)
    with open(image_path, 'wb') as file_handler:
        file_handler.write(response.content)
    load_file(access_token, product_id, image_path)

def load_products_from_file(access_token, filename, image_folder):

    with open(filename, 'r') as file_handler:
        products = json.load(file_handler)

    for product in tqdm(products, desc="Загружено", unit="наименований"):
        product_characteristic = {
            'type': 'product',
            'name': product['name'],
            'slug': slugify(product['name']),
            'sku': str(product['id']),
            'description': product['description'],
            'manage_stock': False,
            'price': [
                {
                    'amount': product['price'],
                    'currency': 'RUB',
                    'includes_tax': True
                }
            ],
            'status': 'live',
            'commodity_type': 'physical'
        }
        product_id = get_item_id(
            access_token, 'products',
            field='sku', value=str(product['id'])
        )
        if product_id:
            update_product(access_token, product_id, product_characteristic)
        else:
            product_id = add_new_product(access_token, product_characteristic)
        if product['product_image']['url']:
            load_image(access_token, product_id, image_folder, product['product_image']['url'])

def load_addresses_from_file(access_token, filename, pizzeria_model):

    with open(filename, 'r') as file_handler:
        addresses = json.load(file_handler)

    for address in tqdm(addresses, desc="Загружено", unit="адресов"):
        save_address(
            access_token,
            pizzeria_model['flow_slug'],
            'address',
            address['address']['full'],
            address={
                'address': address['address']['full'],
                'alias': address['alias'],
                'longitude': address['coordinates']['lon'],
                'latitude': address['coordinates']['lat']
            }
        )

def save_address(access_token, slug, field, value, address):
    entry_id = get_item_id(access_token, 'entries', slug=slug, field=field, value=value)
    if entry_id:
        update_entry(access_token, slug, entry_id, address)
    else:
        add_new_entry(access_token, slug, address)

def create_order(access_token, chat_id):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    customer_address = get_address(access_token, 'customeraddress', 'customerid', str(chat_id))
    customer_id = get_customer(access_token, 'email', customer_address['email'])
    customer_info = execute_get_request(
        f'https://api.moltin.com/v2/customers/{customer_id}',
        {'Authorization': access_token}
    )
    data = {
        'data': {
            'customer': {
                'id': customer_id
            },
            'billing_address': {
                'first_name': customer_info['name'],
                'last_name': customer_info['name'],
                'line_1': customer_address['address'],
                'city': customer_address['city'],
                'postcode': '0000',
                'county': customer_address['county'],
                'country': customer_address['country']
            },
            'shipping_address': {
                'first_name': customer_info['name'],
                'last_name': customer_info['name'],
                'phone_number': customer_address['telephone'],
                'line_1': customer_address['address'],
                'postcode': '0000',
                'county': customer_address['county'],
                'country': customer_address['country']
            }
        }
    }
    response = requests.post(
        f'https://api.moltin.com/v2/carts/{chat_id}/checkout',
        headers=headers,
        json=data
    )
    response.raise_for_status()
    return response.json()['data']['id']

def set_order_payment(access_token, order_id):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'gateway': 'manual',
            'method': 'authorize'
        }
    }
    response = requests.post(
        f'https://api.moltin.com/v2/orders/{order_id}/payments',
        headers=headers,
        json=data
    )
    response.raise_for_status()
    return response.json()['data']['id']

def confirm_order_payment(access_token, order_id, transaction_id):
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'gateway': 'manual',
            'method': 'capture'
        }
    }
    response = requests.post(
        f'https://api.moltin.com/v2/orders/{order_id}/transactions/{transaction_id}/capture',
        headers=headers,
        json=data
    )
    response.raise_for_status()

def confirm_order_shipping(access_token, order_id):
    if not order_id:
        return
    headers = {'Authorization': access_token, 'Content-Type': 'application/json'}
    data = {
        'data': {
            'type': 'order',
            'shipping': 'fulfilled'
        }
    }
    response = requests.put(
        f'https://api.moltin.com/v2/orders/{order_id}',
        headers=headers,
        json=data
    )
    response.raise_for_status()


# s : 주어진 문자열
# 문자열보다 앞 위치에서 가장 가까운 같은 글자가 어디 있는지 찾아서 배열에 저장

def solution(s):
    answer = [] # ananab
    s_list = [ch for ch in s]
    s_list.reverse()

    for i in range(len(s_list)): # a n a n a b
        current_word = s_list[i]
        value = -1
        if i == len(s_list):
            answer.append(value)
            break
        for j in range(i+1, len(s_list)):
            if s_list[j] == current_word:
                value = j-i
                break
        answer.append(value)

    answer.reverse()
    return answer

print(solution("foobar"))

가장가까운같은글자_Lv1.py


from numpy import *
from numpy import linalg as la

def loadExData():
    return[[1, 1, 1, 0, 0],
            [2, 2, 2, 0, 0],
            [1, 1, 1, 0, 0],
            [5, 5, 5, 0, 0],
            [1, 1, 0, 2, 2],
            [0, 0, 0, 3, 3],
            [0, 0, 0, 1, 1]]

def loadExData3():
    return[[4, 4, 0, 2, 2],
            [4, 0, 0, 3, 3],
            [4, 0, 0, 1, 1],
            [1, 1, 1, 2, 0],
            [2, 2, 2, 0, 0],
            [1, 1, 1, 0, 0],
            [5, 5, 5, 0, 0]]

def loadExData2():
    return[[0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 5],
           [0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 3],
           [0, 0, 0, 0, 4, 0, 0, 1, 0, 4, 0],
           [3, 3, 4, 0, 0, 0, 0, 2, 2, 0, 0],
           [5, 4, 5, 0, 0, 0, 0, 5, 5, 0, 0],
           [0, 0, 0, 0, 5, 0, 1, 0, 0, 5, 0],
           [4, 3, 4, 0, 0, 0, 0, 5, 5, 0, 1],
           [0, 0, 0, 4, 0, 4, 0, 0, 0, 0, 4],
           [0, 0, 0, 2, 0, 2, 5, 0, 0, 1, 2],
           [0, 0, 0, 0, 5, 0, 0, 0, 0, 4, 0],
           [1, 0, 0, 0, 0, 0, 0, 1, 2, 0, 0]]

def ecludSim(inA,inB):
    return 1.0/(1.0 + la.norm(inA - inB))

def pearsSim(inA,inB):
    if len(inA) < 3 : return 1.0
    return 0.5+0.5*corrcoef(inA, inB, rowvar = 0)[0][1]

def cosSim(inA,inB):
    num = float(inA.T*inB)
    denom = la.norm(inA)*la.norm(inB)
    return 0.5+0.5*(num/denom)

#计算在给定相似度计算方法的条件下，用户对物品的估计评分值
#standEst()函数中：参数dataMat表示数据矩阵，user表示用户编号，simMeas表示相似度计算方法，item表示物品编号
def standEst(dataMat,user,simMeas,item):
    n=shape(dataMat)[1] #shape用于求矩阵的行列
    simTotal=0.0; ratSimTotal=0.0
    for j in range(n):
        userRating=dataMat[user,j]
        if userRating==0:continue #若某个物品评分值为0，表示用户未对物品评分，则跳过，继续遍历下一个物品
        #寻找两个用户都评分的物品
        overLap=nonzero(logical_and(dataMat[:,item].A>0,dataMat[:,j].A>0))[0]

        if len(overLap)==0:similarity=0
        else: similarity=simMeas(dataMat[overLap,item],dataMat[overLap,j])

        #print'the %d and %d similarity is: %f' %(item,j,similarity)
        #根据评分来计算相似度，乘以userrating是为了扩大相似度，增加差异
        simTotal+=similarity
        ratSimTotal+=similarity*userRating
    if simTotal==0: return 0
    else: return ratSimTotal/simTotal9

def recommend(dataMat,user,N=3,simMeas=cosSim,estMethod=standEst):
    #寻找未评级的物品
    #返回第user行等于0的列下标
    unratedItems = nonzero(dataMat[user,:].A==0)[1]
    if len(unratedItems) == 0: return 'you rated everything'
    itemScores = []
    for item in unratedItems:
        estimatedScore=estMethod(dataMat,user,simMeas,item)#对每一个未评分物品，调用standEst()来产生该物品的预测得分
        itemScores.append((item,estimatedScore))#该物品的编号和估计得分值放入一个元素列表itemScores中
    #对itemScores进行从大到小排序，返回前N个未评分物品  reverse=True降序 reverse=False升序
    return sorted(itemScores,key=lambda jj:jj[1],reverse=True)[:N]

if __name__ == '__main__':
    myMat = mat(loadExData2())
    print(recommend(myMat, 3, estMethod=svdEst))


from methods.CryptoMethod import CryptoMethod

class CaesarMethod(CryptoMethod):

    def __init__(self):
        self.__lang = CryptoMethod.DEFAULT_LANGUAGE

    def encrypt(self, text: str, key: str):
        result: str = ''
        for char in text:
            ind = self.__lang.index(char)
            ind += self.__lang.index(key)
            ind %= len(self.__lang)
            result += self.__lang[ind]

        return result

    def decrypt(self, text: str, key: str):
        result: str = ''
        for char in text:
            ind = self.__lang.index(char)
            ind -= self.__lang.index(key)
            ind %= len(self.__lang)
            result += self.__lang[ind]

        return result

    def setLanguage(self, language: str):
        self.__lang = language


from __future__ import absolute_import

from zope.interface.verify import verifyObject

from twisted.internet.task import Clock
from twisted.python.filepath import FilePath

from ..service import VolumeService, Volume, DEFAULT_CONFIG_PATH, VolumeName
from ..filesystems.zfs import Snapshot
from ..filesystems.memory import FilesystemStoragePool
from .._ipc import (
    IRemoteVolumeManager, RemoteVolumeManager, LocalVolumeManager,
    standard_node, SSH_PRIVATE_KEY_PATH)
from ..testtools import ServicePair
from ...common import FakeNode
from ...common._ipc import ProcessNode
from ...testtools import AsyncTestCase, TestCase

MY_VOLUME = VolumeName(namespace=u"myns", dataset_id=u"myvol")
MY_VOLUME2 = VolumeName(namespace=u"myns", dataset_id=u"myvol2")

def make_iremote_volume_manager(fixture):
    """
    Create a TestCase for ``IRemoteVolumeManager``.

    :param fixture: A fixture that returns a :class:`ServicePair` instance.
    """
    class IRemoteVolumeManagerTests(AsyncTestCase):
        """
        Tests for ``IRemoteVolumeManager`` implementations.
        """
        def test_interface(self):
            """
            The tested object provides :class:`IRemoteVolumeManager`.
            """
            service_pair = fixture(self)
            self.assertTrue(verifyObject(IRemoteVolumeManager,
                                         service_pair.remote))

        def test_snapshots_no_filesystem(self):
            """
            If the filesystem does not exist on the remote manager, an empty
            list of snapshots is returned.
            """
            service_pair = fixture(self)
            creating = service_pair.from_service.create(
                service_pair.from_service.get(MY_VOLUME)
            )

            def created(volume):
                return service_pair.remote.snapshots(volume)
            getting_snapshots = creating.addCallback(created)

            def got_snapshots(snapshots):
                self.assertEqual([], snapshots)
            getting_snapshots.addCallback(got_snapshots)
            return getting_snapshots

        def test_receive_exceptions_pass_through(self):
            """
            Exceptions raised in the ``receive()`` context manager are not
            swallowed.
            """
            service_pair = fixture(self)
            created = service_pair.from_service.create(
                service_pair.from_service.get(MY_VOLUME)
            )

            def got_volume(volume):
                with service_pair.remote.receive(volume):
                    raise RuntimeError()
            created.addCallback(got_volume)
            return self.assertFailure(created, RuntimeError)

        def test_receive_creates_volume(self):
            """
            ``receive`` creates a volume.
            """
            service_pair = fixture(self)
            created = service_pair.from_service.create(
                service_pair.from_service.get(MY_VOLUME)
            )

            def do_push(volume):
                with volume.get_filesystem().reader() as reader:
                    with service_pair.remote.receive(volume) as receiver:
                        receiver.write(reader.read())
            created.addCallback(do_push)

            def pushed(_):
                to_volume = Volume(node_id=service_pair.from_service.node_id,
                                   name=MY_VOLUME,
                                   service=service_pair.to_service)
                d = service_pair.to_service.enumerate()

                def got_volumes(volumes):
                    self.assertIn(to_volume, list(volumes))
                d.addCallback(got_volumes)
                return d
            created.addCallback(pushed)

            return created

        def test_creates_files(self):
            """``receive`` recreates files pushed from origin."""
            service_pair = fixture(self)
            created = service_pair.from_service.create(
                service_pair.from_service.get(MY_VOLUME)
            )

            def do_push(volume):
                root = volume.get_filesystem().get_path()
                root.child(b"afile.txt").setContent(b"WORKS!")

                with volume.get_filesystem().reader() as reader:
                    with service_pair.remote.receive(volume) as receiver:
                        receiver.write(reader.read())
            created.addCallback(do_push)

            def pushed(_):
                to_volume = Volume(node_id=service_pair.from_service.node_id,
                                   name=MY_VOLUME,
                                   service=service_pair.to_service)
                root = to_volume.get_filesystem().get_path()
                self.assertEqual(root.child(b"afile.txt").getContent(),
                                 b"WORKS!")
            created.addCallback(pushed)

            return created

        def remotely_owned_volume(self, service_pair):
            """
            Create a volume ``MY_VOLUME`` on the origin service and a copy
            that is pushed to the destination service.

            :param ServicePair service_pair: The service pair.

            :return: The ``Volume`` instance on the origin service.
            """
            created = service_pair.from_service.create(
                service_pair.from_service.get(MY_VOLUME)
            )

            def got_volume(volume):
                pushing = service_pair.from_service.push(
                    volume, service_pair.remote)
                pushing.addCallback(lambda ignored: volume)
                return pushing
            created.addCallback(got_volume)
            return created

        def test_acquire_changes_node_id(self):
            """
            ``acquire()`` changes the node ID of the given volume on the
            receiving side to the volume manager's.
            """
            service_pair = fixture(self)
            to_service = service_pair.to_service
            created = self.remotely_owned_volume(service_pair)

            def got_volume(pushed_volume):
                service_pair.remote.acquire(pushed_volume)
                d = to_service.enumerate()
                d.addCallback(lambda results: self.assertEqual(
                    list(results),
                    [Volume(node_id=to_service.node_id,
                            name=pushed_volume.name,
                            service=to_service)]))
                return d
            created.addCallback(got_volume)
            return created

        def test_acquire_preserves_data(self):
            """
            ``acquire()`` preserves the data from the acquired volume in the
            renamed volume.
            """
            service_pair = fixture(self)
            to_service = service_pair.to_service
            created = self.remotely_owned_volume(service_pair)

            def got_volume(pushed_volume):
                root = pushed_volume.get_filesystem().get_path()
                root.child(b"test").setContent(b"some data")
                # Re-push with updated contents:
                pushing = service_pair.from_service.push(
                    pushed_volume, service_pair.remote)

                def pushed(ignored):
                    service_pair.remote.acquire(pushed_volume)

                    filesystem = Volume(node_id=to_service.node_id,
                                        name=pushed_volume.name,
                                        service=to_service).get_filesystem()
                    new_root = filesystem.get_path()
                    self.assertEqual(new_root.child(b"test").getContent(),
                                     b"some data")
                pushing.addCallback(pushed)
                return pushing

            created.addCallback(got_volume)
            return created

        def test_acquire_returns_node_id(self):
            """
            ``acquire()`` returns the node ID of the remote volume manager.
            """
            service_pair = fixture(self)
            to_service = service_pair.to_service
            created = self.remotely_owned_volume(service_pair)

            def got_volume(pushed_volume):
                result = service_pair.remote.acquire(pushed_volume)
                self.assertEqual(result, to_service.node_id)
            created.addCallback(got_volume)
            return created

        def test_clone_to(self):
            """
            ``clone_to()`` clones a volume.
            """
            service_pair = fixture(self)
            service = service_pair.to_service

            d = service.create(service.get(MY_VOLUME))

            def created(parent):
                parent.get_filesystem().get_path().child(b"f").setContent(
                    b"ORIG")
                return service_pair.remote.clone_to(parent, MY_VOLUME2)
            d.addCallback(created)

            def cloned(_):
                child = service.get(MY_VOLUME2)
                parent = service.get(MY_VOLUME)
                child_test_file = child.get_filesystem().get_path().child(b"f")
                parent_test_file = parent.get_filesystem().get_path().child(
                    b"f")
                values = [parent_test_file.getContent(),
                          child_test_file.getContent()]
                child_test_file.setContent(b"CHANGED")
                values.extend([parent_test_file.getContent(),
                               child_test_file.getContent()])
                self.assertEqual(values,
                                 [b"ORIG", b"ORIG", b"ORIG", b"CHANGED"])
            d.addCallback(cloned)
            return d

    return IRemoteVolumeManagerTests

def create_local_servicepair(test):
    """
    Create a ``ServicePair`` allowing testing of ``LocalVolumeManager``.

    :param TestCase test: A unit test.

    :return: A new ``ServicePair``.
    """
    def create_service():
        path = FilePath(test.mktemp())
        path.createDirectory()
        pool = FilesystemStoragePool(path)
        service = VolumeService(FilePath(test.mktemp()), pool, reactor=Clock())
        service.startService()
        test.addCleanup(service.stopService)
        return service

    to_service = create_service()
    from_service = create_service()
    remote = LocalVolumeManager(to_service)
    return ServicePair(
        from_service=from_service,
        to_service=to_service,
        remote=remote,
        origin_remote=remote
    )

class LocalVolumeManagerInterfaceTests(
        make_iremote_volume_manager(create_local_servicepair)):
    """
    Tests for ``LocalVolumeManager`` as a ``IRemoteVolumeManager``.
    """
    def test_snapshots(self):
        """
        ``LocalVolumeManager.snapshots`` returns a ``Deferred`` that fires with
        ``[]`` because ``DirectoryFilesystem`` does not support snapshots.
        """
        pair = create_local_servicepair(self)
        volume = self.successResultOf(pair.from_service.create(
            pair.from_service.get(MY_VOLUME)
        ))
        self.assertEqual(
            [], self.successResultOf(pair.remote.snapshots(volume)))

class RemoteVolumeManagerTests(TestCase):
    """
    Tests for ``RemoteVolumeManager``.
    """
    def setUp(self):
        super(RemoteVolumeManagerTests, self).setUp()
        self.pool = FilesystemStoragePool(FilePath(self.mktemp()))
        self.service = VolumeService(
            FilePath(self.mktemp()), self.pool, reactor=Clock())
        self.service.startService()
        self.volume = self.successResultOf(self.service.create(
            self.service.get(MY_VOLUME)
        ))

    def test_snapshots_destination_run(self):
        """
        ``RemoteVolumeManager.snapshots`` calls ``flocker-volume`` remotely
        with the ``snapshots`` sub-command.
        """
        node = FakeNode([b"abc\ndef\n"])

        remote = RemoteVolumeManager(node, FilePath(b"/path/to/json"))
        snapshots = self.successResultOf(remote.snapshots(self.volume))
        self.assertEqual(node.remote_command,
                         [b"flocker-volume", b"--config", b"/path/to/json",
                          b"snapshots", self.volume.node_id.encode("ascii"),
                          b"myns.myvol"])
        self.assertEqual(
            [Snapshot(name="abc"), Snapshot(name="def")], snapshots)

    def test_receive_destination_run(self):
        """
        Receiving calls ``flocker-volume`` remotely with ``receive`` command.
        """
        node = FakeNode()

        remote = RemoteVolumeManager(node, FilePath(b"/path/to/json"))
        with remote.receive(self.volume):
            pass
        self.assertEqual(node.remote_command,
                         [b"flocker-volume", b"--config", b"/path/to/json",
                          b"receive", self.volume.node_id.encode("ascii"),
                          b"myns.myvol"])

    def test_receive_default_config(self):
        """
        ``RemoteVolumeManager`` by default calls ``flocker-volume`` with
        default config path.
        """
        node = FakeNode()

        remote = RemoteVolumeManager(node)
        with remote.receive(self.volume):
            pass
        self.assertEqual(node.remote_command,
                         [b"flocker-volume", b"--config",
                          DEFAULT_CONFIG_PATH.path,
                          b"receive", self.volume.node_id.encode("ascii"),
                          b"myns.myvol"])

    def test_acquire_destination_run(self):
        """
        ``RemoteVolumeManager.acquire()`` calls ``flocker-volume`` remotely
        with ``acquire`` command.
        """
        node = FakeNode([b"remoteuuid"])

        remote = RemoteVolumeManager(node, FilePath(b"/path/to/json"))
        remote.acquire(self.volume)

        self.assertEqual(node.remote_command,
                         [b"flocker-volume", b"--config", b"/path/to/json",
                          b"acquire", self.volume.node_id.encode("ascii"),
                          b"myns.myvol"])

class StandardNodeTests(TestCase):
    """
    Tests for ``standard_node``.
    """
    def test_ssh_as_root(self):
        """
        ``standard_node`` returns a node that will SSH as root to port 22
        using the private key for the cluster.
        """
        node = standard_node(b'example.com')
        self.assertEqual(node, ProcessNode.using_ssh(
            b'example.com', 22, b'root', SSH_PRIVATE_KEY_PATH))


def verificar(nascimento):
    from datetime import date

    ano = date.today().year
    idade = ano - nascimento
    if idade <= 15:
        msg = 'NÃO VOTA'
    elif idade <= 17:
        msg = 'VOTO OPICIONAL'
    elif idade <= 65:
        msg = 'VOTO OBRIGATORIO'
    else:
        msg = 'VOTO OPICIONAL'
    return f'com {idade} anos: {msg}'

print(verificar(int(input('Em que ano você nasceu? '))))


from django.shortcuts import render
from django.http import HttpResponseRedirect
import django
from django.conf import settings
from django.core.mail import send_mail
from django.urls import reverse
from .models import Post, Settings_common, Send_message
from .forms import PostForm,SettingsForm, Send_messageForm
from django.db.models import Q
from django.contrib.auth.decorators import login_required
from mobile.models import Mobil

@login_required
def index(request,mobil_id,message_id):
    message_send = Post.objects.filter(owner=request.user).get(id=message_id)
    mobil_send = Mobil.objects.filter(owner=request.user).get(id=mobil_id)
    set_1 = Settings_common.objects.filter(owner=request.user).first()
    c= Send_message(send_message_start = set_1.message_send_start,send_message_finish = set_1.message_send_finish,
                    send_message_text = message_send.text_message,send_message_email = mobil_send.email_client,
                    send_message_number_tel = mobil_send.number_tel,send_message_sticker = mobil_send.number_sticker,
                    send_message_price = mobil_send.price,owner = request.user)
    if request.method != 'POST':
        b = c
        form = Send_messageForm(instance=c)
    else:
        c.save()
        form = Send_messageForm(instance=c, data=request.POST)
        if form.is_valid():
            form.save()
        if c.send_message_email:
            if c.send_message_email != '*@gmail.com':
                send_mail('service',c.send_message_text,"Jurij", [mobil_send.email_client])
        return HttpResponseRedirect(reverse('send_email:send_messages_all'))

    context={'b':b,'mobil_id': mobil_id, 'message_id': message_id,'form':form}
    return render(request, 'send_email/index.html',context)

@login_required
def success(request):
    email = request.POST.get('email', '')
    f=open('send_email/letter.txt','r')
 #   data = """
#Hello!
#Первое сообщение из моей программы.

#    """
    data=f.read()
    send_mail('Welcome!', data, "Yasoob",
              [email], fail_silently=False)
    f.close()
    return render(request, 'send_email/success.html')

@login_required
def settings_common(request):
    set_1 = Settings_common.objects.filter(owner=request.user).first()
    if set_1:
        set_info = Settings_common.objects.filter(owner=request.user).get(id=set_1.id)
        if request.method != 'POST':
            form = SettingsForm(instance=set_info)
        else:
            form = SettingsForm(instance=set_info, data=request.POST)
            if form.is_valid():
                form.save()
                return HttpResponseRedirect(reverse('users:individual'))
        context = {'form': form, 'set_info': set_info}
        return render(request, 'send_email/settings_common.html', context)
    else:
        if request.method != 'POST':
            form = SettingsForm()
        else:
            form = SettingsForm(request.POST)
            if form.is_valid():
                settings = form.save(commit=False)
                settings.owner = request.user
                settings.save()
                return HttpResponseRedirect(reverse('users:individual'))
        context = {'form': form}
        return render(request, 'send_email/settings_common.html', context)

@login_required
def messages_new_record(request):
    if request.method != 'POST':
        form = PostForm()
    else:
        form = PostForm(request.POST)
        if form.is_valid():
            message_new = form.save(commit=False)
            message_new.owner = request.user
            message_new.save()
            return HttpResponseRedirect(reverse('send_email:messages'))
    context = {'form': form}
    return render(request, 'send_email/messages_new_record.html', context)

@login_required
def messages(request):
    messages = Post.objects.filter(owner=request.user).order_by('post_message','text_message')
    context = {'messages': messages}
    return render(request, 'send_email/messages.html', context)

@login_required
def messages_mobil(request,mobil_id):
    messages = Post.objects.filter(owner=request.user).order_by('post_message','text_message')
    context = {'messages': messages,'mobil_id':mobil_id}
    print('messages_mobil')
    print(mobil_id)
    return render(request, 'send_email/messages.html', context)

@login_required
def messages_edit(request,message_id):
    message = Post.objects.filter(owner=request.user).get(id=message_id)
    if request.method != 'POST':
        form = PostForm(instance=message)
    else:
        form = PostForm(instance=message, data=request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(reverse('send_email:messages'))
    context = {'form': form, 'message': message}
    return render(request, 'send_email/messages_edit.html', context)

@login_required
def messages_delete(request, message_id):
    message = Post.objects.filter(owner=request.user).get(id=message_id)
    if request.method != 'POST':
        form = PostForm(instance=message)
    else:
        Post.objects.filter(id=message_id).delete()
        return HttpResponseRedirect(reverse('send_email:messages'))
    context = {'form': form, 'message': message}
    return render(request, 'send_email/messages_delete.html', context)

@login_required
def messages_search(request):
    query = request.GET.get('q')
    if query:
        eto_s = Post.objects.filter(owner=request.user).order_by('post_message','text_message')
        object_list = eto_s.filter(
            Q(post_message__icontains=query) | Q(text_message__icontains=query))
        context = {'object_list': object_list}
    else:
        context = {'object_list': []}
    return render(request, 'send_email/messages_search.html', context)

@login_required
def send_messages_all(request):
    send_messages_all = Send_message.objects.filter(owner=request.user).order_by('-id')
    context = {'send_messages_all': send_messages_all}
    return render(request, 'send_email/send_messages_all.html', context)

@login_required
def send_messages_all_delete(request,message_id):
    Send_message.objects.filter(id=message_id).delete()
    return HttpResponseRedirect(reverse('send_email:send_messages_all'))

@login_required
def send_messages_all_search(request):
    query = request.GET.get('q')
    if query:
        eto_s = Send_message.objects.filter(owner=request.user).order_by('-id')
        object_list = eto_s.filter(
            Q(send_message_email__icontains=query) | Q(send_message_number_tel__icontains=query))
        context = {'object_list': object_list}
    else:
        context = {'object_list': []}
    return render(request, 'send_email/send_messages_all_search.html', context)


import tensorflow as tf
from PIL import Image
import cv2
from FaceRecognition import Facenet
import os
import numpy as np
#---------------------------------------------------#
#   对输入图像进行resize
#---------------------------------------------------#
def letterbox_image(image, size):
    ih, iw, _   = np.shape(image)
    w, h        = size
    scale       = min(w/iw, h/ih)
    nw          = int(iw*scale)
    nh          = int(ih*scale)

    image       = cv2.resize(image, (nw, nh))
    new_image   = np.ones([size[1], size[0], 3],np.uint8) * 255
    new_image[(h-nh)//2:nh+(h-nh)//2, (w-nw)//2:nw+(w-nw)//2] = image
    return new_image

if __name__ == "__main__":
    model = Facenet(facenet_threhold=12)

    exit
    totalImg = os.listdir("./img")
    for i in range(len(totalImg)):

        # image_1 = input('Input image_1 filename:')
        image_path = "img/"+totalImg[i]
        try:
            image_1 = Image.open(image_path).convert('RGB')
        except:
            print('Image_1 Open Error! Try again!')
            continue

        # image_2 = input('Input image_2 filename:')
        # try:
        #     image_2 = Image.open(image_2)
        # except:
        #     print('Image_2 Open Error! Try again!')
        #     continue
        img_raw = cv2.imread(image_path)
        # img_raw = cv2.resize(img_raw, (640, 640))
        img_raw = letterbox_image(img_raw, [640, 640])
        img = cv2.cvtColor(img_raw, cv2.COLOR_BGR2RGB)

        r_image = model.detect_image(img)
        r_image = cv2.cvtColor(r_image, cv2.COLOR_RGB2BGR)
        cv2.imshow("after", r_image)
        cv2.waitKey(0)
        # print(probability)


def main():

    continue_playing = True

    while ______:
        user1 = _____("Player 1: What's your name?")
        user2 = _____("Player 2: What's your name?")
        user1_answer = _____(f"{_____}, do yo want to choose rock, paper or scissors?")
        user2_answer = _____(f"{_____}, do you want to choose rock, paper or scissors?")

        if user1_answer == user2_answer:
            solution = "It's a tie!"
        elif user1_answer == 'rock':
            if ___________ == 'scissors':
                solution = "Rock wins!"
            else:
                solution = "___________"
        elif __________ == 'scissors':
            if user2_answer == '________':
                solution = "Scissors win!"
            else:
                ________ = "Rock wins!"
        elif _________ == 'paper':
            if user2_answer == 'rock':
                solution = "Paper wins!"
            else:
                solution = "Scissors win!"
        else:
            solution = "Invalid input! You have not entered rock, paper or scissors, try again."

        print(________)

        keep_playing = input("Do you want to continue playing? (Y/N)")

        if ________:
            continue_playing = True
        else:
            continue_playing = False

if __name__ == "__main__":
    main()


import pandas as pd
import matplotlib.pyplot as plt
from math import sqrt
import random

def combineCrossValFiles(path, result_files,test_sets,test_is):
    i = 0
    xy = 0
    df_res_list = []
    for filename in result_files:
        test_sets[i]["reward"].plot()
        file = open(path + filename, 'r')
        raw_rew = file.read().replace('\nEpisode reward ', ',')
        res = []
        for l in raw_rew.split('\n'):
            x = l.split(",")
            res.append([int(x[0]), float(x[1])])

        df_res = pd.DataFrame(res, columns=["ex_nr", "reward"])
        df_res["costs"] = df_res['reward'].apply(invers_sqrt)
        df_res["nr"] = test_is[i]
        # print(df_res.describe())

        # df_res["costs"].plot()
        df_res["reward"].plot()
        # df_res.plot.scatter(x='nr', y='reward', c='r')
        # plt.scatter(df_res['nr'], df_res['reward'], c='r')
        print(df_res.where(df_res['reward'] <= -0.35).dropna())
        plt.ylim([-0.55, 0])  # 1e13
        plt.ylabel(str(i))
        plt.show()
        df_res.set_index("nr")
        df_res_list.append(df_res)
        '''
        if xy == 0:
            i += -1
            xy = 1
        else:
            xy = 0
        '''
        i += 1

    res = pd.concat(df_res_list)
    del res['ex_nr']

    res = res.drop_duplicates(subset=['nr'], keep='last')
    res.sort_values(by=['nr'], inplace=True, ascending=False)
    res.reset_index(inplace=True)
    return res

#df = pd.read_csv('res_left_deep.txt',sep='|')
#df_rd = pd.read_csv('res_right_deep.txt',sep='|')
df = pd.read_csv('DP/res_left_deep_l2_new.txt',sep='|')
df_rd = pd.read_csv('DP/res_right_deep_l2_new.txt',sep='|')
df_psql_style = pd.read_csv('res_psql_style_left_deep.txt',sep='|')
numofjoins = lambda x: len(x.split('('))
#print()
cost = { 'max':1.e+13, 'min':1.e+6}
sqt = lambda y : ((sqrt(y-cost['min']))/(sqrt(cost['max']-cost['min']))*-10) # SQRT
invers_sqrt  = lambda y : ((y/10*(sqrt(cost['max']-cost['min'])))**2+cost['min'])

#df['numofjoins']=df['ldeepquery'].apply(numofjoins) # -> old
df['numofjoins']=df['resquery'].apply(numofjoins)
df['reward']=df['costs'].apply(sqt)

df_rd['reward']=df_rd['costs'].apply(sqt)
df_psql_style['reward']=df_psql_style['costs'].apply(sqt)
print(df.describe())

#dfkl = df
#dfkl.sort_values(by=['numofjoins'], inplace=True,ascending=False)
#dfkl['query'].to_csv("job_queries_simple_sorted_desc.txt",sep="|",index=False)
print(df.groupby(['numofjoins']).count()['nr'])
#df.sort_values(by=['numofjoins'], inplace=True,ascending=False)

random.seed(7400)
test_is=[]
test_sets = []
rand_ord = random.sample(range(0, len(df)), 112)
pointer = 0
print(len(df))
for i in range(0,4):
    test_i=[]
    for j in range(0,33):
        if pointer+1<len(rand_ord):
            pointer+=1
        else:
            pointer = 0
        test_i.append(rand_ord[pointer])
    test = df.iloc[test_i]
    test.reset_index(inplace=True)
    test_sets.append(test)
    test_is.append(test_i)

#print(len(test_is))
#print(len(set(test_is)))

path = "results/CrossVal/DQN/"
result_files = ['0_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_12-14.txt',
                '1_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_13-01.txt',
                '2_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_14-29.txt',
                '3_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_15-37.txt']
dqn = combineCrossValFiles(path,result_files,test_sets,test_is)

path = "results/CrossVal/DDQN/"
result_files = ['0_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_12-34.txt',
                '1_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_14-04.txt',
                '2_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_15-30.txt',
                '3_DQN_CM1-postgres-card-job-masking-v0_0_2019-06-20_16-33.txt']
ddqn = combineCrossValFiles(path,result_files,test_sets,test_is)

path = "results/CrossVal/PPO/"
result_files = ['0_PPO_CM1-postgres-card-job-masking-v0_0_2019-06-21_07-19.txt',
                '1_PPO_CM1-postgres-card-job-masking-v0_0_2019-06-20_17-42.txt',
                '2_PPO_CM1-postgres-card-job-masking-v0_0_2019-06-20_20-57.txt',
                '3_PPO_CM1-postgres-card-job-masking-v0_0_2019-06-21_00-08.txt']
ppo = combineCrossValFiles(path,result_files,test_sets,test_is)

path = "results/CrossVal/DDQN82/"
result_files = ['DQN_CM1-postgres-card-job-masking-v0_0_2019-06-25_22-49.txt',
#'DQN_CM1-postgres-card-job-masking-v0_0_2019-06-25_22-56.txt',
'DQN_CM1-postgres-card-job-masking-v1_0_2019-06-25_23-03.txt',
#'DQN_CM1-postgres-card-job-masking-v1_0_2019-06-25_23_11.txt',
'DQN_CM1-postgres-card-job-masking-v2_0_2019-06-25_23_18.txt',
#'DQN_CM1-postgres-card-job-masking-v2_0_2019-06-25_23_25.txt',
'DQN_CM1-postgres-card-job-masking-v3_0_2019-06-25_23_33.txt' ]
#'DQN_CM1-postgres-card-job-masking-v3_0_2019-06-25_23_40.txt' ]
ddqn82 = combineCrossValFiles(path,result_files,test_sets,test_is)

path = "results/CrossVal/DDQN11/"
result_files = ['DQN_CM1-postgres-card-job-masking-v0_0_2019-06-25_21-43.txt',
#'DQN_CM1-postgres-card-job-masking-v0_0_2019-06-25_21-47.txt',
'DQN_CM1-postgres-card-job-masking-v1_0_2019-06-25_21-51.txt',
#'DQN_CM1-postgres-card-job-masking-v1_0_2019-06-25_21-55.txt',
'DQN_CM1-postgres-card-job-masking-v2_0_2019-06-25_21-59.txt',
#'DQN_CM1-postgres-card-job-masking-v2_0_2019-06-25_22-03.txt',
#'DQN_CM1-postgres-card-job-masking-v3_0_2019-06-25_22-07.txt',
'DQN_CM1-postgres-card-job-masking-v3_0_2019-06-25_22-11.txt']
ddqn11 = combineCrossValFiles(path,result_files,test_sets,test_is)

df['reward'].plot()
dqn['reward'].plot()
ddqn['reward'].plot()
ppo['reward'].plot()
#df_rd['reward'].plot()
#df_psql_style['reward'].plot()
plt.ylim([-0.55,0])
plt.show()

df_box = pd.DataFrame()
df_box["DP left deep"]=df['reward']
df_box["DP right deep"]=df_rd['reward']
df_box["DQN"]=dqn['reward']
df_box["DDQN"]=ddqn['reward']
df_box["PPO"]=ppo['reward']
#df_box["PSQL style"]=df_psql_style['reward']
df_box.plot.box(showfliers=False)
#plt.ylim([-0.35,0])
plt.show()

df_box = pd.DataFrame()
#df_box["DP left deep"]=df['costs']
#df_box["DP right deep"]=df_rd['costs']
df_box["DQN"]=dqn['costs']
#df_box["DDQN"]=ddqn['costs']
df_box["DDQN82"]=ddqn82['costs']
#df_box["DDQN11"]=ddqn11['costs']
df_box["PPO"]=ppo['costs']
#df_box["PSQL style"]=df_psql_style['reward']
df_box.plot.box(showfliers=False)
#plt.xlabel("?")
plt.ylabel("cost value")
plt.show()

df_box = pd.DataFrame()
#df_box["DP left deep"]=df['costs']
#df_box["DP right deep"]=df_rd['costs']
#df_box["DQN"]=dqn['costs']
#df_box["DDQN"]=ddqn['costs']
df_box["DDQN82"]=ddqn82['costs']
#df_box["DDQN11"]=ddqn11['costs']
df_box["PPO"]=ppo['costs']
#df_box["PSQL style"]=df_psql_style['reward']
df_box.plot.box(showfliers=False)
#plt.xlabel("?")
plt.ylabel("Cost Value")
plt.show()

df_box = pd.DataFrame()
df_box["DDQN82"]=ddqn82['costs']
df_box["PPO"]=ppo['costs']
df_box["DP right deep"]=df_rd['costs']
df_box["DP left deep"]=df['costs']
#df_box["PSQL style"]=df_psql_style['reward']
df_box.plot.box(showfliers=False)
#plt.xlabel("?")
plt.ylabel("Cost Value")
plt.show()

x = ppo["costs"]/df["costs"].mean()*100
x.plot.box(label="PPO",showfliers=False)
x =[0,1,2]
y = [100,100,100]
plt.plot(x,y,label="DP left deep mean", c='r')
y = [80,80,80]
#plt.plot(x,y,label="ReJoin")

plt.ylim([0, 900])
#plt.xlabel("?")
plt.ylabel("%")
plt.legend(loc='lower left')
plt.show()

'''
df['costs'].plot()
res['costs'].plot()
df_rd['costs'].plot()
plt.show()
'''


class Cart:
    products_list = []
    products_amounts = []
    total = 0
    def __init__(self, name):
        self.name = name

    def add_to_cart(self,product,amount):
        if(product.amount>=amount):
            self.products_list.append(product)
            self.products_amounts.append(amount)
            #product.amount = product.amount - amount
            product.amount -= amount
        else:
            print("No hay suficiente cantidad disponible")

    def get_iva(self):
        pass

    def get_total(self):
        suma = 0
        for i in range(len(self.products_list)):
            product = self.products_list[i]
            amount = self.products_amounts[i]
            suma += product.get_total(amount)

        print(self.name)
        print(suma)

class Product:
    def __init__(self,amount,name,description,price):
        self.amount = amount
        self.name = name
        self.description = description
        self.price = price

    def get_total(self,amount):
        return amount*self.price

class Stock:
    list_products = []

    def add_to_stock(self,product):
        self.list_products.append(product)

product1 = Product(5,"Galletas","",10)
product2 = Product(10,"Agua","",8)

cart = Cart("Tzuzul")
cart.add_to_cart(product1,3)
cart.add_to_cart(product2,3)

print(cart.products_list)

cart.get_total()

print(product1.amount)
print(product2.amount)


# ——*—— coding: utf-8 _*_
import maya.cmds as cmds
from tool import datetimeinfo

# lock normal vertex chek 检查法线是否锁定
def checkVertexNormalLock(*args):
    logDate = datetimeinfo.dateTimeInfo()
    allMesh = cmds.ls(type='mesh')
    allTransform = list(set(cmds.listRelatives(allMesh, p=True,f=True, type='transform')))
    lockedVtx = []
    checkedTransforms = set()
    for i in allTransform:
        vtx = cmds.polyListComponentConversion(i, toVertex=True)
        itemFrat = cmds.ls(vtx, flatten=True)
        for e in itemFrat:
            vartexNormalList = cmds.polyNormalPerVertex(e, q=True, freezeNormal=True)
            if True in vartexNormalList:
                lockedVtx.append(e)
        checkedTransforms.add(i)
    if lockedVtx:
        def vertexNormalLockset(*args):
            cmds.select(lockedVtx, replace=True)
        def vertexNormalLockClear(*args):
            cmds.polyNormalPerVertex(set(lockedVtx),ufn=True)
            cmds.select(cl=1)
            cmds.button('vertexNormalLocksetbtn', e=True, en=False)
            cmds.button('vertexNormalLockClearbtn', e=True, en=False)
            checkVertexNormalLock()
        # ui edit info-------------------------------------------------------------
        wrongPrint = '\n'.join(lockedVtx)
        fieldText = logDate + u'******* Error *******\n【模型法线锁定错误】\n' + u'请解除法线锁定！\n'
        cmds.button('vertexNormalLockCheckButton', e=True, bgc=[0.9, 0.4, 0.5])
        cmds.button('vertexNormalLocksetbtn', e=True, en=True,c=vertexNormalLockset)
        cmds.button('vertexNormalLockClearbtn', e=True, en=True,c=vertexNormalLockClear)
        cmds.scrollField('errorComentPrintField', e=True, insertText=fieldText, insertionPosition=0)
    else:
        # ui edit info-------------------------------------------------------------
        fieldText = logDate + u'【模型法线锁定】Check OK！\n'
        cmds.button('vertexNormalLockCheckButton', e=True, bgc=[0.5, 0.8, 0.7])
        cmds.button('vertexNormalLocksetbtn', e=True, en=False)
        cmds.button('vertexNormalLockClearbtn', e=True, en=False)
        cmds.scrollField('errorComentPrintField', e=True, insertText=fieldText, insertionPosition=0)

# checkVertexNormalLock()


import numpy as np
import pandas as pd
from torch import nn, optim
import torch
from torch.utils.data import DataLoader
from sklearn.preprocessing import LabelEncoder
from rec4torch.inputs import DenseFeat, SparseFeat, VarLenSparseFeat, build_input_array, TensorDataset
from rec4torch.models import DeepFM
from rec4torch.snippets import sequence_padding, seed_everything, Evaluator
from sklearn.metrics import f1_score

batch_size = 16
device = 'cuda' if torch.cuda.is_available() else 'cpu'
seed_everything(42)

def get_data():
    def split(x):
        key_ans = x.split('|')
        for key in key_ans:
            if key not in key2index:
                key2index[key] = len(key2index) + 1
        return list(map(lambda x: key2index[x], key_ans))

    data = pd.read_csv("./datasets/movielens_sample.txt")
    data['rating'] = data['rating'] - 1
    sparse_features = ["movie_id", "user_id", "gender", "age", "zip", ]
    dense_features = ["occupation"]

    # 离散变量编码
    for feat in sparse_features:
        lbe = LabelEncoder()
        data[feat] = lbe.fit_transform(data[feat])

    # 序列特征处理
    key2index = {}
    genres_list = list(map(split, data['genres'].values))
    genres_list = sequence_padding(genres_list)
    data['genres'] = genres_list.tolist()

    # 离散特征和序列特征处理
    fixlen_feature_columns = [SparseFeat(feat, data[feat].nunique(), embedding_dim=4) for feat in sparse_features]
    varlen_feature_columns = [VarLenSparseFeat(SparseFeat('genres', vocabulary_size=len(
        key2index) + 1, embedding_dim=4), maxlen=genres_list.shape[-1], pooling='mean')]
    dense_feature_columns = [DenseFeat(feat, 1) for feat in dense_features]

    linear_feature_columns = fixlen_feature_columns + varlen_feature_columns + dense_feature_columns
    dnn_feature_columns = fixlen_feature_columns + varlen_feature_columns + dense_feature_columns

    # 生成训练样本
    train_X, train_y = build_input_array(data, linear_feature_columns+dnn_feature_columns, target='rating')
    train_X = torch.tensor(train_X)
    train_y = torch.tensor(train_y)
    return train_X, train_y, linear_feature_columns, dnn_feature_columns

# 加载数据集
train_X, train_y, linear_feature_columns, dnn_feature_columns = get_data()
train_dataloader = DataLoader(TensorDataset(train_X, train_y, device=device), batch_size=batch_size, shuffle=True)

# 模型定义
model = DeepFM(linear_feature_columns, dnn_feature_columns, out_dim=5)
model.to(device)

model.compile(
    loss=nn.CrossEntropyLoss(),
    optimizer=optim.Adam(model.parameters(), lr=1e-2)
)

class MyEvaluator(Evaluator):
    def evaluate(self):
        y_trues, y_preds = [], []
        for X, y in train_dataloader:
            y_prob = self.model.predict(X)
            y_prob = torch.argmax(torch.softmax(y_prob, dim=-1), dim=-1)
            y_trues.append(y.cpu().numpy())
            y_preds.append(y_prob.cpu().numpy())

        return {'f1': f1_score(np.concatenate(y_trues), np.concatenate(y_preds), average='macro')}

if __name__ == "__main__":
    evaluator = MyEvaluator(monitor='f1')
    model.fit(train_dataloader, epochs=10, steps_per_epoch=None, callbacks=[evaluator])


from fastapi import FastAPI
from fastapi.responses import RedirectResponse
import json
import uvicorn

app = FastAPI()

@app.get('/')
async def home():
    return RedirectResponse(url='/data')

@app.get('/data')
async def show_data():
    file_json = open('estados-brasil.json')
    print(file_json)
    json_data = json.loads(file_json.read())
    return json_data['estados']

uvicorn.run(app, port=8000)


import os
import configparser
import sqlite3
import shutil
import requests
import json
import re
import rich
from styles import main_tuple_style, secondary_tuples_style

class DictionaryConnection:

    endpoints = {
        "Dictionary": "https://www.dictionaryapi.com/api/v3/references/collegiate/json/",
        "Thesaurus": "https://www.dictionaryapi.com/api/v3/references/thesaurus/json/",
    }

    style_dict = {
        "main": main_tuple_style,
        "secondary": secondary_tuples_style,
        "definitions": lambda x: "\n".join(x),
    }

    regex_filter = re.compile("[,\.!?/~]")

    def __init__(self, dir=os.path.join(os.environ["HOME"], ".personaldictionary")):
        api_config_path = os.path.join(dir, ".keys")
        self.meta_dict_path = os.path.join(dir, "meta.db")

        api_config = configparser.ConfigParser()
        api_config.read(api_config_path)

        self.config = api_config
        self.dir = dir

        try:
            self.meta_dict = sqlite3.connect(self.meta_dict_path)
            cur = self.meta_dict.cursor()

            create_words_table = """
            CREATE TABLE IF NOT EXISTS words (
                id integer PRIMARY KEY,
                word text NOT NULL,
                entry_id text NOT NULL
            );
            """

            create_word_entries_table = """
            CREATE TABLE IF NOT EXISTS word_entries (
                entry_id text PRIMARY KEY,
                file text
            )
            """

            cur.execute(create_words_table)
            cur.execute(create_word_entries_table)
            cur.close()

        except sqlite3.OperationalError as e:
            print("Cannot connect to local disctionary")
            print(e)
            exit()

    def disconnet(self):
        self.meta_dict.close()

    def _check_dictionary(self, word, endpoint="Dictionary"):
        url = self.endpoints[endpoint]

        res = requests.get(
            url + word, {"key": self.config.get("Merriam-Webster", endpoint)}
        )

        res.raise_for_status()

        parsed = res.json()

        if len(parsed) == 0:
            raise ValueError
        elif not isinstance(parsed[0], dict):
            raise ValueError
        elif not ("meta" in parsed[0].keys()):
            raise ValueError
        else:
            return parsed

    def _check_metadict(self, word):
        cur = self.meta_dict.cursor()

        cur.execute(
            """
        SELECT file
        FROM words
        LEFT JOIN  word_entries
        ON words.entry_id = word_entries.entry_id
        WHERE
        words.word = :word
        """,
            {"word": word},
        )

        data = cur.fetchall()
        cur.close()

        return data

    def _check_cache(self, word):
        files = self._check_metadict(word)

        if len(files) == 0:
            return None
        else:
            results = []
            for file in files:
                with open(os.path.join(self.dir, ".data", file[0]), "r") as f:
                    results.append(json.load(f))

            return results

    def _save_entry(self, entry):

        id = self.regex_filter.sub("", entry["meta"]["id"])
        entry_path = os.path.join(self.dir, ".data", id + ".json")

        with open(entry_path, "w+") as file:
            json.dump(entry, file)

    def _save_word(self, word, entries):
        cur = self.meta_dict.cursor()

        for entry in entries:
            id = self.regex_filter.sub("", entry["meta"]["id"])

            stems = set(entry["meta"]["stems"] + [word])

            for stem in stems:
                cur.execute(
                    "DELETE FROM words WHERE word = :word AND entry_id = :id",
                    {"word": stem, "id": id},
                )
                cur.execute("DELETE FROM word_entries WHERE entry_id = :id", {"id": id})

                cur.execute(
                    "INSERT INTO words (word, entry_id) VALUES (:word, :id)",
                    {"word": stem, "id": id},
                )
                cur.execute(
                    "INSERT INTO word_entries (entry_id, file) VALUES (:id, :path)",
                    {"id": id, "path": id + ".json"},
                )

            self._save_entry(entry)

        cur.close()
        self.meta_dict.commit()

    def remove_word(self, word):
        cur = self.meta_dict.cursor()
        cur.execute("DELETE FROM words WHERE word = :word", {"word": word})
        cur.close()

        self.meta_dict.commit()

    def clean_dictionary(self):
        cur = self.meta_dict.cursor()

        cur.execute(
            """
        SELECT file
        FROM word_entries
        LEFT JOIN words
            ON word_entries.entry_id = words.entry_id
        WHERE words.word IS NULL
        """
        )

        files_to_delete = cur.fetchall()

        cur.execute(
            """
        DELETE FROM word_entries
        WHERE file IN (
            SELECT file
            FROM word_entries
            LEFT JOIN words
            ON word_entries.entry_id = words.entry_id
            WHERE words.word IS NULL
        )
        """
        )

        cur.close()
        self.meta_dict.commit()

        for file in files_to_delete:
            os.remove(os.path.join(self.dir, ".data", file))

    def purge_dictionary(self):
        shutil.rmtree(os.path.join(self.dir, ".data"))

        cur = self.meta_dict.cursor()

        cur.execute("DROP TABLE IF EXISTS words")
        cur.execute("DROP TABLE IF EXISTS word_entries")

        cur.close()
        self.meta_dict.commit()

    def parse_entry(self, entry):
        parsed = {
            "main": (entry.get("meta", {}).get("stems", [""])[0], entry.get("fl", "")),
            "secondary": [
                (ure.get("ure", ""), ure.get("fl", "")) for ure in entry.get("uros", [])
            ],
            "definitions": [
                str(i + 1) + ". " + shortdef.capitalize()
                for i, shortdef in enumerate(entry.get("shortdef", []))
            ],
        }

        return parsed

    def print_word(self, parsed):
        for key, val in parsed.items():
            styled_text = self.style_dict[key](val)
            rich.print(styled_text)

    def check_word(self, word, force=False, prompt=True, save=True):

        if not force:
            entry = self._check_cache(word)
            from_cache = True
        else:
            entry = None

        if entry is None:
            try:
                entry = self._check_dictionary(word)

                if not isinstance(entry, list):
                    raise ValueError
                elif not isinstance(entry[0], dict):
                    raise ValueError
                elif entry[0].get("meta", None) is None:
                    raise ValueError
                else:
                    pass
                from_cache = False
            except ValueError:
                print(word + " not found")
                return 0

        if prompt:
            print("")
            for single_entry in entry:
                parsed = self.parse_entry(single_entry)
                self.print_word(parsed)
                print("")

        if save and not from_cache:
            self._save_word(word, entry)

    def count_words(self):
        cur = self.meta_dict.cursor()

        cur.execute("SELECT COUNT(*) total FROM words")
        count = cur.fetchall()

        if len(count) == 0:
            count = 0
        else:
            count = count[0][0]

        cur.close()
        return count

    def list_words(self, n):
        cur = self.meta_dict.cursor()

        cur.execute("SELECT word FROM words LIMIT :n", {"n": n})
        words = cur.fetchall()

        cur.close()
        return words


import os
import pickle

import requests
from flask import Flask
from flask import request
from flask import jsonify
import pandas as pd
from prophet import Prophet
from pymongo import MongoClient

MODEL_FILE = os.getenv('MODEL_FILE', 'model_prophet_Oxford.bin')

EVIDENTLY_SERVICE_ADDRESS = os.getenv('EVIDENTLY_SERVICE', 'http://127.0.0.1:5000')
MONGODB_ADDRESS = os.getenv("MONGODB_ADDRESS", "mongodb://127.0.0.1:27017")

with open(MODEL_FILE, 'rb') as f_in:
    model = pickle.load(f_in)

app = Flask('price-forecasting')
mongo_client = MongoClient(MONGODB_ADDRESS)
db = mongo_client.get_database("prediction_service")
collection = db.get_collection("data_forecasting")

@app.route('/predict', methods=['POST'])
def predict():
    record = request.get_json()
    key_features = ['ds', 'y']
    dict2 = {x:[record[x]] for x in key_features}

    feature_df = pd.DataFrame.from_dict(dict2)
    y_pred = model.predict(feature_df)
    pred = y_pred.to_dict("records")

    result = {
        'y_hat': pred[0]['yhat'],
        'y_hat_lower' : pred[0]['yhat_lower'],
        'y_hat_upper' : pred[0]['yhat_upper'],
    }

    rec = record.copy()
    rec['pred'] = result['y_hat']
    rec['pred_low'] = result['y_hat_lower']
    rec['pred_high'] = result['y_hat_upper']

    print(rec)
    ## Change from features dict to records dict
    save_to_db(record, result['y_hat'], result['y_hat_lower'], result['y_hat_upper'])
    send_to_evidently_service(record, result['y_hat'], result['y_hat_lower'], result['y_hat_upper'])
    return jsonify(result)

## Saving to MongoDB
def save_to_db(record, prediction, pred_low, pred_high):
    rec = record.copy()
    rec['pred'] = prediction
    rec['pred_low'] = pred_low
    rec['pred_high'] = pred_high
    collection.insert_one(rec)

# ## Saving to Evidently for monitoring
def send_to_evidently_service(record, prediction, pred_low, pred_high):
    rec = record.copy()
    rec['pred'] = prediction
    rec['pred_low'] = pred_low
    rec['pred_high'] = pred_high
    requests.post(f"{EVIDENTLY_SERVICE_ADDRESS}/iterate/uk_house_price", json=[rec])

if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0', port=9696)


from collections import deque

def convert_time_to_seconds(data):
    hours, minutes, seconds = [int(d) for d in data.split(':')]
    result = seconds + minutes * 60 + hours * 60 * 60
    return result

def convert_seconds_to_time(sec):
    sec %= 24 * 60 * 60
    hours = sec // 3600
    minutes = (sec - hours * 3600) // 60
    seconds = sec - hours * 3600 - minutes * 60
    return "%02i:%02i:%02i" % (hours, minutes, seconds)

robots_queue = deque(input().split(';'))

process_time_by_robot = {}
busy_time_by_robot = {}

for robot in robots_queue:
    name, time = robot.split('-')
    process_time_by_robot[name] = int(time)
    busy_time_by_robot[name] = -1

seconds = convert_time_to_seconds(input())

items = deque()

product = input()
while not product == 'End':
    items.append(product)
    product = input()

while items:
    seconds = seconds + 1
    product = items.popleft()
    for name, busy_until in busy_time_by_robot.items():
        if seconds >= busy_until:
            time_str = convert_seconds_to_time(seconds)
            print(f'{name} - {product} [{time_str}]')
            busy_time_by_robot[name] = seconds + process_time_by_robot[name]
            break
    else:
        items.append(product)


#from tags import tags MUST BE IN ALL MODULES
#tags are global flags that enable or disable blurbs in the narrative tree

class Iter_dict():
    tags = {
    "smoke_reaction"    : 1,
    "gender_formal"     : 1
    }

    outputs = {
    "smoke_reaction"    : ["entices", "repulses"],
    "gender_formal"     : ["sir", "madam"]
    }

    def __init__(self):
        None

    def __getitem__(self, key):
        skey = str(key)

        return self.outputs[key][self.tags[key]]

iter_dict = Iter_dict()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021-08-30 20:38
# @Author : huff
# @File : 875 爱吃香蕉的珂珂.py
# @Software: PyCharm

'''
珂珂喜欢吃香蕉。这里有 N 堆香蕉，第 i 堆中有 piles[i] 根香蕉。警卫已经离开了，将在 H 小时后回来。
珂珂可以决定她吃香蕉的速度 K （单位：根/小时）。每个小时，她将会选择一堆香蕉，从中吃掉 K 根。
如果这堆香蕉少于 K 根，她将吃掉这堆的所有香蕉，然后这一小时内不会再吃更多的香蕉。
珂珂喜欢慢慢吃，但仍然想在警卫回来前吃掉所有的香蕉。
返回她可以在 H 小时内吃掉所有香蕉的最小速度 K（K 为整数）。

示例 1：
输入: piles = [3,6,7,11], H = 8
输出: 4

示例 2：
输入: piles = [30,11,23,4,20], H = 5
输出: 30

示例 3：
输入: piles = [30,11,23,4,20], H = 6
输出: 23
'''
#import math
class Solution:
    def sumHour(self,piles,k):
        hour = 0
        for i in piles:
            #hour +=math.ceil(i/k)
            hour += (i-1)//k+1

        return hour

    def minEatingSpeed(self, piles: list, h: int) -> int:
        left,right = 1,max(piles)
        if len(piles) >= h:
            return max(piles)
        while left < right:
            mid = left + (right - left) // 2
            if self.sumHour(piles,mid) > h:
                left = mid +1
            else:
                right = mid
        return left

if __name__ == '__main__':
    #piles = [30,11,23,4,20]
    #H = 6
    piles = [312884470]
    H = 968709470
    s = Solution()
    result = s.minEatingSpeed(piles,H)
    print('最小速度：',result)

875 爱吃香蕉的珂珂.py


import cv2
import numpy as np

img = cv2.imread('../../resources/man2.jpg')
img2 = cv2.imread('../../resources/man3.jpg')

#opencv addition = saturated operation
    #I(x,y) = min(max(round(result), 0), 255)
cv_add = cv2.add(img, img2)
weighted = cv2.addWeighted(img, 0.5, img2, 0.5, 50)

#numpy addition
add =  img + img2

cv2.imshow("add", add)
cv2.imshow("cv_add", cv_add)
cv2.imshow("weighted", weighted)

cv2.waitKey(0)
cv2.destroyAllWindows()


from __future__ import division

import abc
import datetime
import json
import math
import os
import socket
import threading
import time
from collections import OrderedDict
from hashlib import md5
from multiprocessing import Process, Queue
from subprocess import Popen, PIPE, STDOUT
from sys import builtin_module_names

from gammarf_base import GrfModuleBase

AVG_SAMPLES = 50  # how many samples to avg before sending data
CHECK_QUEUE_INTERVAL = 10000
CMD_BUFSZ = 32768
CMDSOCK_TIMEOUT = 10
ERROR_SLEEP = 3
HACKRF_LNA_GAIN = 32
HACKRF_MIN_SCAN_MHZ = 40
HACKRF_MAX_SCAN_MHZ = 2000
MODULE_DESCRIPTION = "spectrum module"
REPORTER_QSIZE_LIMIT = 1e6
REPORTER_SLEEP = 1/250 # so as not to saturate the server
RTLSDR_CROP = 20  # %
RTLSDR_INTEGRATION_INTERVAL = 3
RTLSDR_WINDOW = "hamming"
THREAD_TIMEOUT = 3

device_list = ["rtlsdr", "hackrf"]

def start(config):
    return GrfModuleSpectrum(config)

class Reporter(Process):
    def __init__(self, reporter_opts, reporter_queue, settings):
        self.station_id = reporter_opts['station_id']
        self.station_pass = reporter_opts['station_pass']
        self.server_host = reporter_opts['server_host']
        self.server_port = reporter_opts['server_port']
        self.freqmap = dict()
        self.running = True
        self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.reporter_queue = reporter_queue

        self.settings = dict()
        for setting, default in settings.items():
            self.settings[setting] = default

        super(Reporter, self).__init__()

    def run(self):
        while self.running:
            (op, args) = self.reporter_queue.get()

            if op == "stop":
                self.running = False
                continue

            if op == "toggle":
                self.settings[args[0]] = args[1]
                continue

            freq, pwr, loc, ct, step = args
            sent = False

            try:
                fent = self.freqmap[freq]
            except KeyError:
                fent = {'mean': 0, 'stdev': 0, 'n': 0, 'S': 0, 'last_reported_mean': None, 'last_reported_stdev': None}

            # http://dsp.stackexchange.com/questions/811/determining-the-mean-and-standard-deviation-in-real-time
            prev_mean = fent['mean']
            fent['n'] = fent['n'] + 1
            fent['mean'] = fent['mean'] + (pwr - fent['mean']) / fent['n']
            fent['S'] = fent['S'] + (pwr - fent['mean']) * (pwr - prev_mean)
            fent['stdev'] = math.sqrt(fent['S']/fent['n'])

            if fent['n'] > AVG_SAMPLES:
                if fent['last_reported_mean']:
                    if abs(fent['mean']) > abs(fent['last_reported_mean']) + fent['last_reported_stdev']:
                        self.send_stats(freq, fent['mean'], fent['stdev'])
                        fent['last_reported_mean'] = fent['mean']
                        fent['last_reported_stdev'] = fent['stdev']
                        sent = True
                else:
                    self.send_stats(freq, fent['mean'], fent['stdev'])
                    fent['last_reported_mean'] = fent['mean']
                    fent['last_reported_stdev'] = fent['stdev']
                    sent = True

            self.freqmap[freq] = fent

            if sent:
                time.sleep(REPORTER_SLEEP)

        return

    def send_stats(self, freq, mean, stdev):
        data = OrderedDict()
        data['freq'] = freq
        data['mean'] = str(mean)
        data['stdev'] = str(stdev)
        data['ct'] = int(time.time())
        data['stationid'] = self.station_id
        data['module'] = 'sp'

        # just basic sanity
        m = md5()
        m.update(self.station_pass + str(data['mean']) + str(data['ct']))
        data['sign'] = m.hexdigest()[:12]

        self.socket.sendto(json.dumps(data), (self.server_host, self.server_port))

class RtlSpectrum(threading.Thread):
    def __init__(self, spectrum_opts, reporter, reporter_queue, gpsp, devmod, parent):
        threading.Thread.__init__(self)

        self.devnum = spectrum_opts['devnum']
        self.reporter = reporter
        self.reporter_queue = reporter_queue
        self.gpsp = gpsp
        self.devmod = devmod
        self.parent = parent
        self.overflow = False

        cmd = spectrum_opts['cmd']
        fstr = spectrum_opts['fstr']
        integration = spectrum_opts['integration']
        gain = spectrum_opts['gain']
        ppm = spectrum_opts['ppm']

        ON_POSIX = 'posix' in builtin_module_names
        self.cmdpipe = Popen([cmd, "-d {}".format(self.devnum), "-f {}".format(fstr),
                "-i {}".format(integration), "-p {}".format(ppm), "-g {}".format(gain),
                "-c {}%".format(RTLSDR_CROP), "-w {}".format(RTLSDR_WINDOW)],
                stdout=PIPE, stderr=STDOUT, close_fds=ON_POSIX)

        self.stoprequest = threading.Event()

    def run(self):
        check_q = 0

        while not self.stoprequest.isSet():
            data = self.cmdpipe.stdout.readline()

            if len(data) == 0:
                try:
                    continue
                except Exception:
                    return

            # look for gps here to avoid flooding the reporter in the case of no lock
            loc = self.gpsp.get_current()
            if (loc == None) or (loc['lat'] == "0.0" and loc['lng'] == "0.0") or (loc['lat'] == "NaN"):
                print("[spectrum] No GPS loc, waiting...")
                time.sleep(ERROR_SLEEP)
                continue

            for raw in data.split('\n'):
                if len(raw) == 0:
                    continue

                if len(raw.split(' ')[0].split('-')) != 3:  # line irrelevant, or from stderr
                    if raw == "Error: dropped samples.":
                        print("[spectrum] Error with device {}, exiting task".format(self.devnum))
                        self.devmod.removedev(self.devnum)
                        return
                    continue

                try:
                    _date, _time, freq_low, freq_high, step, _samples, raw_readings = raw.split(', ', 6)
                    freq_low = float(freq_low)
                    step = float(step)
                    readings = [x.strip() for x in raw_readings.split(',')]

                except:
                    print("[spectrum] Thread exiting on exception")
                    return

                ct = int(time.time())
                for i in range(len(readings)):
                    freq = int(round(freq_low + (step * i)))
                    pwr = float(readings[i])
                    self.reporter_queue.put( ("data", (freq, pwr, loc, ct, step) ) )

            check_q += 1
            if check_q >= CHECK_QUEUE_INTERVAL:
                qsize = self.reporter_queue.qsize()
                if qsize > REPORTER_QSIZE_LIMIT:
                    print("[spectrum] WARINING: Queue filling up too fast!  Run spectrum over less bandwidth.")
                    self.overflow = True
                    break
                check_q = 0

        self.cmdpipe.stdout.close()
        self.cmdpipe.kill()
        os.kill(self.cmdpipe.pid, 9)
        os.wait()

        if self.overflow:
            self.parent.stop(self.devnum, self.devmod)

        return

    def join(self, timeout=None):
        self.stoprequest.set()
        super(RtlSpectrum, self).join(timeout)

class HackRFSpectrum(threading.Thread):
    def __init__(self, spectrum_opts, reporter, reporter_queue, gpsp, devmod, parent):
        threading.Thread.__init__(self)

        self.devnum = spectrum_opts['devnum']
        self.reporter = reporter
        self.reporter_queue = reporter_queue
        self.gpsp = gpsp
        self.devmod = devmod
        self.parent = parent
        self.overflow = False
        cmd = spectrum_opts['cmd']
        fstr = spectrum_opts['fstr']
        width = spectrum_opts['width']
        lna_gain = spectrum_opts['lna_gain']
        vga_gain = spectrum_opts['vga_gain']

        ON_POSIX = 'posix' in builtin_module_names
        DEVNULL = open(os.devnull, 'w')
        self.cmdpipe = Popen([cmd, "-f{}".format(fstr), "-w {}".format(width),
            "-l {}".format(lna_gain), "-g {}".format(vga_gain)],
            stdout=PIPE, stderr=DEVNULL, close_fds=ON_POSIX)

        self.stoprequest = threading.Event()

    def run(self):
        check_q = 0

        while not self.stoprequest.isSet():
            data = self.cmdpipe.stdout.readline()

            if len(data) == 0:
                continue

            # look for gps here to avoid flooding the reporter in the case of no lock
            loc = self.gpsp.get_current()
            if (loc == None) or (loc['lat'] == "0.0" and loc['lng'] == "0.0") or (loc['lat'] == "NaN"):
                print("[spectrum] No GPS loc, waiting...")
                time.sleep(ERROR_SLEEP)
                continue

            for raw in data.split('\n'):
                if len(raw) == 0:
                    continue

                try:
                    _date, _time, freq_low, freq_high, step, _samples, raw_readings = raw.split(', ', 6)
                    freq_low = float(freq_low)
                    step = float(step)
                    readings = [x.strip() for x in raw_readings.split(',')]

                except Exception:
                    print("[spectrum] Thread exiting on exception")
                    return

                ct = int(time.time())
                for i in range(len(readings)):
                    freq = int(round(freq_low + (step * i)))
                    try:
                        pwr = float(readings[i])
                    except:
                        continue

                    try:
                        self.reporter_queue.put( ("data", (freq, pwr, loc, ct, step) ) )
                    except:
                        pass  # when exiting

            check_q += 1
            if check_q >= CHECK_QUEUE_INTERVAL:
                qsize = self.reporter_queue.qsize()
                if qsize > REPORTER_QSIZE_LIMIT:
                    print("[spectrum] WARINING: Queue filling up too fast!  Run spectrum over less bandwidth.")
                    self.overflow = True
                    break
                check_q = 0

        self.cmdpipe.stdout.close()
        self.cmdpipe.kill()
        os.kill(self.cmdpipe.pid, 9)
        os.wait()

        if self.overflow:
            self.parent.stop(self.devnum, self.devmod)

        return

    def join(self, timeout=None):
        self.stoprequest.set()
        super(HackRFSpectrum, self).join(timeout)

class GrfModuleSpectrum(GrfModuleBase):
    def __init__(self, config):
        rtl_path = config.rtldevs.rtl_path
        if not isinstance(rtl_path, str) or not rtl_path:
            raise Exception("param 'rtl_path' not appropriately defined in config")

        rtlcmd = rtl_path + '/' + 'rtl_power'
        if not os.path.isfile(rtlcmd) or not os.access(rtlcmd, os.X_OK):
            raise Exception("executable rtl_power not found in specified path")

        hackrf_path = config.hackrfdevs.hackrf_path
        if not isinstance(hackrf_path, str) or not hackrf_path:
            raise Exception("param 'hackrf_path' not appropriately defined in config")

        hackrfcmd = hackrf_path + '/' + 'hackrf_sweep'
        if not os.path.isfile(hackrfcmd) or not os.access(hackrfcmd, os.X_OK):
            raise Exception("executable hackrf_sweep not found in specified path")

        self.rtlcmd = rtlcmd
        self.hackrfcmd = hackrfcmd
        self.spectrum_workers = list()
        self.reporter = None

        self.settings = {}

        print("Loading {}".format(MODULE_DESCRIPTION))

    def help(self):
        print("Spectrum: Report statistics about large swaths of bandwidth")
        print("")
        print("Usage: spectrum devnum freqs")
        print("\tWhere freqs is a frequency range in rtl_power format.")
        print("\tExample: > run spectrum 0 200M:300M:15k")
        print("")
        print("\tSettings:")
        return True

    def run(self, devnum, freqs, system_params, loadedmods, remotetask=False):
        self.remotetask = remotetask
        devmod = loadedmods['devices']

        # these things are done only once
        if not self.reporter:  # don't do in init -- what if the module's never used?
            reporter_opts = {'station_id': system_params['station_id'],
                    'station_pass': system_params['station_pass'],
                    'server_host': system_params['server_host'],
                    'server_port': system_params['server_port']}

            self.gpsworker = loadedmods['location'].gps_worker
            self.reporter_queue = Queue()
            reporter = Reporter(reporter_opts, self.reporter_queue, self.settings)
            reporter.daemon = True
            reporter.start()
            self.reporter = reporter

        if not freqs:
            print("Must include a frequency specification")
            return
        freqs = freqs.strip()
        if len(freqs.split(':')) != 3:
            print("Bad frequency specification")
            return

        devtype = devmod.get_devtype(devnum)
        if devtype == "rtlsdr":
            try:
                outfreqs = []
                lowfreq, highfreq, width = freqs.split(':')
                for f in [lowfreq, highfreq]:
                    if f[len(f)-1] == 'M':
                        f = int(float(f[:len(f)-1])*1e6)
                    elif f[len(f)-1] == 'k':
                        f = int(float(f[:len(f)-1])*1e3)
                    else:
                        f = int(f)
                    outfreqs.append(f)
            except Exception:
                print("Error parsing frequency string")
                return

            if outfreqs[1] < outfreqs[0]:
                print("Second scan frequency must be greater than the first scan frequency")
                return

            fstr = "{}:{}:{}".format(str(outfreqs[0]), str(outfreqs[1]), width)

            spectrum_opts = {'cmd': self.rtlcmd,
                    'devnum': devnum,
                    'fstr': fstr,
                    'integration': RTLSDR_INTEGRATION_INTERVAL,
                    'ppm': devmod.get_ppm(devnum),
                    'gain': devmod.get_gain(devnum)}

            spectrum = RtlSpectrum(spectrum_opts, self.reporter, self.reporter_queue, self.gpsworker, devmod, self)

        elif devtype == "hackrf":
            try:
                outfreqs = []
                lowfreq, highfreq, width = freqs.split(':')
                for f in [lowfreq, highfreq]:
                    if f[len(f)-1] == 'M':
                        f = int(float(f[:len(f)-1]))
                    elif f[len(f)-1] == 'k':
                        print("Use frequencies with an 'M' (MHz) suffix")
                        return
                    else:
                        print("Use frequencies with an 'M' (MHz) suffix")
                        return
                    outfreqs.append(f)

                if outfreqs[1] < outfreqs[0]:
                    print("Second scan frequency must be greater than the first scan frequency")
                    return

                if outfreqs[1] - outfreqs[0] < HACKRF_MIN_SCAN_MHZ:
                    print("You must scan at least {} MHz when using HackRF.".format(HACKRF_MIN_SCAN_MHZ))
                    return

                if outfreqs[1] - outfreqs[0] > HACKRF_MAX_SCAN_MHZ:
                    print("You may scan at most {} MHz when using HackRF.".format(HACKRF_MAX_SCAN_MHZ))
                    return

                if width[len(width)-1] == 'M':
                    width = int(float(width[:len(width)-1]) * 1e6)
                elif width[len(width)-1] == 'k':
                    width = int(float(width[:len(width)-1]) * 1e3)
                else:
                    width = int(width)

            except Exception:
                print("Error parsing frequency string")
                return

            fstr = "{}:{}".format(str(outfreqs[0]), str(outfreqs[1]))

            spectrum_opts = {'cmd': self.hackrfcmd,
                    'devnum': devnum,
                    'fstr': fstr,
                    'width': width,
                    'lna_gain': devmod.get_lna_gain(devnum),
                    'vga_gain': devmod.get_vga_gain(devnum)}

            spectrum = HackRFSpectrum(spectrum_opts, self.reporter, self.reporter_queue, self.gpsworker, devmod, self)

        spectrum.daemon = True
        spectrum.start()
        self.spectrum_workers.append( (devnum, spectrum) )

        print("Spectrum added on device {}".format(devnum))
        print("[spectrum] NOTE: It takes awhile to gather samples to form an average, for new frequency ranges")

        return True

    def report(self):
        return

    def info(self):
        return

    def shutdown(self):
        print("Shutting down spectrum module(s)")
        try:  # if no module is running, this will cause an error
            self.reporter_queue.put( ("stop", (None) ) )
        except:
            pass

        self.reporter.terminate()
        self.reporter.join()
        self.reporter_queue.close()

        for spectrum in self.spectrum_workers:
            devnum, thread = spectrum
            thread.join(THREAD_TIMEOUT)

        return

    def showconfig(self):
        return

    def setting(self, setting, arg=None):
        if not self.reporter_queue:
            print("Module not ready")
            return True

        if setting == None:
            for setting, state in self.settings.items():
                print("{}: {} ({})".format(setting, state, type(state)))
            return True

        if setting == 0:
            return self.settings.keys()

        if setting not in self.settings.keys():
            return False

        if isinstance(self.settings[setting], bool):
            new = not self.settings[setting]
        elif not arg:
            print("Non-boolean setting requires an argument")
            return True
        else:
            if isinstance(self.settings[setting], int):
                new = int(arg)
            elif isinstance(self.settings[setting], float):
                new = float(arg)
            else:
                new = arg

        self.settings[setting] = new
        self.reporter_queue.put( ("toggle", (setting, new) ) )

        return True

    def stop(self, devnum, devmod):
        for spectrum in self.spectrum_workers:
            spectrum_devnum, thread = spectrum
            if spectrum_devnum == devnum:
                try:
                    thread.join(THREAD_TIMEOUT)
                except:  # exiting due to queue overflow
                    pass

                if not self.remotetask:
                    devmod.freedev(devnum)

                self.spectrum_workers.remove( (spectrum_devnum, thread) )
                return True

        return False

    def ispseudo(self):
        return False

    def devices(self):
        return device_list


"""This module contains the class representing EVM contracts, aka Smart
Contracts."""
import re
import logging
import persistent

from mythril.support.support_utils import sha3
from mythril.disassembler.disassembly import Disassembly
from mythril.support.support_utils import get_code_hash

log = logging.getLogger(__name__)

class EVMContract(persistent.Persistent):
    """This class represents an address with associated code (Smart
    Contract)."""

    def __init__(
        self, code="", creation_code="", name="Unknown", enable_online_lookup=False
    ):
        """Create a new contract.

        Workaround: We currently do not support compile-time linking.
        Dynamic contract addresses of the format __[contract-name]_____________ are replaced with a generic address
        Apply this for creation_code & code

        :param code:
        :param creation_code:
        :param name:
        :param enable_online_lookup:
        """
        creation_code = re.sub(r"(_{2}.{38})", "aa" * 20, creation_code)
        code = re.sub(r"(_{2}.{38})", "aa" * 20, code)
        self.creation_code = creation_code
        self.name = name
        self.code = code
        self.disassembly = Disassembly(code, enable_online_lookup=enable_online_lookup)

        self.creation_disassembly = Disassembly(
            creation_code, enable_online_lookup=enable_online_lookup
        )

    @property
    def bytecode_hash(self):
        """

        :return: runtime bytecode hash
        """
        return get_code_hash(self.code)

    @property
    def creation_bytecode_hash(self):
        """

        :return: Creation bytecode hash
        """
        return get_code_hash(self.creation_code)

    def as_dict(self):
        """

        :return:
        """
        return {
            "name": self.name,
            "code": self.code,
            "creation_code": self.creation_code,
            "disassembly": self.disassembly,
        }

    def get_easm(self):
        """

        :return:
        """
        return self.disassembly.get_easm()

    def get_creation_easm(self):
        """

        :return:
        """
        return self.creation_disassembly.get_easm()

    def matches_expression(self, expression):
        """

        :param expression:
        :return:
        """
        str_eval = ""
        easm_code = None

        tokens = re.split("\s+(and|or|not)\s+", expression, re.IGNORECASE)

        for token in tokens:

            if token in ("and", "or", "not"):
                str_eval += " " + token + " "
                continue

            m = re.match(r"^code#([a-zA-Z0-9\s,\[\]]+)#", token)

            if m:
                if easm_code is None:
                    easm_code = self.get_easm()

                code = m.group(1).replace(",", "\\n")
                str_eval += '"' + code + '" in easm_code'
                continue

            m = re.match(r"^func#([a-zA-Z0-9\s_,(\\)\[\]]+)#$", token)

            if m:

                sign_hash = "0x" + sha3(m.group(1))[:4].hex()
                str_eval += '"' + sign_hash + '" in self.disassembly.func_hashes'

        return eval(str_eval.strip())


from datetime import datetime
array = [2, 4, 5, 65, 76, -2, 12, 11, 9, 1, 0]
size = len(array)
print(array)

for i in range(1, size):
    aux = array[i]
    j = i-1
    k = j
    for j in range(0,(i)):

        if (array[k]>aux):

            array[k+1]=array[k]
            k = k-1

    array[k+1] = aux

print(array)

hora =datetime.now()
print(hora)