# Ten program wyświetla pięć liczb losowych
# z przedziału od 1 do 100.
import random

def main():
    for count in range(5):
        # Wygenerowanie liczby losowej.
        number = random.randint(1, 100)
        # Wyświetlenie wygenerowanej liczby.
        print(number)

# Wywołanie funkcji main().
main()


from pwn import *

# conn = remote('20.197.63.174', 3331)
conn = process(['python3', 'game.py'])

def send_replacements(lst):
	global conn
	n = len(lst)
	confirm = [b'y'] * n
	confirm[-1] = b'n'
	for i in range(n):
		conn.sendline(lst[i])
		conn.sendline(confirm[i])

def play_level(lst, level=0):
	global conn
	conn.sendline(b'y')
	send_replacements(lst)
	conn.recvuntil(b'Level passed!\n')

# level 1
play_level([
	b'hacking => CSeC'
], level=1)

# level 2
play_level([
	b'hi => bye',
	b'asc => crash'
], level=2)

# level 3
play_level([
	b'qq => q'
], level=3)

# level 4
play_level([
	b'qq => d', b'qd => d', b'dq => d', b'dd => d',
	b'd => quackquack'
], level=4)

conn.recvuntil(b'Game: ')
flag1 = conn.recvline().strip().decode()
print(flag1)

# level 5
play_level([
	b'*0 => *aR', b'*1 => *bR', 	# init left
	b'R0$ => La$', b'R1$ => Lb$', 	# init right
	b'a0L => aaR', b'a1L => abR', b'b0L => baR', b'b1L => bbR', 	# left turnback
	b'R0a => Laa', b'R1a => Lba', b'R0b => Lab', b'R1b => Lbb', 	# right turnback
	b'0L => L0', b'1L => L1', 	# move left
	b'R0 => 0R', b'R1 => 1R', 	# move right
	b'L => p', b'aR => p', b'bR => p', 	# base case palindrome
	b'apa => p', b'bpb => p', 	# palindrome reduction from center
	b'apb => q', b'bpa => q', b'aqa => q', b'bqb => q', b'aqb => q', b'bqa => q', 	# not_palindrome reduction
	b'*p$ => palindrome', b'*q$ => not_palindrome' 	# final answer
], level=5)

conn.recvuntil(b'flag: ')
flag2 = conn.recvline().strip().decode()
print(flag2)

conn.close()


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

from .utils import Logger

class Scheduler(object):
    spider = None

    def __init__(self, crawler):
        self.settings = crawler.settings
        self.logger = Logger.from_crawler(crawler)
        if self.settings.getbool("CUSTOM_REDIS"):
            from custom_redis.client import Redis
        else:
            from redis import Redis
        self.redis_conn = Redis(self.settings.get("REDIS_HOST"),
                                self.settings.getint("REDIS_PORT"))
        self.queue_name = None
        self.queues = {}

    @classmethod
    def from_crawler(cls, crawler):
        return cls(crawler)

    def open(self, spider):
        self.spider = spider
        self.queue_name = self.settings.get(
            "TASK_QUEUE_TEMPLATE", "%s:request:queue") % spider.name
        spider.set_redis(self.redis_conn)

    def enqueue_request(self, request):
        request.callback = getattr(
            request.callback, "__name__", request.callback)
        request.errback = getattr(
            request.errback, "__name__", request.errback)
        self.redis_conn.zadd(
            self.queue_name,
            pickle.dumps(request),
            -int(request.meta["priority"]))
        self.logger.debug("Crawlid: %s, url: %s added to queue. " % (
            request.meta['crawlid'], request.url))

    def next_request(self):
        self.logger.debug(
            "length of queue %s is %s" % (
                self.queue_name, self.redis_conn.zcard(self.queue_name)))
        item = None

        if self.settings.getbool("CUSTOM_REDIS"):
            item = self.redis_conn.zpop(self.queue_name)
        else:
            pipe = self.redis_conn.pipeline()
            pipe.multi()
            pipe.zrange(self.queue_name, 0, 0).zremrangebyrank(
                self.queue_name, 0, 0)
            result, _ = pipe.execute()
            if result:
                item = result[0]

        if item:
            request = pickle.loads(item)
            request.callback = request.callback and getattr(
                self.spider, request.callback)
            request.errback = request.errback and getattr(
                self.spider, request.errback)
            return request

    def close(self, reason):
        self.logger.info("Closing Spider: %s. " % self.spider.name)

    def has_pending_requests(self):
        return False

class SingleTaskScheduler(Scheduler):

    def __init__(self, crawler):
        super(SingleTaskScheduler, self).__init__(crawler)
        self.queue_name = "%s:single:queue"

    def has_pending_requests(self):
        return self.redis_conn.zcard(self.queue_name) > 0


#!/usr/bin/env python

import argparse

def filter_sam( out_fn, in_fn, chromosome):
  with open(out_fn, 'w') as donor_out:
    for line in open(in_fn, 'r'):
      if line.startswith("@SQ"):
        if "SN:{}\t".format(chromosome) in line:
          donor_out.write(line)
      elif line.startswith("@"):
        donor_out.write(line)
      else:
        fields = line.strip('\n').split('\t')
        if fields[2] == chromosome:
          donor_out.write(line)

if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Filter specified chromosome')
  parser.add_argument('--target', help='target filename')
  parser.add_argument('--source', help='source filename')
  parser.add_argument('--chromosome', help='name of chromosome')
  args = parser.parse_args()
  filter_sam(args.target, args.source, args.chromosome)


# Inserting a Node Into a Sorted Doubly Linked List

# Given a reference to the head of a doubly-linked list and an integer, , create a new DoublyLinkedListNode object having data value
# and insert it at the proper location to maintain the sort.

class DoublyLinkedListNode:
    def __init__(self, data=0, prev=None, next=None):
        self.val = val
        self.prev = prev
        self.next = next

class Solution:
    def sortedInsert(head, data):
        current = head
        newNode = DoublyLinkedListNode(data)

        # If the node is to be inserted at
        # the beginning of the doubly linked list
        if head.data >= newNode.data:
            newNode.next = head
            newNode.next.prev = newNode
            head = newNode
        else:
            current = head
            # Locate the node after which
            # the new node  is to be inserted
            while current.next and current.next.data < newNode.data:
                current = current.next

            # Make the appropriate links
            newNode.next = current.next

            # If the new node is not inserted
            # at the end of the list
            if current.next:
                newNode.next.prev = newNode
            newNode.prev = current
            current.next = newNode
        return head


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

# import needed modules
from requests import get
from csv import writer, reader
from datetime import date
import sys

# %% define function for export/save data to *.csv file

def write_csv(data, filepath):
    with open(filepath, 'w', newline='') as csv_file:
        write = writer(csv_file)
        for element in data:
            write.writerow(element.split(","))

# %% check arguments passed by user by sys.argv

if len(sys.argv) == 3:
    api_key = sys.argv[1]
    user_input_date = sys.argv[2]
elif len(sys.argv) == 2:
    api_key = sys.argv[1]
    user_input_date = str(date.today())
elif len(sys.argv) < 2:
    print("\nPodano za mało argumentów za pomocą 'sys.argv'.\n"
          "Program do działania wymaga dwóch lub trzech argumentów:\n"
          "rain_forecast.py << klucz API >> << data w formacie YYYY-MM-DD >>\n"
          "lub\n"
          "rain_forecast.py << klucz API >>.\n\n"
          "Działanie programu zakończone.")
    sys.exit()
else:
    print("\nPodano za dużo argumentów za pomocą 'sys.argv'.\n"
          "Program do działania wymaga dwóch lub trzech argumentów:\n"
          "rain_forecast.py << klucz API >> << data w formacie YYYY-MM-DD >>\n"
          "lub\n"
          "rain_forecast.py << klucz API >>.\n\n"
          "Działanie programu zakończone.")
    sys.exit()

if len(user_input_date) != 10:
    print("\nNieprawidłowy format daty.\n"
          "Prawidłowy format to YYYY-MM-DD, np. 2022-10-10.\n\n"
          "Działanie programu zakończone.")
    sys.exit()

# %% variables to downlad data from API

url = "https://weatherbit-v1-mashape.p.rapidapi.com/forecast/daily"

# coordinates for Poznań
latitude = 52.40692
longitude = 16.92993

querystring = {"lat": latitude, "lon": longitude}

headers = {
    "X-RapidAPI-Key": f"{api_key}",
    "X-RapidAPI-Host": "weatherbit-v1-mashape.p.rapidapi.com"
}

# %% variables to open/read data from *.csv file

FILEPATH = "checked_days.csv"

csv_file = reader(open(FILEPATH))
lines_from_csv = list(csv_file)

dictionary_CSV = {}

# %% load data from *.csv file to dict

for element in lines_from_csv:
    dictionary_CSV[f"{element[0]}"] = {
        'precip': float(element[1]),
        'snow': float(element[2])
        }

# %% main 'if/elif/else' statetments

if user_input_date in dictionary_CSV.keys():
    if (dictionary_CSV[f'{user_input_date}']['precip'] > 0 and
            dictionary_CSV[f'{user_input_date}']['snow'] > 0):
        print(f"\nW dniu {user_input_date} w Poznaniu "
              "będzie padać śnieg z deszczem :(")

    elif dictionary_CSV[f'{user_input_date}']['precip'] > 0:
        print(f"\nW dniu {user_input_date} w Poznaniu "
              "będzie padać deszcz! Zabierz ze sobą parasol :)")

    elif dictionary_CSV[f'{user_input_date}']['snow'] > 0:
        print(f"\nW dniu {user_input_date} w Poznaniu "
              "będzie padać śnieg! Ubierz coś ciepłego :)")

    else:
        print(f"\nW dniu {user_input_date} w Poznaniu nie będzie padać! "
              "Miłego dnia :)")

else:
    print("\nPobieram dane z API.")
    dictionary_API = {}
    r = get(url, headers=headers, params=querystring)
    response = r.json()
    weather_forecast_data = response['data']

    for day in weather_forecast_data:
        dictionary_API[f"{day['datetime']}"] = {
            'precip': day['precip'],
            'snow': day['snow']
            }

    if user_input_date in dictionary_API.keys():
        if (dictionary_API[f'{user_input_date}']['precip'] > 0 and
                dictionary_API[f'{user_input_date}']['snow'] > 0):
            print(f"\nW dniu {user_input_date} w Poznaniu "
                  "będzie padać śnieg z deszczem :(")

        elif dictionary_API[f'{user_input_date}']['precip'] > 0:
            print(f"\nW dniu {user_input_date} w Poznaniu "
                  "będzie padać deszcz! Zabierz ze sobą parasol :)")

        elif dictionary_API[f'{user_input_date}']['snow'] > 0:
            print(f"\nW dniu {user_input_date} w Poznaniu "
                  "będzie padać śnieg! Ubierz coś ciepłego :)")

        else:
            print(f"\nW dniu {user_input_date} w Poznaniu nie będzie padać! "
                  "Miłego dnia :)")

    else:
        print(f"\nNie wiem czy w dniu {user_input_date} będzie padać "
              "w Poznaniu!")

# write/save data to *.csv file
    list_for_write_csv = []
    for key, day in zip(dictionary_API.keys(), dictionary_API):
        string = (f"{key},{dictionary_API[day]['precip']},"
                  f"{dictionary_API[day]['snow']}")
        list_for_write_csv.append(string)

    write_csv(list_for_write_csv, FILEPATH)

# %%


from typing import Optional
'''
1373. 二叉搜索子树的最大键值和

dfs
边统计和边判断是否为搜索树即可。
一旦子树不为搜索树，直接520520。
'''
null = None
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def maxSumBST(self, root: Optional[TreeNode]) -> int:
        res = 0
        def dfs(node):
            nonlocal res
            if node is None:
                return 0, 520520, -520520
            sum_left, min_left, max_left = dfs(node.left)
            sum_right, min_right, max_right = dfs(node.right)
            if min_left == -520520 or min_right == -520520 or max_left == 520520 or max_right == 520520:
                return 0, -520520, 520520
            if max_left >= node.val or min_right <= node.val:
                return 0, -520520, 520520
            sum1 = sum_left + sum_right + node.val
            res = max(res, sum1)
            return sum1, min(node.val, min_left), max(node.val, max_right)
        _, _, _ = dfs(root)
        return res

s = Solution()
print(s.maxSumBST([1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]))


#!/usr/bin/env python3
from http.server import ThreadingHTTPServer
from os.path import dirname, realpath
from .httpHandler import HTTPApiHandler
from .fileCacher import cacheFile
from ..query import QueryHandler

def startServer(port):
    HTTPApiHandler.queryHandler = QueryHandler()
    filesPath = dirname(realpath(__file__)) + "/files"
    cacheFile(None, filesPath + "/404.html", "text/html")
    cacheFile("/404_styles.css", filesPath + "/404_styles.css", "text/css")
    cacheFile("/404.png", filesPath + "/404.png", "image/png")
    cacheFile("/index.html", filesPath + "/index.html", "text/html")
    cacheFile("/rest-caller.js", filesPath + "/rest-caller.js", "text/javascript")
    cacheFile("/styles.css", filesPath + "/styles.css", "text/css")
    cacheFile("/roboto.css", filesPath + "/roboto.css", "text/css")
    cacheFile("/Roboto-Regular.ttf", filesPath + "/Roboto-Regular.ttf", "application/octet-stream")
    cacheFile("/Roboto-Medium.ttf", filesPath + "/Roboto-Medium.ttf", "application/octet-stream")
    httpd = ThreadingHTTPServer(('', port), HTTPApiHandler)
    try:
        print("Server started")
        httpd.serve_forever()
    except Exception as e:
        print("\nException occurred, stopping: {}".format(e))
    except KeyboardInterrupt:
        print("\nGracefully stopping server...")
    httpd.server_close()
    print("Server stopped")

if __name__ == "__main__":
    startServer(8080)


"""
Kela Kanta data preprocessing

Reads Kela Kanta data, applies the preprocessing steps below and writes the result to files.
- remove extra linebreaks
- remove empty lines
- transform base16 ints to base10 ints
- parse dates
- replace "," with "." as a decimal point

Note: running this script on ePouta takes several hours.
Speed could be improved with e.g. multiprocessing if needed.

Input files:
- 107_522_2021_LM_<YYYY>.csv.finreg_IDs (11 files)
- 107_522_2021_LT_<YYYY>.csv.finreg_IDs (11 files)

Output files:
- prescriptions_<YYYY>_<YYYY-MM-DD>.csv (11 files)
- deliveries_<YYYY>_<YYYY-MM-DD>.csv (11 files)
"""

import os
import re
import pandas as pd
from datetime import datetime
from functools import partial
from finregistry_data.config import KELA_KANTA_INPUT_DIR, KELA_KANTA_OUTPUT_DIR

def read_prescription_data(filepath):
    """Read drug prescriptions data in chunks"""
    hash_to_int = partial(int, base=16)
    hash_cols = [
        "CDA_ID_MD5HASH",
        "CDA_SET_ID_MD5HASH",
        "DOC_GROUP_MD5HASH",
        "CDA_ADDENDUM_REF_MD5HASH",
        "CDA_RPLC_ID_MD5HASH",
        "PRO_PERSON_REG_MD5HASH",
        "ORGANIZATION_OID_MD5HASH",
    ]
    date_cols = ["CREATION_DATE"]
    dtypes = {
        "PATIENT_ID": str,
        "DOC_TYPE_CODE": float,
        "DOC_VERSION": float,
        "DRUG_NAME_C": str,
        "DOSE_QUANTITY_TEXT": str,
        "ATC_CODE": str,
        "PURPOSE_OF_USE": str,
        "DOSAGE_INSTRUCTIONS": str,
        "ITERATION_CODE": float,
        "TYPE_1_AMOUNT": str,
        "TYPE_1_SIZE": str,
        "TYPE_2_AMOUNT": str,
        "TYPE_2_SIZE_UNIT": str,
        "TYPE_3_TIME": str,
        "TYPE_3_UNIT": str,
        "PRODUCT_CODE": float,
        "DOSE_DISTRIBUTION": str,
        "PREPARATION_TYPE_CODE": float,
        "RESEPTISTATUS": str,
        "LAAKEMUOTOKOODI": float,
        "ERIKOISALA_CODE": str,
        "MED_EXCHANGE_BAN": str,
        "RENEWAL_BAN": str,
    }
    chunks = pd.read_csv(
        filepath,
        sep=";",
        engine="python",
        encoding="utf-8",
        encoding_errors="ignore",
        on_bad_lines="warn",
        converters=dict.fromkeys(hash_cols, hash_to_int),
        parse_dates=date_cols,
        dtype=dtypes,
        chunksize=10000,
    )
    return chunks

def read_delivery_data(filepath):
    """Read drug delivery data in chunks"""
    hash_to_int = partial(int, base=16)
    hash_cols = [
        "CDA_ID_MD5HASH",
        "DOC_GROUP_MD5HASH",
        "CDA_ADDENDUM_REF_MD5HASH",
        "CDA_RPLC_ID_MD5HASH",
    ]
    date_cols = ["CREATION_DATE"]
    dtypes = {
        "PATIENT_ID": str,
        "DRUG_NAME_C": str,
        "DOSE_QUANTITY_TEXT": str,
        "ATC_CODE": str,
        "MED_EXCHANGED": str,
        "DIS_AMOUNT_CALC_TXT": str,
        "DIS_AMT_VALUE": str,
        "DIS_AMOUNT_TXT": str,
        "DIS_AMT_UNIT": str,
        "PRODUCT_CODE1": str,
        "DOSE_DISTRIBUTION": str,
        "PREPARATION_TYPE_CODE": float,
        "RESEPTISTATUS": str,
        "LAAKEMUOTOKOODI": float,
        "DELIVERY_FEE": float,
    }
    chunks = pd.read_csv(
        filepath,
        sep=";",
        engine="python",
        encoding="utf-8",
        encoding_errors="ignore",
        on_bad_lines="warn",
        decimal=",",
        converters=dict.fromkeys(hash_cols, hash_to_int),
        parse_dates=date_cols,
        dtype=dtypes,
        chunksize=10000,
    )
    return chunks

def get_output_filepath(input_filepath):
    """Get output filepath from input filepath."""
    input_filename = os.path.basename(input_filepath)
    today = datetime.today().strftime("%Y-%m-%d")
    pattern = r"^107_522_2021_(.{2})_(\d{4})\.csv\.finreg_IDs"
    filetype, year = re.findall(pattern, input_filename, re.IGNORECASE)[0]
    filetype = "prescriptions" if filetype == "LM" else "deliveries"
    output_filename = filetype + "_" + year + "_" + today + ".csv"
    output_path = KELA_KANTA_OUTPUT_DIR / output_filename
    return output_path

def write_chunk_to_csv(chunk, output_filepath):
    """Writes chunk to csv"""
    chunk.to_csv(
        output_filepath,
        mode="a",
        header=not os.path.exists(output_filepath),
        index=False,
        sep=";",
    )

if __name__ == "__main__":

    # Preprocess drug prescriptions
    prescription_files = KELA_KANTA_INPUT_DIR.glob("107_522_2021_LM_*")
    for prescription_file in prescription_files:
        print(prescription_file)
        output_filepath = get_output_filepath(prescription_file)
        chunks = read_prescription_data(prescription_file)
        for chunk in chunks:
            chunk = chunk.replace("\n", " ", regex=True)
            write_chunk_to_csv(chunk, output_filepath)

    # Preprocess drug deliveries
    delivery_files = KELA_KANTA_INPUT_DIR.glob("107_522_2021_LT_*")
    for delivery_file in delivery_files:
        print(delivery_file)
        output_filepath = get_output_filepath(delivery_file)
        chunks = read_delivery_data(delivery_file)
        for chunk in chunks:
            chunk = chunk.replace("\n", " ", regex=True)
            write_chunk_to_csv(chunk, output_filepath)


import os
import boto3
from elasticsearch import Elasticsearch
from unittest import TestCase
from me_articles_drafts_delete import MeArticlesDraftsDelete
from tests_util import TestsUtil

class TestMeArticlesDraftsDelete(TestCase):
    dynamodb = boto3.resource('dynamodb', endpoint_url='http://localhost:4569/')
    elasticsearch = Elasticsearch(
        hosts=[{'host': 'localhost'}]
    )

    @classmethod
    def setUpClass(cls):
        TestsUtil.set_all_tables_name_to_env()
        os.environ['DOMAIN'] = 'example.com'

        cls.article_info_table = cls.dynamodb.Table('ArticleInfo')
        cls.article_content_table = cls.dynamodb.Table('ArticleContent')
        cls.article_content_edit_table = cls.dynamodb.Table('ArticleContentEdit')
        cls.article_history_table = cls.dynamodb.Table('ArticleHistory')
        cls.tag_table = cls.dynamodb.Table('Tag')

    def setUp(self):
        TestsUtil.delete_all_tables(self.dynamodb)

        article_info_items = [
            {
                'article_id': 'draftId00001',
                'user_id': 'test01',
                'status': 'draft',
                'tags': ['a', 'b', 'c'],
                'eye_catch_url': 'https://' + os.environ['DOMAIN'] + '/00001.png',
                'sort_key': 1520150272000000,
                'version': 2
            },
            {
                'article_id': 'draftId00002',
                'user_id': 'test01',
                'status': 'public',
                'sort_key': 1520150272000000,
                'version': 2
            }
        ]
        TestsUtil.create_table(self.dynamodb, os.environ['ARTICLE_INFO_TABLE_NAME'], article_info_items)

    def tearDown(self):
        TestsUtil.delete_all_tables(self.dynamodb)

    def assert_bad_request(self, params):
        me_articles_drafts_publish_with_header = MeArticlesDraftsDelete(params, {}, dynamodb=self.dynamodb)
        response = me_articles_drafts_publish_with_header.main()

        self.assertEqual(response['statusCode'], 400)

    def test_main_ok(self):
        params = {
            'pathParameters': {
                'article_id': 'draftId00001'
            },
            'requestContext': {
                'authorizer': {
                    'claims': {
                        'cognito:username': 'test01',
                        'phone_number_verified': 'true',
                        'email_verified': 'true'
                    }
                }
            }
        }

        response = MeArticlesDraftsDelete(params, {}, dynamodb=self.dynamodb).main()

        self.assertEqual(response['statusCode'], 200)

        article_info = self.article_info_table.get_item(Key={'article_id': params['pathParameters']['article_id']})['Item']
        self.assertEqual(article_info['status'], 'delete')

    def test_main_ng_with_public_article(self):
        params = {
            'pathParameters': {
                'article_id': 'publicId00002'
            },
            'requestContext': {
                'authorizer': {
                    'claims': {
                        'cognito:username': 'test01',
                        'phone_number_verified': 'true',
                        'email_verified': 'true'
                    }
                }
            }
        }

        response = MeArticlesDraftsDelete(params, {}, dynamodb=self.dynamodb).main()

        self.assertEqual(response['statusCode'], 400)

    def test_validation_with_no_article_id(self):
        params = {
            'queryStringParameters': {},
            'requestContext': {
                'authorizer': {
                    'claims': {
                        'cognito:username': 'test01',
                        'phone_number_verified': 'true',
                        'email_verified': 'true'
                    }
                }
            }
        }

        self.assert_bad_request(params)

    def test_validation_article_id_max(self):
        params = {
            'queryStringParameters': {
                'article_id': 'A' * 13,
            },
            'requestContext': {
                'authorizer': {
                    'claims': {
                        'cognito:username': 'test01',
                        'phone_number_verified': 'true',
                        'email_verified': 'true'
                    }
                }
            }
        }

        self.assert_bad_request(params)

    def test_validation_article_id_min(self):
        params = {
            'queryStringParameters': {
                'article_id': 'A' * 11,
            },
            'requestContext': {
                'authorizer': {
                    'claims': {
                        'cognito:username': 'test01',
                        'phone_number_verified': 'true',
                        'email_verified': 'true'
                    }
                }
            }
        }

        self.assert_bad_request(params)


import time
import json
import requests
import datetime
import math
import sys

from pprint import pprint

s_time = time.time()
path = sys.argv[0].replace('c_timer.py', '')

# скважина качает 4м3/ч или 4000л/ч охватывая 10соток или 1000м2, т.е. за час получается 4л/м2 или 4мм

with open(path+'json/const_zones.json') as f:
  rf = json.load(f)
pprint(rf)
zones = rf['zones']

start_h_watering = rf['start_h_watering']

'''
{
"zones": [
    {"name": "z1",                          # номер/имя зоны полива
    "gpio": "14",                           # gpio esp zone
    "norm": 3,                              # норма суточного полива мм/м2
    "http_esp": "http://192.168.0.54:84"},  # http_esp, возможно подлл. нескольких esp
    {"name": "z2",
    "gpio": "12",
    "norm": 3,
    "http_esp": "http://192.168.0.54:84"}],
"start_h_watering": 19                      # час начала полива
}
'''

city_openweather = 'Kiev'
api_openweather = 'your_api_key'

#     текущая погода http://api.openweathermap.org/data/2.5/weather?q=Kiev&APPID=your_api_key&units=metric
#     прогноз погоды http://api.openweathermap.org/data/2.5/forecast?q=Kiev&APPID=your_api_key&units=metric
data_weather = requests.get('http://api.openweathermap.org/data/2.5/forecast?q='+city_openweather+'&APPID='+api_openweather+'&units=metric')
weather = data_weather.json()['list']

today = datetime.datetime.today().strftime('%Y-%m-%d %H:%M')
print(today)

cur_time = round(time.time())
print(cur_time)

# считаем суточное количество осадков
day_rain = 0
for d in weather:
    if d['dt'] <= (cur_time+24*60*60) and 'rain' in d:
        print(d['rain'])
        if '3h' in d['rain']: day_rain += d['rain']['3h']

print("day_rain = ", day_rain)
rf.update({"day_rain":day_rain})

temp_time = 0
for z in rf['zones']:
    watering = z["norm"] - day_rain
    if watering > 0:
        h = round(watering/4-watering/4*100%25/100, 2)            # необходимое время полива в часах до сотых
        start_time = round(start_h_watering+temp_time, 2)
        end_time = round(start_h_watering+temp_time+h, 2)
        temp_time += h
        z.update({"watering": [start_time, end_time]})
rf.update({"date":today})
pprint(rf)

with open(path+'json/timer.json', 'w') as outfile:
    json.dump(rf, outfile)

print("--- %s seconds ---" % (time.time() - s_time))


from coroutine import coroutine
@coroutine
def grep(pattern):
    print('looking for %s pattern' % pattern)
    try:
        while True:
            line = (yield)
            if pattern in line:
                print(line)
    except GeneratorExit: # run when g.close() is called
        print('Going away, Good bye')

if __name__ == "__main__":
    g = grep('python')
    g.send('Yeah, but no, but yeah, but no')
    g.send('A series of tubes"')
    g.send('python generators rock!')
    g.close()
    g.throw(RuntimeError,"you're are hosed") #can also throw error


from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By

class check_box_single():
    def __init__(self):
        self.driver = webdriver.Chrome('./chromedriver')
        self.driver.implicitly_wait(10)
        self.driver.get("https://www.seleniumeasy.com/test/basic-checkbox-demo.html")
        self.driver.maximize_window()
    def push_button(self):
        button = self.driver.find_element_by_xpath("//*[@id=\"isAgeSelected\"]")
        self.driver.execute_script("arguments[0].click();", button)

    def extract_text(self):
        elements = self.driver.find_element(By.ID, 'txtAge')
        msg2 = str(elements.text)
        return msg2

    def validation(self, msg2):
        if msg2:
            print('Avem afisare')
            if 'Success' in msg2:
                return True
            else:
                return False
        else:
            return False
def msj_check(driver):
    button = driver.find_element_by_xpath("//*[@id=\"isAgeSelected\"]")
    driver.execute_script("arguments[0].click();", button)
    elements = driver.find_element(By.ID, 'txtAge')

    msg2 = str(elements.text)
    if msg2:
        print('Avem afisare')
        if 'Success' in msg2:
            print('Contine')
            print(msg2)
        else:
            print("Afisare incorecta!")
    else:
        print ('False')

ob = check_box_single()
ob.push_button()
msg2 = ob.extract_text()
print(ob.validation(msg2))


from .base_source import BaseSource
import numpy as np

class LineSource(BaseSource):
    def __init__(self, source_params):
        super().__init__(source_params)
        self.x = source_params['x_start']
        self.y1 = source_params['y_start']
        self.y2 = source_params['y_end']

        if self.function == 'gaussian':
            self.amplitude = source_params['amplitude']
            self.t0 = source_params.get('t0', 0)
            self.frequency_center = float(source_params['frequency_center'])
            self.frequency_width = float(source_params['frequency_width'])
            self.sigma_f = self.frequency_width / (2.0 * np.sqrt(2 * np.log(2)))
            self.sigma_t = 1 / (2 * np.pi * self.sigma_f)
            self.omega = 2.0 * np.pi * self.frequency_center
        elif self.function == 'sinusoidal':
            self.frequency = float(source_params['frequency'])
            self.omega = 2.0 * np.pi * self.frequency
        else:
            raise ValueError(f"Unsupported function type: {self.function}")

    def update_source(self, time, dt, ez):
        if self.function == 'gaussian':
            ez[self.x, self.y1:self.y2] = self.amplitude * np.exp(-((time - self.t0) ** 2) / (2 * self.sigma_t ** 2)) * \
                                            np.sin(self.omega * (time-self.t0))
        elif self.function == 'sinusoidal':
            ez[self.x, self.y1:self.y2] = np.sin(self.omega * time)
        else:
            raise ValueError(f"Unsupported function type: {self.function}")

    def __str__(self):
        base_str = super().__str__()
        if self.function == 'gaussian':
            return f"{base_str}, source_x: {self.source_x}, source_y: {self.source_y}, amplitude: {self.amplitude}, t0: {self.t0}, frequency center: {self.frequency_center}, frequency width: {self.frequency_width}"
        elif self.function == 'sinusoidal':
            return f"{base_str}, x: {self.x}, y1: {self.y1}, y2: {self.y2}, frequency: {self.frequency}, omega: {self.omega}"


class Calci():
    def __init__(self, tokens):
        self._tokens = tokens
        self._current = tokens[0]

    def expression(self):
        eq_result = self.term()
        while self._current is '+':
            self.next()
            eq_result += self.term()
            print(result)
        while self._current is '-':
            self.next()
            eq_result -= self.term()
        return eq_result

    def factor(self):
        eq_result = None
        if self._current.isdigit():
            eq_result = float(self._current)
            self.next()
        elif self._current is '(':
            self.next()
            eq_result = self.expression()
            self.next()
        return eq_result

    def next(self):
        self._tokens = self._tokens[1:]
        self._current = self._tokens[0] if len(self._tokens) > 0 else None

    def term(self):
        eq_result = self.factor()
        while self._current is '*':
            self.next()
            eq_result *= self.factor()
        while self._current is '/':
            self.next()
            eq_result /= self.factor()
        return eq_result

if __name__ == '__main__':
    while True:
        print("please enter your calculation expression")
        my_list = list(input('> '))
        tokens = []
        real_tokens = []
        for i in range(len(my_list)):
            if my_list[i].isdigit() and len(tokens) > 0 and tokens[-1].isdigit():
                tokens[-1] += my_list[i]
            else:
                tokens.append(my_list[i])
        for ext_space in tokens:
            if ext_space != " ":
                real_tokens.append(ext_space)
        print (Calci(real_tokens).expression() )


import netCDF4 as netCDF
from extraction_utils import basic, getCoordinateVariable
import json
import matplotlib.pyplot as plt
import decimal
import numpy as np
import traceback

class ImageStats(object):
	"""docstring for ImageStats"""
	def __init__(self, filename, variable):
		super(ImageStats, self).__init__()
		self.filename = filename
		self.variable = variable

	def process(self):
		#print "running basic processing on %s" % self.filename
		# create three arrays, 1D lat 1D lon 2D data
		#print "processing image"
		netcdf_file = netCDF.Dataset(self.filename, "r")
		#variable = np.ma.masked_array(netcdf_file.variables[self.variable])
		variable = np.ma.array(netcdf_file.variables[self.variable][:])

		lats = getCoordinateVariable(netcdf_file, "Lat")
		lons = getCoordinateVariable(netcdf_file, "Lon")
		time_dim_index = netcdf_file.variables[self.variable].dimensions.index('time')
		if 'depth' in netcdf_file.variables[self.variable].dimensions:
			depth_dim_index = netcdf_file.variables[self.variable].dimensions.index('depth')
		var_list = []
		lat_list = []
		lon_list = []
		#print variable.shape
		if(len(variable.shape) > 3 ):
			#print "hmmmm"
			#print variable.shape
			#print variable
			#print np.nanmean(variable, axis=time_dim_index).shape

			var_list = [[float(x) if not np.isinf(x) and not np.isnan(x) else None for x in y  ] for y in np.nanmean(variable, axis=time_dim_index)[0]]
			#print var_list
			lat_list = [float(x) for x in lats]
			lon_list = [float(x) for x in lons]
		elif(len(variable.shape) > 2 ):
			#print variable.shape
			#print variable
			#print np.nanmean(variable, axis=time_dim_index)
			var_list = [[float(x) if not np.isinf(x) and not np.isnan(x) else None for x in y  ] for y in np.nanmean(variable, axis=time_dim_index)]
			#var_list = [[float(x) for x in y] for y in variable[0]]
			#print var_list
			lat_list = [float(x) for x in lats]
			lon_list = [float(x) for x in lons]
		else:
			var_list = [list(x) for x in variable]
			lat_list = [float(x) for x in lats]
			lon_list = [float(x) for x in lons]

		#print len(lat_list)
		#print len(lon_list)
		#print len(var_list)
		#print len(var_list[0])
		#print lat_list
		_ret = {}
		_ret['vars'] = ['Data','Latitudes','Longitudes']
		_ret['data'] = []
		_ret['data'].append(var_list)
		_ret['data'].append(lat_list)
		_ret['data'].append(lon_list)
		#print json.dumps(_ret )
		return json.dumps(_ret )

		#netcdf_variable = netcdf_file[variable]


import os
import shutil
import time
import configparser

from PIL import Image

STEP = 10

# from lib.utils import Id2name

# INPUT_DIR = r"data/MH_01_easy/mav0/cam0/data"
# OUTPUT_DIR = r"./imgs"

config = configparser.ConfigParser()
config.read("config.ini", encoding="utf-8")
INPUT_DIR = config["DEFAULT"]["SIMULATOR_IMG_DIR"]
OUTPUT_DIR = config["DEFAULT"]["IMGS_FROM_SERVER"]

imgs = os.listdir(INPUT_DIR)
imgs.sort()

# for i in range (len(os.listdir(INPUT_DIR))):
#    shutil.copy("{}/output{}.jpg".format(INPUT_DIR, i), "{}/output{}.jpg".format(OUTPUT_DIR, i))
#    time.sleep(0.5)

##for i in range(140, len(os.listdir(INPUT_DIR))):
# for i in range(140, 300):
#    img = Id2name(i)
#    shutil.copy("{}/{}".format(INPUT_DIR, img), "{}/output{}.jpg".format(OUTPUT_DIR, i-1))
#    time.sleep(0.25)

# for i in range(0, 600):
#    shutil.copy("{}/img{}.jpg".format(INPUT_DIR, i), "{}/output{}.jpg".format(OUTPUT_DIR, i))
#    time.sleep(0.25)

### EuRoC Machine Hall
for i in range(0, 1000000, STEP):
    img = imgs[i]
    # shutil.copy("{}/{}".format(INPUT_DIR, img), "{}/output{}.jpg".format(OUTPUT_DIR, i))
    im = Image.open("{}/{}".format(INPUT_DIR, img))
    rgb_im = im.convert("RGB")
    rgb_im.save("{}/{}.jpg".format(OUTPUT_DIR, img[:-4]))  # jpg
    time.sleep(1)


"""Apply Perl::Critic tool and gather results."""
import argparse
import logging
import subprocess
from typing import List, Optional

from statick_tool.issue import Issue
from statick_tool.package import Package
from statick_tool.tool_plugin import ToolPlugin

class PerlCriticToolPlugin(ToolPlugin):
    """Apply Perl::Critic tool and gather results."""

    def get_name(self) -> str:
        """Get name of tool."""
        return "perlcritic"

    def gather_args(self, args: argparse.Namespace) -> None:
        """Gather arguments."""
        args.add_argument(
            "--perlcritic-bin",
            dest="perlcritic_bin",
            type=str,
            help="perlcritic binary path",
        )

    def get_file_types(self) -> List[str]:
        """Return a list of file types the plugin can scan."""
        return ["perl_src"]

    def process_files(
        self, package: Package, level: str, files: List[str], user_flags: List[str]
    ) -> Optional[List[str]]:
        """Run tool and gather output."""
        perlcritic_bin = "perlcritic"
        if self.plugin_context and self.plugin_context.args.perlcritic_bin is not None:
            perlcritic_bin = self.plugin_context.args.perlcritic_bin

        flags = ["--nocolor", "--verbose=%f:::%l:::%p:::%m:::%s\n"]
        flags += self.get_user_flags(level)

        try:
            output = subprocess.check_output(
                [perlcritic_bin] + flags + files,
                stderr=subprocess.STDOUT,
                universal_newlines=True,
            ).join(" ")

        except subprocess.CalledProcessError as ex:
            output = ex.output
            if ex.returncode != 2:
                logging.warning("perlcritic failed! Returncode = %d", ex.returncode)
                logging.warning("%s exception: %s", self.get_name(), ex.output)
                return []

        except OSError as ex:
            logging.warning("Couldn't find %s! (%s)", perlcritic_bin, ex)
            return []

        logging.debug("%s", output)
        return output.splitlines()

    def parse_output(
        self, total_output: List[str], package: Optional[Package] = None
    ) -> List[Issue]:
        """Parse tool output and report issues."""
        issues: List[Issue] = []
        # Load the plugin mapping if possible
        warnings_mapping = self.load_mapping()
        for line in total_output:
            split_line = line.strip().split(":::")
            # Should split into five segments, anything less is invalid.
            if len(split_line) < 5:
                continue
            cert_reference = None
            if split_line[2].replace("::", "__") in warnings_mapping:
                cert_reference = warnings_mapping[split_line[2].replace("::", "__")]

            issues.append(
                Issue(
                    split_line[0],
                    split_line[1],
                    self.get_name(),
                    split_line[2],
                    split_line[4],
                    split_line[3],
                    cert_reference,
                )
            )

        return issues


from django.db import models

class ShowManager(models.Manager):
    def basic_validator(self, postData):
        errors = {}
        if len(postData['show_title']) < 2:
            errors["show_title"] = "Show title should be at least 2 characters!"
        if len(postData['show_network']) < 3:
            errors["show_network"] = "Network should be at least 3 characters"
        if len(postData['show_description']) < 10:
            errors["show_description"] = "description should be at least 10 characters"
        return errors

class Show(models.Model):
    title = models.CharField(max_length=255)
    network = models.CharField(max_length=30)
    release_date = models.CharField(max_length=10, null=True)
    description = models.TextField(null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    objects = ShowManager()


from common import *
def updateaddr():
	rent = Mydb()
	items = ['id', 'title', 'addr', 'area', 'city']
	table = 'rent58'
	updatelnglat = 0
	updateaddr = 0

	rent.select(table, items, None)
	records = rent.cur.fetchall()
	for record in records:
		id, title, addr, area, city = record
		condition = dict(id=id)
		taddr = title.split()[0]
		addr = area+addr
		for area in (taddr, addr):
			url = lnglat % (area, city)
			result = getapi(url)
			if result['status'] == 0:
				result = result['result']['location']
				lng = result['lng']
				lat = result['lat']
				rent.update(table, dict(lnglat=str(lng)+','+str(lat)), condition)
				updatelnglat += 1

				#update address
				url = location % (lng, lat)
				result = getapi(url)
				addr = result['result']['formatted_address']
				if addr:
					rent.update(table, dict(addr=addr), condition)
					updateaddr += 1
				break
			elif result['status'] == 302:
				print(result['message'])
				exit()

	print('updated %s records of lng and lat, %s records of address' % (updatelnglat, updateaddr))

if __name__ == '__main__':
	updateaddr()


#!/usr/bin/env python

from graph import DiGraph, before_after_calculations
import os
import json
import threading
import random
from datetime import date

def read_graphml_files():
    with open('tmp/interesting_graphs.txt') as fh:
        lines = [line.rstrip() for line in fh]

    return [(line, DiGraph.from_graphml(f"graphml/{line}")) for line in lines]

def process_graph(name, G, results):
    print(f"-- Processing graph {name}")
    rand_ports = [random.randrange(1, 65535) for i in range(50)]
    G_simulation, G_attack, stats = G.simulate_traffic(amount_of_rules=50, rand_ports=rand_ports)
    print("Finished processing")

    results.append(
        (
            before_after_calculations(
                f"{name} simulated",
                f"{name} simulated + attack",
                G_simulation,
                G_attack
            ),
            stats
        )
    )

def main():
    graphs = read_graphml_files()
    thread_list = []
    results = []

    for name, graph in graphs:
        thread = threading.Thread(target=process_graph, args=(name, graph, results))
        thread_list.append(thread)

    for thread in thread_list:
        thread.start()

    for thread in thread_list:
        thread.join()

    filename = f"networks_simulation_results_{date.today()}.json"

    # Überprüfen, ob Datei bereits existiert
    i = 0
    while os.path.isfile(filename):
        i += 1
        filename = f"networks_simulation_results_{date.today()}.{i}.json"

    # results = [process_graph(name, graph) for name, graph in graphs]
    with open(f"tmp/{filename}", 'a') as fh:
        fh.write(json.dumps(results))

if __name__ == "__main__":
    main()


from setuptools import setup, find_packages

VERSION = '0.0.19'
DESCRIPTION = 'ParkingLot is a Python service imitating a parking lot like system.'
LONG_DESCRIPTION = 'The service indicates rather a vehicle allowed or not allowed to enter the parking lot.'

# Setting up
setup(
    name="parkinglot",
    version=VERSION,
    author="PsychoRover",
    description=DESCRIPTION,
    long_description_content_type="text/markdown",
    long_description=LONG_DESCRIPTION,
    packages=find_packages(),
    install_requires=['psycopg2', 'ocrspace'],
    keywords=['python', 'parking', 'lot', 'moon', 'parkinglot'],
    classifiers=[
        "Development Status :: 1 - Planning",
        "Intended Audience :: Developers",
        "Programming Language :: Python :: 3",
        "Operating System :: Unix",
        "Operating System :: MacOS :: MacOS X",
        "Operating System :: Microsoft :: Windows",
    ]
)


import sys,re, os, io, codecs
from _collections import defaultdict

def loadModelfile():
    modelfile = sys.argv[1]
    features = defaultdict()

    #load model file into features
    with open(modelfile,"r", encoding = "ISO-8859-1") as modelhandler:
        model = modelhandler.readlines()
        for cldata in model:
            cldata = cldata.strip()
            cldata = cldata.split(" ")
            clname = cldata[0]
            cldata = cldata[1:]
            weights = defaultdict(float)
            for ft in cldata:
                ft = ft.split("=|")
                weights[ft[0]] = float(ft[1])
            features[clname] = weights

    input_stream = io.TextIOWrapper(sys.stdin.buffer,encoding = "ISO-8859-1")
    calculate_accuracy(input_stream,features)

def calculate_accuracy(lines,features):

    for line in lines:

        output=""
        line = line.strip()

        line = " ".join(line.split())

        data = line.split(" ")
        length = len(data)

        bos = "*BOS*"
        eos = "*EOS*"

        prevpos = bos
        prev2pos= bos
        prevclass= bos
        prev2class=bos

        i=0
        while(i<length):

            word = data[i]
            pos = word.rfind("/")
            postag = word[pos+1:]
            crnt = word[:pos]

            if(i==length-1):
                next =eos
                nextpos=eos
            else:
                nextdata = data[i+1]
                rpos = nextdata.rfind("/")
                nextpos = nextdata[rpos+1:]
                next = nextdata[:rpos]

            wshape = wordshape(crnt)

            ftarray = ["crnt|"+crnt, "crntpos|"+postag, "prevpos|"+prevpos,
                       "prevcls|"+prevclass, "prev2pos|"+prev2pos,"prev2cls|"+prev2class,
                       "next|"+next, "nextpos|"+nextpos, "wshape|"+wshape]

            scores = defaultdict()
            for key in features.keys():
                score = calculateScore(ftarray,features[key])
                scores[key]=score

            predClass = max(scores.keys(), key=(lambda key: scores[key] ))

            if(next == eos):
                prev2pos = bos
                prevpos= bos
                prevclass = bos
                prev2class = bos
            else:
                prev2pos = prevpos
                prev2class = prevclass
                prevpos = postag
                prevclass = predClass
            output+=word+"/"+predClass+" "

            #calculate Fscore and accuracy

            i+=1
        output=output.strip()+ os.linesep
        sys.stdout.write(output)
        sys.stdout.flush()

def wordshape(word):
    wshape = word
    wshape = re.sub("[A-Z]+","A",wshape)
    wshape = re.sub("[a-z]+","a",wshape)
    wshape = re.sub("[0-9]+","0",wshape)
    wshape = re.sub("[^A-Za-z0-9]+","_",wshape)
    return wshape

def calculateScore(data,weightVector):
    score = 0.0
    for ft in data:
        if(ft in weightVector.keys()):
            score+=weightVector[ft]
    return score

loadModelfile()


import os
import testinfra.utils.ansible_runner
import pytest

testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
    os.environ['MOLECULE_INVENTORY_FILE']
).get_hosts('all')

@pytest.mark.parametrize("name", [
    ("apt-transport-https"),
    ("software-properties-common"),
    ("unattended-upgrades"),
    ("mailutils"),
    ("bsd-mailx"),
])
def test_default_packages(host, name):
    pkg = host.package(name)
    assert pkg.is_installed

def test_default_config_files_present(host):
    f = host.file("/etc/apt/apt.conf.d/50unattended-upgrades")
    assert f.exists
    assert f.is_file


from tkinter import *
from tkinter import messagebox
from tkinter import ttk
from modelo import (
    FuncionalidadRecetas,
    FuncionalidadSemanas,
    FuncionalidadConfiguracion,
)
from pdf import crear
from modelo import Recetas, Configuracion
import tkinter

class VistaApp:
    def ventana_volver(ventana):
        ventana.destroy()
        VistaApp.ventana_principal()

    def ventana_principal():

        #########################################
        # VENTANA PRINCIPAL
        ##########################################
        ventana = Tk()
        ventana.title("Comedere Club")
        ventana.config(width=230, height=220)
        ventana.resizable(width=FALSE, height=FALSE)
        ventana.iconphoto(False, tkinter.PhotoImage(file="trebol.ico"))

        dec1 = Label(ventana, width=60, bg="olive drab2")
        dec1.place(x=0, y=210)

        ### LABELS
        # TITULO
        lbl_titulo = Label(
            ventana,
            text="🍀 Comedere Club",
            width=19,
            font=("Segoe Print", 14),
            bg="olive drab2",
        )
        lbl_titulo.place(x=0, y=10)

        ### BOTONES
        # BOTON PARA VER LAS RECETAS
        btn_recetas = Button(ventana, text="Recetas", bd=5, font=("Gadugi", 14))
        btn_recetas.place(x=67, y=60)
        btn_recetas.config(command=lambda: VistaApp.ventana_recetas(ventana))

        # BOTON PARA VER MENU SEMANAL
        btn_semana = Button(ventana, text="Menu Semanal", bd=5, font=("Gadugi", 12))
        btn_semana.place(x=48, y=120)
        btn_semana.config(command=lambda: VistaApp.ventana_semanas(ventana))

        # BOTON PARA VER MENU SEMANAL
        btn_configuracion = Button(
            ventana, text="Configuración", bd=2, font=("Gadugi", 8)
        )
        btn_configuracion.place(x=7, y=180)
        btn_configuracion.config(
            command=lambda: VistaApp.ventana_configuracion(ventana)
        )

        ventana.mainloop()

        ####################################
        # VENTANA RECETAS
        ####################################

    def ventana_recetas(ventana_prin):

        ventana_prin.destroy()
        ## VENTANA RECETAS
        ventana = Tk()
        ventana.title("Comedere Club")
        ventana.protocol("WM_DELETE_WINDOW", lambda: VistaApp.ventana_volver(ventana))
        ventana.config(width=490, height=400)
        ventana.resizable(width=FALSE, height=FALSE)
        ventana.iconphoto(False, tkinter.PhotoImage(file="trebol.ico"))

        ### LABELS
        # TITULO
        lbl_titulo = Label(
            ventana,
            text="🍀 Comedere Club / Recetas",
            width=33,
            font=("Segoe Print", 18),
            bg="olive drab2",
        )
        lbl_titulo.place(x=0, y=5)

        # TOTAL DE RECETAS AGREGADAS
        lbl_recetas = Label(ventana, font=("Gadugi", 12), bg="olive drab2")
        lbl_recetas.place(x=15, y=369)

        # MOSTRAR TOTAL DE RECETAS AGREGADAS
        def mostrar_total():
            resultado = 0
            for x in Recetas.select():
                resultado = resultado + 1

            lbl_recetas.config(text="Recetas guardadas: " + str(resultado) + " 🍀")
            lbl_recetas.after(800, mostrar_total)

        mostrar_total()

        # FORMATO ULTIMA VEZ
        lbl_formato = Label(ventana, text="dd/mm/aaaa", font=("Gadugi", 8))
        lbl_formato.place(x=400, y=165)

        # LABEL PARA BORRAR
        lbl_borrar = Label(ventana, text="ID de la receta ▲", font=("Gadugi", 8))
        lbl_borrar.place(x=381, y=245)

        ### ENTRYS
        # ENTRY PARA AGREGAR RECETAS
        entry_agregar = Entry(ventana, width=24, bg="snow3")
        entry_agregar.place(x=15, y=105)

        # ENTRY PARA BUSCAR RECETAS
        entry_buscar = Entry(ventana, width=24, bg="snow3")
        entry_buscar.place(x=330, y=105)

        # ENTRY PARA BORRAR
        entry_borrar = Entry(ventana, width=4, bg="snow3")
        entry_borrar.place(x=450, y=223)

        ### BOTONES
        # BOTON PARA AGREGAR RECETAS
        btn_agregar = Button(ventana, text="Agregar recetas", bd=5, font=("Gadugi", 12))
        btn_agregar.place(x=24, y=60)
        btn_agregar.config(
            command=lambda: FuncionalidadRecetas.agregar_receta(
                str.lower(entry_agregar.get()), entry_agregar
            )
        )

        # BOTON PARA BUSCAR RECETAS
        btn_buscar = Button(ventana, text="Buscar...", bd=5, font=("Gadugi", 12))
        btn_buscar.place(x=370, y=60)
        btn_buscar.config(
            command=lambda: FuncionalidadRecetas.buscar_recetas(
                str.lower(entry_buscar.get()),
                recetas.get(),
                ult_vez.get(),
                entry_borrar,
                treeview,
            )
        )

        # BOTON PARA BORRAR RECETAS
        btn_borrar = Button(ventana, text="Borrar", bd=5, font=("Gadugi", 12))
        btn_borrar.place(x=380, y=205)
        btn_borrar.config(
            command=lambda: FuncionalidadRecetas.borrar_receta(
                str.lower(entry_borrar.get()), entry_borrar, treeview
            )
        )

        # BOTON PARA MOSTRAR RECETAS
        btn_mostrar = Button(ventana, text="Mostrar Recetas", bd=5, font=("Gadugi", 10))
        btn_mostrar.place(x=375, y=290)
        btn_mostrar.config(
            command=lambda: FuncionalidadRecetas.mostrar_recetas(treeview)
        )

        # BOTON PARA VOLVER
        btn_volver = Button(ventana, text="Volver", bd=2, font=("Gadugi", 10))
        btn_volver.place(x=440, y=370)
        btn_volver.config(command=lambda: VistaApp.ventana_volver(ventana))

        ### CHECK BOX
        recetas = IntVar()
        check_recetas = Checkbutton(
            ventana,
            variable=recetas,
            onvalue=1,
            offvalue=0,
            text="Receta",
            command=lambda: checks(check_ult_vez, recetas.get()),
        )
        check_recetas.place(x=380, y=125)

        ult_vez = IntVar()
        check_ult_vez = Checkbutton(
            ventana,
            variable=ult_vez,
            onvalue=1,
            offvalue=0,
            text="Ultima vez",
            command=lambda: checks(check_recetas, ult_vez.get()),
        )
        check_ult_vez.place(x=380, y=145)

        def checks(check, var):
            check.config(state=DISABLED)
            if var == 0:
                check.config(state=NORMAL)

        # TREEVIEW PARA VER RECETAS AGREGADAS
        style = ttk.Style(ventana)
        style.theme_use("clam")
        style.configure("Treeview", foreground="white")

        treeview = ttk.Treeview(ventana)
        treeview["columns"] = ("ID", "Receta", "Ultima vez hecha")
        treeview.column("#0", width=0, stretch=NO)
        treeview.column(
            "ID",
            width=40,
            anchor=CENTER,
        )
        treeview.column(
            "Receta",
            width=233,
            anchor=CENTER,
        )
        treeview.column(
            "Ultima vez hecha",
            width=80,
            anchor=CENTER,
        )

        treeview.heading("#0", text="", anchor=CENTER)
        treeview.heading("ID", text="ID", anchor=CENTER)
        treeview.heading("Receta", text="Receta", anchor=CENTER)
        treeview.heading("Ultima vez hecha", text="Ultima vez hecha", anchor=CENTER)

        treeview.place(x=15, y=130)

        ventana.mainloop()

        ##############################################
        # VENTANA SEMANAS
        ##############################################

    def ventana_semanas(ventana_prin):

        ventana_prin.destroy()
        ## VENTANA SEMANAS
        ventana = Tk()
        ventana.title("Comedere Club")
        ventana.protocol("WM_DELETE_WINDOW", lambda: VistaApp.ventana_volver(ventana))
        ventana.config(width=670, height=320)
        ventana.resizable(width=FALSE, height=FALSE)
        ventana.iconphoto(False, tkinter.PhotoImage(file="trebol.ico"))

        ### LABELS
        # TITULO
        lbl_titulo = Label(
            ventana,
            text="🍀 Comedere Club / Semanas",
            width=45,
            font=("Segoe Print", 18),
            bg="olive drab2",
        )
        lbl_titulo.place(x=0, y=5)

        ### ENTRYS
        # ENTRY NOMBRE DEL PDF
        entry_nombre = Entry(ventana, width=21, bg="snow3")
        entry_nombre.place(x=15, y=260)
        entry_nombre.insert(0, "Menu semanal")

        ### BOTONES

        # BOTON PARA VOLVER
        btn_volver = Button(ventana, text="Volver", bd=2, font=("Gadugi", 10))
        btn_volver.place(x=5, y=290)
        btn_volver.config(command=lambda: VistaApp.ventana_volver(ventana))

        # BOTON PARA MODIFICAR SEMANA
        btn_mod_semana = Button(
            ventana,
            text="Modificar la\nsemana marcada",
            bd=4,
            font=("Gadugi", 10),
            padx=7,
        )
        btn_mod_semana.place(x=15, y=140)
        btn_mod_semana.config(
            command=lambda: VistaApp.ventana_mod_semana(
                ventana, pasado.get(), presente.get(), futuro.get(), treeview
            )
        )
        btn_pdf = Button(
            ventana, text="Importar la semana\nactual a PDF", bd=4, font=("Gadugi", 10)
        )
        btn_pdf.place(x=15, y=200)
        btn_pdf.config(command=lambda: crear(str(entry_nombre.get())))

        ### CHECK BOX
        pasado = IntVar()
        check_pasado = Checkbutton(
            ventana, variable=pasado, onvalue=1, offvalue=0, text="Semana pasada"
        )
        check_pasado.config(
            command=lambda: [
                checks_semanas(check_presente, check_futuro, pasado.get()),
                FuncionalidadSemanas.mostrar_semana(
                    pasado.get(), presente.get(), futuro.get(), treeview
                ),
            ]
        )
        check_pasado.place(x=15, y=70)

        presente = IntVar()
        check_presente = Checkbutton(
            ventana, variable=presente, onvalue=1, offvalue=0, text="Semana actual"
        )
        check_presente.config(
            command=lambda: [
                checks_semanas(check_pasado, check_futuro, presente.get()),
                FuncionalidadSemanas.mostrar_semana(
                    pasado.get(), presente.get(), futuro.get(), treeview
                ),
            ]
        )
        check_presente.place(x=15, y=90)

        futuro = IntVar()
        check_futuro = Checkbutton(
            ventana, variable=futuro, onvalue=1, offvalue=0, text="Semana siguiente"
        )
        check_futuro.config(
            command=lambda: [
                checks_semanas(check_pasado, check_presente, futuro.get()),
                FuncionalidadSemanas.mostrar_semana(
                    pasado.get(), presente.get(), futuro.get(), treeview
                ),
            ]
        )
        check_futuro.place(x=15, y=110)

        def checks_semanas(check1, check2, var):
            check1.config(state=DISABLED)
            check2.config(state=DISABLED)
            if var == 0:
                check1.config(state=NORMAL)
                check2.config(state=NORMAL)

        # TREEVIEW PARA VER LAS SEMANAS
        style = ttk.Style(ventana)
        style.theme_use("clam")
        style.configure("Treeview", foreground="white")

        treeview = ttk.Treeview(ventana)
        treeview["columns"] = ("Dia", "Receta", "Que falta")
        treeview.column("#0", width=0, stretch=NO)
        treeview.column(
            "Dia",
            width=80,
            anchor=CENTER,
        )
        treeview.column(
            "Receta",
            width=223,
            anchor=CENTER,
        )
        treeview.column(
            "Que falta",
            width=180,
            anchor=CENTER,
        )

        treeview.heading("#0", text="", anchor=CENTER)
        treeview.heading("Dia", text="Dia", anchor=CENTER)
        treeview.heading("Receta", text="Receta", anchor=CENTER)
        treeview.heading("Que falta", text="Que falta", anchor=CENTER)

        treeview.place(x=170, y=70)

        ventana.mainloop()

        ##############################################
        # VENTANA MODIFICAR SEMANAS
        ##############################################

    def ventana_mod_semana(ventana_prin, pasado, presente, futuro, treeview):

        if pasado == 0 and presente == 0 and futuro == 0:
            messagebox.showinfo(
                message="Ninguna semana seleccionada", title="Comedere Club"
            )
            VistaApp.ventana_semanas(ventana)

        else:
            ventana_prin.withdraw()
            ## VENTANA MODIFICAR SEMANAS
            ventana = Tk()
            ventana.title("Comedere Club")
            ventana.protocol(
                "WM_DELETE_WINDOW",
                lambda: [ventana_prin.deiconify(), ventana.destroy()],
            )
            ventana.config(width=270, height=250)
            ventana.resizable(width=FALSE, height=FALSE)

            texto = ""
            if pasado == 1:
                texto = " Modificando la semana pasada ..."
            elif presente == 1:
                texto = " Modificando la semana actual ..."
            else:
                texto = " Modificando la semana siguiente ..."
            # LABEL PARA SABER QUE SEMANA ESTOY MODIFICANDO
            lbl_modificar = Label(
                ventana,
                text=(texto),
                anchor=W,
                width=43,
                font=("Gadugi", 12),
                bg="olive drab2",
            )
            lbl_modificar.place(x=0, y=10)

            ### LABELS
            # LABEL DIA
            lbl_dia = Label(
                ventana, text="Dia", width=9, font=("Gadugi", 8), bg="olive drab2"
            )
            lbl_dia.place(x=15, y=100)

            # LABEL RECETA
            lbl_receta = Label(
                ventana, text="Receta", width=9, font=("Gadugi", 8), bg="olive drab2"
            )
            lbl_receta.place(x=15, y=150)

            # LABEL DIA
            lbl_falta = Label(
                ventana,
                text="Que falta?",
                width=9,
                font=("Gadugi", 8),
                bg="olive drab2",
            )
            lbl_falta.place(x=15, y=200)

            ### ENTRYS
            # ENTRY DIA
            entry_dia = Entry(ventana, width=17, bg="snow3", state="readonly")
            entry_dia.place(x=35, y=125)

            # ENTRY RECETA
            entry_receta = Entry(ventana, width=20, bg="snow3")
            entry_receta.place(x=15, y=175)

            # ENTRY QUE FALTA
            entry_falta = Entry(ventana, width=20, bg="snow3")
            entry_falta.place(x=15, y=225)

            # BOTON PARA MODIFICAR ALGUNA RECETA
            btn_modificar = Button(ventana, text="Modificar", bd=5, font=("Gadugi", 12))
            btn_modificar.place(x=15, y=45)
            btn_modificar.config(
                command=lambda: FuncionalidadSemanas.modificar_semana(
                    pasado,
                    presente,
                    futuro,
                    entry_dia.get(),
                    str.lower(entry_receta.get()),
                    entry_falta.get(),
                    treeview,
                )
            )

            # ELEGIR RECETA ALEATORIAMENTE
            btn_random = Button(
                ventana, text="Elegir receta\naleatoriamente", bd=5, font=("Gadugi", 9)
            )
            btn_random.place(x=147, y=155)
            btn_random.config(
                command=lambda: FuncionalidadSemanas.receta_aleatoria(entry_receta)
            )

            # BOTON PARA VOLVER
            btn_dia = Button(ventana, text="Volver", bd=2, font=("", 10))
            btn_dia.place(x=220, y=220)
            btn_dia.config(
                command=lambda: [ventana_prin.deiconify(), ventana.destroy()]
            )

            # POPUP PARA AUTOCOMPLETAR EL DIA
            btn_dia = Button(ventana, text="▼", bd=5, font=("", 5))
            btn_dia.place(x=15, y=125)
            btn_dia.config(command=lambda: popup_mostrar())

            # MOSTRAR MENU POPUP
            def popup_mostrar():
                try:
                    popup_dia.tk_popup(x=200, y=300)
                finally:
                    popup_dia.grab_release()

            # OPCIONES DEL MENU POPUP
            popup_dia = Menu(ventana, tearoff=0)
            popup_dia.add_command(
                label="Lunes",
                command=lambda: [
                    normal(entry_dia),
                    borrar_entry(entry_dia),
                    entry_dia.insert(0, "Lunes"),
                    readonly(entry_dia),
                ],
            )
            popup_dia.add_command(
                label="Martes",
                command=lambda: [
                    normal(entry_dia),
                    borrar_entry(entry_dia),
                    entry_dia.insert(0, "Martes"),
                    readonly(entry_dia),
                ],
            )
            popup_dia.add_command(
                label="Miercoles",
                command=lambda: [
                    normal(entry_dia),
                    borrar_entry(entry_dia),
                    entry_dia.insert(0, "Miercoles"),
                    readonly(entry_dia),
                ],
            )
            popup_dia.add_command(
                label="Jueves",
                command=lambda: [
                    normal(entry_dia),
                    borrar_entry(entry_dia),
                    entry_dia.insert(0, "Jueves"),
                    readonly(entry_dia),
                ],
            )
            popup_dia.add_command(
                label="Viernes",
                command=lambda: [
                    normal(entry_dia),
                    borrar_entry(entry_dia),
                    entry_dia.insert(0, "Viernes"),
                    readonly(entry_dia),
                ],
            )

            def borrar_entry(entry):
                entry.delete(0, "end")

            def readonly(entry):
                entry.config(state="readonly")

            def normal(entry):
                entry.config(state="normal")

            ventana.mainloop()

    ##################
    ## VENTANA CONFIGURACION
    ##################

    def ventana_configuracion(ventana_prin):
        ventana_prin.destroy()

        ventana = Tk()
        ventana.title("Comedere Club")
        ventana.protocol("WM_DELETE_WINDOW", lambda: VistaApp.ventana_volver(ventana))
        ventana.config(width=195, height=150)
        ventana.resizable(width=FALSE, height=FALSE)
        ventana.iconphoto(False, tkinter.PhotoImage(file="trebol.ico"))

        lbl_titulo = Label(
            ventana,
            text="🍀 Configuración",
            width=16,
            font=("Segoe Print", 14),
            bg="olive drab2",
        )
        lbl_titulo.place(x=0, y=10)

        guardar_recetas = IntVar()
        check_recetas = Checkbutton(
            ventana,
            variable=guardar_recetas,
            onvalue=1,
            offvalue=0,
            text="Guardar recetas",
        )
        check_recetas.place(x=5, y=60)

        btn_dia = Button(ventana, text="❓", font=("", 8))
        btn_dia.place(x=150, y=60)
        btn_dia.config(
            command=lambda: messagebox.showinfo(
                title="Comedere Club",
                message="Cuando finalice la semana, las recetas que esten en la semana actual sin guardar, se agregaran automaticamente en el listado de recetas",
            )
        )

        btn_guardar = Button(ventana, text="Guardar y salir", font=("", 10))
        btn_guardar.place(x=45, y=120)
        btn_guardar.config(
            command=lambda: [
                FuncionalidadConfiguracion.configuraciones(guardar_recetas.get()),
                VistaApp.ventana_volver(ventana),
            ]
        )

        for x in Configuracion.select():
            if x.configuracion == 1 and x.id == 2:
                check_recetas.select()

        ventana.mainloop()


import numpy as np
import gym
import cv2

class StackedEnv(gym.Wrapper):
    def __init__(self, env, width, height, n_img_stack, n_action_repeats):
        super(StackedEnv, self).__init__(env)
        self.width = width
        self.height = height
        self.n_img_stack = n_img_stack
        self.n_action_repeats = n_action_repeats
        self.stack = []

    def reset(self):
        img_rgb = super(StackedEnv, self).reset()
        img_gray = self.preprocess(img_rgb)
        self.stack = [img_gray] * self.n_img_stack
        return np.rollaxis(np.stack(self.stack, axis=2), 2, 0)

    def step(self, action):
        total_reward = 0
        done = False
        img_rgb = None
        info = None
        for i in range(self.n_action_repeats):
            img_rgb, reward, done, info = super(StackedEnv, self).step(action)
            total_reward += reward
            if done:
                break
        img_gray = self.preprocess(img_rgb)
        self.stack.pop(0)
        self.stack.append(img_gray)
        assert len(self.stack) == self.n_img_stack
        return np.rollaxis(np.stack(self.stack, axis=2), 2, 0), total_reward, done, info

    def preprocess(self, rgb_img):
        gray = np.dot(rgb_img[..., :], [0.299, 0.587, 0.114])
        gray = gray / 128. - 1.
        res = cv2.resize(gray, dsize=(self.height, self.width), interpolation=cv2.INTER_CUBIC)
        return res


import little_helper

def paths(list):
    """
    >>> list(paths([[0],[1]]))
    [[0, 1]]
    >>> list(paths([[1, 2]]))
    [[1], [2]]
    >>> list(paths([[0],[1,2]]))
    [[0, 1], [0, 2]]
    """
    if len(list) > 0:
        lists = []
        for option in list[0]:
            for path in paths(list[1:]):
                lists.append([option] + path)
        return lists
    else:
        return [[]]

def mask_it(mask, bin_value):
    for a,b in zip(mask, bin_value):
        if a == '1':
            yield ['1']
        elif a == 'X':
            yield ['0', '1']
        else:
            yield [b]

def answer(input):
    """
    >>> answer('''mask = 000000000000000000000000000000X1001X
    ... mem[42] = 100
    ... mask = 00000000000000000000000000000000X0XX
    ... mem[26] = 1''')
    208
    """
    lines = input.split('\n')

    memory = {}

    for line in lines:
        if line.startswith('mask = '):
            mask = line[7:]
        else:
            address, value = line.replace('mem[', '').replace('] = ', '|').split('|',1)
            address = int(address)
            value = int(value)

            binary_address = bin(address).replace('0b','').rjust(36,'0')
            new_bin_address_masked = mask_it(mask, binary_address)
            for path in paths(list(new_bin_address_masked)):
                new_bin_address = ''.join(path)
                new_address = int(new_bin_address, 2)
                memory[new_address] = value
    return sum(memory.values())

if __name__ == '__main__':
    little_helper.help(2020, __file__, answer)


version = '0.2'
identifier = 'edu.utah.sci.vistrails.itk'
name = 'ITK'

import core.bundles.utils
import core.requirements
from core.modules.vistrails_module import Module, ModuleError

# Ugly, but Carlos doesnt know any better
if core.bundles.utils.guess_system() == 'linux-ubuntu':
    import sys
    sys.path.append('/usr/local/lib/VisTrailsITK')

try:
    from core.bundles import py_import
    itk = py_import('itk', {'linux-ubuntu': 'vistrails-itk'})
except ImportError:
    raise core.requirements.MissingRequirement("ITK and WrapITK")

import core.modules
import core.modules.module_registry

# ITK Package imports
from PixelType import *
from FeatureExtractionFilters import *
from ITK import *
from Image import Image
from IntensityFilters import *
from SegmentationFilters import *
from SelectionFilters import *
from SmoothingFilters import *
from ThresholdFilters import *
from GradientFilters import *
from NeighborhoodFilters import *
from ImageReader import *

def initialize(*args, **keywords):
    reg = core.modules.module_registry
    basic = core.modules.basic_modules

########################################################################################
# Misc.
    Index2D.register(reg,basic)
    Index3D.register(reg,basic)
    Size.register(reg,basic)
    Region.register(reg,basic)
    PixelType.register(reg,basic)
    Filter.register(reg,basic)
    Kernel.register(reg,basic)

    Image.register(reg,basic)

########################################################################################
# Pixel Types
    pixeltypes = [PixelTypeFloat,
                  PixelTypeUnsignedChar,
                  PixelTypeUnsignedShort,
                  PixelTypeRGB]

    for cls in pixeltypes:
        cls.register(reg,basic)

########################################################################################
# Feature Extraction Filters
    featurefilters = [GradientMagnitudeRecursiveGaussianImageFilter,
                      DanielssonDistanceMapImageFilter,
                      SobelEdgeDetectionImageFilter]

    for cls in featurefilters:
        cls.register(reg,basic)

########################################################################################
# Intensity Filters
    intensityfilters = [RescaleIntensityImageFilter,
                        SigmoidImageFilter,
                        ThresholdImageFilter,
                        ShiftScaleImageFilter,
                        NormalizeImageFilter]

    for cls in intensityfilters:
        cls.register(reg,basic)

########################################################################################
# Segmentation Filters
    segmentationfilters = [IsolatedWatershedImageFilter,
                           ConnectedThresholdImageFilter,
                           ConfidenceConnectedImageFilter,
                           IsolatedConnectedImageFilter]

    for cls in segmentationfilters:
        cls.register(reg,basic)

########################################################################################
# Selection Filters
    selectionfilters = [RegionOfInterestImageFilter,
                        CastImageFilter,
                        ExtractImageFilter]

    for cls in selectionfilters:
        cls.register(reg,basic)

########################################################################################
# Smoothing Filters
    smoothingfilters = [CurvatureAnisotropicDiffusionFilter,
                        RecursiveGaussianImageFilter,
                        DiscreteGaussianImageFilter,
                        GradientAnisotropicDiffusionImageFilter,
                        MinMaxCurvatureFlowImageFilter,
                        BinomialBlurImageFilter,
                        BilateralImageFilter,
                        CurvatureFlowImageFilter]

    for cls in smoothingfilters:
        cls.register(reg,basic)

########################################################################################
# Threshold Filters
    thresholdfilters = [BinaryThresholdImageFilter]

    for cls in thresholdfilters:
        cls.register(reg,basic)

########################################################################################
# Gradient Filters
    gradientfilters = [GradientMagnitudeImageFilter]

    for cls in gradientfilters:
        cls.register(reg,basic)

########################################################################################
# Neighborhood Filters
    neighborhoodfilters = [MeanImageFilter,
                           MedianImageFilter,
                           BinaryErodeImageFilter]

    for cls in neighborhoodfilters:
        cls.register(reg,basic)

########################################################################################
# Image Reader
    imagereader = [ImageReader,
                   ImageToFile,
                   GDCMReader,
                   DICOMReader]

    for cls in imagereader:
        cls.register(reg,basic)


from approzium import AuthClient
from approzium.pymysql import connect

auth = AuthClient(
    "authenticator:6001",
    # This is insecure, see https://approzium.org/configuration for proper use.
    disable_tls=True,
)
conn = connect(host="dbmysqlsha1", user="bob", db="db", authenticator=auth)
with conn.cursor() as cursor:
    cursor.execute("SELECT 1")
    result = cursor.fetchone()
    print(result)
conn.close()


from components import decorators
from components import endpoints_webapp2

import webapp2

import api
import config
import notifications
import service
import swarming

README_MD = (
  'https://chromium.googlesource.com/infra/infra/+/master/'
  'appengine/cr-buildbucket/README.md')

class MainHandler(webapp2.RequestHandler):  # pragma: no cover
  """Redirects to README.md."""

  def get(self):
    return self.redirect(README_MD)

class CronResetExpiredBuilds(webapp2.RequestHandler):
  """Resets expired builds."""

  @decorators.require_cronjob
  def get(self):
    service.reset_expired_builds()

class CronUpdateBuckets(webapp2.RequestHandler):  # pragma: no cover
  """Updates buckets from configs."""

  @decorators.require_cronjob
  def get(self):
    config.cron_update_buckets()

class BuildHandler(webapp2.RequestHandler):  # pragma: no cover
  """Redirects to API explorer to see the build."""

  def get(self, build_id):
    api_path = '/_ah/api/buildbucket/v1/builds/%s' % build_id
    return self.redirect(api_path)

def get_frontend_routes():  # pragma: no cover
  routes = [
    webapp2.Route(r'/', MainHandler),
    webapp2.Route(r'/b/<build_id:\d+>', BuildHandler),
    endpoints_webapp2.discovery_service_route(),
  ]
  routes += endpoints_webapp2.api_routes(api.BuildBucketApi)
  routes += endpoints_webapp2.api_routes(swarming.SwarmbucketApi)
  return routes

def get_backend_routes():
  return [
    webapp2.Route(
      r'/internal/cron/buildbucket/reset_expired_builds',
      CronResetExpiredBuilds),
    webapp2.Route(
      r'/internal/cron/buildbucket/update_buckets',
      CronUpdateBuckets),
    webapp2.Route(
      r'/internal/task/buildbucket/notify/<build_id:\d+>',
      notifications.TaskPublishNotification),
  ]


# Дана упорядоченная последовательность an чисел от 1 до N.
# Из копии данной последовательности bn удалили одно число, а оставшиеся перемешали. Найти удаленное число.
import random

n = int(input('Введите длину последовательности: '))

first_list = [i for i in range(1, n + 1)]
set_first_list = set(first_list)
print(f'Последовательность an {first_list}')
first_list.pop(int(input('Введите какой элемент удалить: ')))
random.shuffle(first_list)
print(f'Последовательность bn {first_list}')
set1 = set(first_list)
print(set1)
print(set_first_list.difference(set1))


import datetime
from PySide2.QtWidgets import QDialog

from ui_add_update import Ui_Dialog

class addDialog(QDialog):
    def __init__(self, *args, **kvargs):
        super().__init__(*args, **kvargs)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

        self.ui.OkButton.clicked.connect(self.accept)
        self.ui.CancelButton.clicked.connect(self.reject)
        self.ui.dateEdit.setDate(datetime.date.today())
        self.ui.OkButton.clicked.connect(self.get_data)
        self.ui.sc1000.valueChanged.connect(self.set_label)
        self.ui.sc500.valueChanged.connect(self.set_label)
        self.ui.sc200.valueChanged.connect(self.set_label)
        self.ui.sc100.valueChanged.connect(self.set_label)
        self.ui.sc50.valueChanged.connect(self.set_label)

    def set_label(self):
        self.ui.lsc1000.setNum(1000*self.ui.sc1000.value())
        self.ui.lsc500.setNum(500*self.ui.sc500.value())
        self.ui.lsc200.setNum(200*self.ui.sc200.value())
        self.ui.lsc100.setNum(100*self.ui.sc100.value())
        self.ui.lsc50.setNum(50*self.ui.sc50.value())
        self.ui.label.setNum(1000*self.ui.sc1000.value()+500*self.ui.sc500.value()+200*self.ui.sc200.value()+100*self.ui.sc100.value()+50*self.ui.sc50.value())

    def get_data(self):
        return {
            "c_date": self.ui.dateEdit.date().toPython(),
            "c_1000": self.ui.sc1000.value(),
            "c_500": self.ui.sc500.value(),
            "c_200": self.ui.sc200.value(),
            "c_100": self.ui.sc100.value(),
            "c_50": self.ui.sc50.value()
        }


import unittest

from traits.api import HasTraits, Int, Str, Tuple
from traitsui.api import Item, View
from traits.testing.api import UnittestTools

from traitsui.tests._tools import (
    BaseTestMixin,
    create_ui,
    requires_toolkit,
    reraise_exceptions,
    ToolkitName,
)

class TupleEditor(HasTraits):
    """Dialog containing a Tuple of two Int's."""

    tup = Tuple(Int, Int, Str)

    traits_view = View(
        Item(label="Enter 4 and 6, then press OK"), Item("tup"), buttons=["OK"]
    )

class TestTupleEditor(BaseTestMixin, unittest.TestCase, UnittestTools):
    def setUp(self):
        BaseTestMixin.setUp(self)

    def tearDown(self):
        BaseTestMixin.tearDown(self)

    @requires_toolkit([ToolkitName.qt, ToolkitName.wx])
    def test_value_update(self):
        # Regression test for #179
        model = TupleEditor()
        with create_ui(model):
            with self.assertTraitChanges(model, "tup", count=1):
                model.tup = (3, 4, "nono")

    @requires_toolkit([ToolkitName.qt])
    def test_qt_tuple_editor(self):
        # Behavior: when editing the text of a tuple editor,
        # value get updated immediately.

        from pyface import qt

        val = TupleEditor()
        with reraise_exceptions(), create_ui(val) as ui:

            # the following is equivalent to clicking in the text control of
            # the range editor, enter a number, and clicking ok without
            # defocusing

            # text element inside the spin control
            lineedits = ui.control.findChildren(qt.QtGui.QLineEdit)
            lineedits[0].setFocus()
            lineedits[0].clear()
            lineedits[0].insert("4")
            lineedits[1].setFocus()
            lineedits[1].clear()
            lineedits[1].insert("6")
            lineedits[2].setFocus()
            lineedits[2].clear()
            lineedits[2].insert("fun")

            # if all went well, the tuple trait has been updated and its value
            # is (4, 6, "fun")
            self.assertEqual(val.tup, (4, 6, "fun"))

if __name__ == "__main__":
    # Executing the file opens the dialog for manual testing
    val = TupleEditor()
    val.configure_traits()
    print(val.tup)