from __future__ import absolute_import, division, print_function

import collections
import numpy as np
from six.moves import range
import tensorflow as tf
from tensorflow.python.keras.optimizer_v2 import gradient_descent

from tensorflow_federated import python as tff

tf.logging.set_verbosity(tf.logging.ERROR)

nest = tf.contrib.framework.nest

np.random.seed(0)

tf.compat.v1.enable_v2_behavior()

tf.enable_resource_variables()

tff.federated_computation(lambda: 'Hello, World!')()

emnist_train, emnist_test = tff.simulation.datasets.emnist.load_data()

example_dataset = emnist_train.create_tf_dataset_for_client(emnist_train.client_ids[0])

# example_element = iter(example_dataset).next()

# example_element['label'].numpy()

NUM_EPOCHS = 10
BATCH_SIZE = 20
SHUFFLE_BUFFER = 500
NUM_CLIENTS = 3

def preprocess(dataset):
    def element_fn(element):
        return collections.OrderedDict([
            ('x', tf.reshape(element['pixels'], [-1])),
            ('y', tf.reshape(element['label'], [1])),
        ])

    return dataset.repeat(NUM_EPOCHS).map(element_fn).shuffle(SHUFFLE_BUFFER).batch(BATCH_SIZE)

preprocessed_example_dataset = preprocess(example_dataset)

sample_batch = nest.map_structure(lambda x: x.numpy(), iter(preprocessed_example_dataset).next())

def make_federated_data(client_data, client_ids):
    return [preprocess(client_data.create_tf_dataset_for_client(x)) for x in client_ids]

sample_clients = emnist_train.client_ids[0:NUM_CLIENTS]

federated_train_data = make_federated_data(emnist_train, sample_clients)

def create_compiled_keras_model():
    model = tf.keras.models.Sequential([
        tf.keras.layers.Dense(
            10, activation=tf.nn.softmax, kernel_initializer='zeros', input_shape=(784,)
        )
    ])

    def loss_fn(y_true, y_pred):
        return tf.reduce_mean(tf.keras.losses.sparse_categorical_crossentropy(y_true, y_pred))

    model.compile(
        loss=loss_fn,
        optimizer=gradient_descent.SGD(learning_rate=0.02),
        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]
    )

    return model

def model_fn():
    keras_model = create_compiled_keras_model()
    return tff.learning.from_compiled_keras_model(keras_model, sample_batch)

iterative_process = tff.learning.build_federated_averaging_process(model_fn)

state = iterative_process.initialize()

for round_num in range(2, 30):
    state, metrics = iterative_process.next(state, federated_train_data)
    print('round {:2d} metrics={}'.format(round_num, metrics))


# _*_ coding: utf-8 _*_
"""
# @Time : 2021/11/10 15:37
# @Author : lijun
# @File : pay_gateway.py
# @desc :
"""
from tools.DB import DB

class PayGateway:
    @staticmethod
    def real_query(select_field, where_field):
        gateway_list = ['pay_gateway_' + str(index) for index in range(0, 65)]
        sql = "select %s from %s where %s='%s';"
        db = DB('soa')
        for gateway in gateway_list:
            order_infos = db.query(
                sql % (','.join(select_field), gateway, where_field['field'], where_field['value']))
            if order_infos:
                print("支付状态pay_status(0-未支付 1-处理中 2-已支付 3-退款中 4-退款成功 5退款失败 6支付失败 7部分退款)")
                print("所在表：%s" % gateway)
                print('共查找出', len(order_infos), '条数据')
                print('--------------------------------------------')
                return order_infos
        del db

if __name__ == '__main__':
    select_field_list = ['id', 'parent_order_sn', 'pay_sn', 'site_code', 'pay_status', 'channel_code', 'transaction_id',
                         '3ds_status']
    sql_field = {
        'field': 'parent_order_sn',
        'value': 'L2202160108590453'
    }
    for order in PayGateway.real_query(select_field=select_field_list, where_field=sql_field):
        print(order)


from sys import stdin as s

N,M=map(int,s.readline().split())
trees=list(map(int,s.readline().split()))

start=0
finish=max(trees)

while start <= finish:
    mid=(start+finish)//2
    cnt=0 # 나무의 개수

    for i in trees:
        if cnt > M:
            break

        if i >= mid:
            cnt += i-mid

    if cnt >= M:
        start=mid+1
    else :
        finish=mid-1

print(finish)


import sys
input = sys.stdin.readline

N = int(input())
snows = list(map(int, input().split()))
snows.sort()

res = 10**10
for i in range(N):
    for j in range(i+3, N):
        l, r = i+1, j-1
        while l < r:
            v = (snows[i]+snows[j]) - (snows[l]+snows[r])
            res = min(res, abs(v))

            if v < 0:
                r -= 1
            else:
                l += 1

print(res)


import socket
import struct

class RDT():
    def __init__(self,sock):
        self.sock = sock

    def checksum(self, data):
        sum = 0
        data = str(data)
        for i in range(0,len(data),2):
            if i + 1 >= len(data):
                sum += ord(data[i]) & 0xFF
            else:
                w = ((ord(data[i]) << 8) & 0xFF00) + (ord(data[i+1]) & 0xFF)
                sum += w

        while (sum >> 16) > 0:
            sum = (sum & 0xFFFF) + (sum >> 16)

        sum = ~sum

        return sum & 0xFFFF

    def create_pkt(self, ack:int, seq:int, msg:str)->bytes:
        tamanho_mensagem = len(msg.encode())
        # Empacotar a estrutura com o tamanho da mensagem no início
        chcs = self.checksum(msg)
        pacote = struct.pack('>i3i1008s', tamanho_mensagem, ack, seq, chcs, msg.encode())
        return pacote

    def unpack_pkt(self, packet)->dict:
        # Desempacotar o pacote
        tamanho_mensagem, num1, num2, num3, mensagem = struct.unpack('>i3i1008s', packet)
        # Decodificar a string de volta para o formato de string original
        mensagem = mensagem[:tamanho_mensagem].decode()
        dicionario = {'ack' : num1, 'seq' : num2, 'checksum' : num3, 'mensagem' : mensagem, 'mensagem_size' : tamanho_mensagem}
        return dicionario

    def wait_for_ack(self, destino, ack_value, sndpkt)->bool:
        # S1, S2, S3 / S6, S7, S8
        estado = f'wait for ack{ack_value}'
        while estado == f'wait for ack{ack_value}':
            try:
                data, endereco = self.sock.recvfrom(1024)
                data = self.unpack_pkt(data)
                v1 = endereco == destino
                v2 = self.checksum(data['mensagem']) == data['checksum']
                v3 = data['ack'] == ack_value^1
                # S3
                if v1 and v2 and v3:
                    self.sock.settimeout(None) # encerrando o timer
                    estado = f'wait for ack{ack_value^1}'
                    return True
                else: # S2
                    continue

            except socket.timeout: # S3
                self.sock.sendto(sndpkt, destino) # Reenvio o pacote
                self.sock.settimeout(2) # Reinicio o timer

    def enviar(self, msg, destino):
        # S0 - Criar o pacote e enviar e iniciar o timer
        sndpkt = self.create_pkt(ack = 1, seq=0, msg='ACK')
        # S1, S2, S3, S4 (S4 - Receber, restante na função)
        self.sock.sendto(sndpkt, destino)
        self.sock.settimeout(2)
        rcvpkt = self.wait_for_ack(destino, 0, sndpkt)

        # S5
        sndpkt = self.create_pkt(ack=0, seq=1, msg=msg)
        # S6, S7, S8, S9 (S9 - Receber, restante na função)
        self.sock.sendto(sndpkt, destino)
        self.sock.settimeout(2)
        rcvpkt = self.wait_for_ack(destino, 1, sndpkt)

    def wait_for_seq(self, seq:int, endereco_s=None)->tuple:
            estado = f'wait for {seq} from below'
            while (estado == f'wait for {seq} from below'):
                data, endereco = self.sock.recvfrom(1024)
                data = self.unpack_pkt(data)
                v1 = self.checksum(data['mensagem']) == data['checksum']
                v2 = data['seq'] == seq
                v3 = (endereco_s == endereco) or (endereco_s == None)
                if v1 and v2 and v3:
                    sndpkt = self.create_pkt(ack=seq^1, seq=seq^1, msg='OK')
                    estado = f'wait for {seq^1} from below'
                else:
                    sndpkt = self.create_pkt(ack=seq, seq=seq, msg='NO')

                self.sock.sendto(sndpkt, endereco)

            return data['mensagem'], endereco

    def receber(self):
        # R0 e R1
        data, endereco = self.wait_for_seq(0)
        data, endereco = self.wait_for_seq(1, endereco)
        return data, endereco

class Server(RDT):
    def __init__(self,sock):
        super().__init__(sock)

class Client(RDT):
    def __init__(self,sock):
        super().__init__(sock)


from math import ceil, sqrt,floor

'''faça um programa que leia o comprimento do cateto oposto a do cateto adjacente
de um triângulo retângulo, calcule e mostre o comprimento da hipotenusa.'''

# Declararando variáveis
cateto_oposto_inicial = input()
cateto_adjacente_inicial = input()

# Convertendo variáveis
cateto_oposto_convertido = float(cateto_oposto_inicial)
cateto_adjacente_convertido = float(cateto_adjacente_inicial)

# Resolvendo problemas
hipotenusa = (cateto_oposto_convertido ** 2) + (cateto_adjacente_convertido ** 2)
raiz_quadrada = sqrt(hipotenusa)

# Imprimindo o resultado de acordo com a saída desejada.
print("{:.2f}".format((raiz_quadrada)))
# print("{:.2f}".format((hipotenusa)))

Exercícios Curso em vídeo de Python/Calculo da Hipotenusa.py


from dataclasses import dataclass

from aiogram.fsm.state import State, StatesGroup
from aiogram.types import InlineKeyboardButton as Button, KeyboardButton as KButton, Message
from aiogram.utils.keyboard import InlineKeyboardBuilder as Board, ReplyKeyboardBuilder as KBoard

start_board = Board([
    [Button(text='Погода ⛅', callback_data='weather forecast')],
    [Button(text='Настройки ⚙', callback_data='settings')]
]).as_markup()
back_btn = lambda data='', text='': Button(text='🔙 Назад' if not text else text, callback_data=f'back_{data}')

settings_board = Board([
    [Button(text='🔔 Настроить уведомления', callback_data='notify_settings')],
    [Button(text='🗺 Обновить местоположение', callback_data='send_location')],
    [Button(text='🗑 Удалить все данные', callback_data='delete_data')],
    [back_btn()]
]).as_markup()
location_board = KBoard([
    [KButton(text='🗺 Отправить своё местоположение', request_location=True)],
    [KButton(text='🔙 Назад')]
]).as_markup(one_time_keyboard=True, resize_keyboard=True)

time_board = lambda h=None, m=None: lambda data='', text='': (
    Board().row(Button(text='Часы: ↘' if h is None else f'Часы: {h:02} ↘', callback_data='show_h'))
    .row(Button(text='Минуты: ↘' if m is None else f'Минуты: {m:02} ↘', callback_data='show_m'))
    .row(*([back_btn(data, text)]
         + ([] if h is None or m is None else [Button(text='Создать 🔔', callback_data=f'create_notify {h}:{m}')])))
    .as_markup()
)
hour_board = lambda h=None, m=None: lambda data='', text='': (
    Board().row(Button(text='Часы: ↖' if h is None else f'Часы: {h:02} ↖', callback_data='hide_h'))
    .row(*[Button(text=f'✅ {n:02}' if h == n else f'{n:02}', callback_data=f'set h {n}') for n in range(24)], width=6)
    .row(Button(text='Минуты: ↘' if m is None else f'Минуты: {m:02} ↘', callback_data='show_m'))
    .row(*([back_btn(data, text)]
           + ([] if h is None or m is None else [Button(text='Создать 🔔', callback_data=f'create_notify {h}:{m}')])))
    .as_markup()
)
minute_board = lambda h=None, m=None: lambda data='', text='': (
    Board().row(Button(text='Часы: ↘' if h is None else f'Часы: {h:02} ↘', callback_data='show_h'))
    .row(Button(text='Минуты: ↖' if m is None else f'Минуты: {m:02} ↖', callback_data='hide_m'))
    .row(*[Button(text=f'✅ {n:02}' if m == n else f'{n:02}',
                  callback_data=f'set m {n}') for n in range(0, 60, 5)], width=6)
    .row(*([back_btn(data, text)]
           + ([] if h is None or m is None else [Button(text='Создать 🔔', callback_data=f'create_notify {h}:{m}')])))
    .as_markup()
)

START = ('{}{}\n\nС помощью ветров знаний и сил солнца, неба и дождя я предсказываю прогноз погоды на каждый день! '
         'Нажми на кнопку «Погода», чтобы узнать погоду прямо сейчас и прогноз погоды на сегодня, на завтра или даже '
         'на целых 5 дней вперёд. ⛅\n\nТы можешь настроить меня в «Настройках» и указать своё местоположение или время'
         ', когда ты хочешь получать уведомления. 🔔')
SETTINGS = ('Здесь ты можешь обновить своё местоположение или настроить ежедневные уведомления о погоде. ⚙\n\nЯ за '
            'конфиденциальность, поэтому по желанию ты можешь удалить все данные о себе и заставить меня забыть тебя, '
            'нажав на кнопку «Удалить все данные». 😉')
DATA_DELETED = 'Ой, кто-то сверкнул у меня перед лицом Нейрализатором из «Людей в чёрном»... Я всё забыл про тебя...'

CURR_LOCATION = 'Я помню, что ты из {}. 😉'
LOCATION = ('Нажми на кнопку ниже, чтобы отправить своё текущее местоположение, и дальше я всё сделаю за тебя! 🔍\n\n'
            'Или можешь нажать на 📎 и поделиться местоположением так, если хочешь указать другое.\n\nНу и, наконец, '
            'можешь просто отправить мне название города.')
LOCATION_SET = 'Я запомнил, где ты живёшь ;) Приятно познакомиться с жителем {}! 🤝'
LOCATION_ERROR = ('Я старался, но не смог найти твой город. 😩 Может быть, где-то опечатка? Попробуй ещё раз или отправь'
                  ' мне своё местоположение через кнопку ниже или с помощью 📎.')
NO_LOCATION_FORECAST = 'Чтобы предсказать прогноз погоды, мне нужно знать, где ты находишься ;)'

CURR_NOTIFY = ('Список поставленных уведомлений ниже на кнопках.\n\nНажми на ненужное, если хочешь удалить. 🙅🏻♂',
               'Уведомления не установлены.\n\nНажми на кнопку ниже, чтобы установить уведомления. 👇🏻')
NO_LOCATION_NOTIFY = ('Я не смогу отправить тебе уведомление с погодой, потому что не знаю твоё местоположение. 🤷🏻♂\n'
                      'Покажи мне по кнопке ниже, где ты находишься ;)')
NEW_NOTIFY = 'Выбери часы и минуты для уведомления и нажми «Создать» или введи их в формате HH:MM. 🤓'
NOTIFY_ERROR = ('Что-то мне не разобрать, что ты написал. 🤨 Может быть, у тебя где-то ошибочка? Попробуй ещё раз или'
                'воспользуйся клавиатурой ниже ;)')
NOTIFY_EXISTS = 'Уведомление с таким временем уже есть. 🤷🏻♂\nВыбери другое время ;)'
NOTIFY_SUCCESS = 'Уведомление успешно создано!  🥳'

FORECAST = ('{icon} {adverb} в {city} {verb}{desc}.\n🌡 На улице {temp}°C ({feels_verb} как {feels_like}°C).\n🫠 '
            'Давление: {pressure} мм рт.ст.\n💦 Влажность: {humidity}%.\n🍃 {wind_side} ветер скоростью {wind_speed} '
            'м/c.\n☁ На небе облачность в {clouds}%.')
SUN_DESC = '🌅 Восход сегодня {verb_sr} в {sunrise}.\n🌇 Закат {verb_ss} в {sunset}.'

SOON = 'В разработке — ждите очень скоро! 🔜'

@dataclass
class CallbackData:
    data: str
    message: Message

class Dialog(StatesGroup):
    get_geo = State()
    get_notify_time = State()


import datetime
import traceback
from rx import Observer

class TraceObserver(Observer):
    def __init__(self, prefix, trace_next=True, trace_next_payload=True):
        self.prefix = prefix
        self.trace_next = trace_next
        self.trace_next_payload = trace_next_payload

    def on_next(self, value, date=None):
        if self.trace_next is True:
            if self.trace_next_payload is True:
                print("{}:{} - on_next: {}".format(
                    date or datetime.datetime.now(),
                    self.prefix, value))
            else:
                print("{}:{} - on_next".format(
                    date or datetime.datetime.now(),
                    self.prefix))

    def on_completed(self, date=None):
        print("{}:{} - on_completed".format(
            date or datetime.datetime.now(),
            self.prefix))

    def on_error(self, error, date=None):
        if isinstance(error, Exception):
            print("{}:{} - on_error: {}, {}".format(
                date or datetime.datetime.now(),
                self.prefix, error,
                traceback.print_tb(error.__traceback__)))
        else:
            print("{}:{} - on_error: {}".format(
                date or datetime.datetime.now(),
                self.prefix, error))


import torch
import torch.nn as nn
from mmengine.model import BaseModule

class Sobel(BaseModule):
    """Sobel layer.

    The layer reduces channels from 3 to 2.
    """

    def __init__(self) -> None:
        super().__init__()
        grayscale = nn.Conv2d(3, 1, kernel_size=1, stride=1, padding=0)
        grayscale.weight.data.fill_(1.0 / 3.0)
        grayscale.bias.data.zero_()
        sobel_filter = nn.Conv2d(1, 2, kernel_size=3, stride=1, padding=1)
        sobel_filter.weight.data[0, 0].copy_(
            torch.FloatTensor([[1, 0, -1], [2, 0, -2], [1, 0, -1]]))
        sobel_filter.weight.data[1, 0].copy_(
            torch.FloatTensor([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]))
        sobel_filter.bias.data.zero_()
        self.sobel = nn.Sequential(grayscale, sobel_filter)
        for p in self.sobel.parameters():
            p.requires_grad = False

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        """Run sobel layer."""
        return self.sobel(x)


import cv2 as cv

#Loading the image
image = cv.imread("IMG.jpg")

#resize the image
image = cv.resize(image, (800,600))

#converting image to grayscale
grayscale_image = cv.cvtColor(image, cv.COLOR_BGR2GRAY)

#Smoothning the image
smoothgrayscaleimage = cv.medianBlur(grayscale_image, 5)

#getting the edges of the image
getedge = cv.adaptiveThreshold(smoothgrayscaleimage, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 9, 9)

#Preparing the mask
colorImage = cv.bilateralFilter(image, 9, 300, 300)

#cartoon image
cartoon = cv.bitwise_and(colorImage, colorImage, mask=getedge)
cv.imshow("cartoon image", cartoon)

cv.waitKey(0)
cv.destroyAllWindows()


"""
2525. Categorize Box According to Criteria
https://leetcode.com/problems/categorize-box-according-to-criteria/
"""

class Solution:
    def categorizeBox(self, length: int, width: int, height: int, mass: int) -> str:
        results = []
        if max(length, width, height, mass) >= 10 ** 4 or length * width * height >= 10 ** 9:
            results.append("Bulky")
        if mass >= 100:
            results.append("Heavy")

        if len(results) == 2:
            return "Both"
        elif not results:
            return "Neither"
        else:
            return results[0]


from operator import itemgetter
import networkx as nx
import wikipedia
import matplotlib.pyplot as plt

def graphBuilder(pageTitle):
    SEED = pageTitle.title()
    STOPS = ("International Standard Serial Number",
            "International Standard Book Number",
            "National Diet Library",
            "International Standard Name Identifier",
            "International Standard Book Number (Identifier)",
            "Pubmed Identifier",
            "Pubmed Central",
            "Digital Object Identifier",
            "Arxiv",
            "Proc Natl Acad Sci Usa",
            "Bibcode",
            "Library Of Congress Control Number",
            "Jstor",
            "Doi (Identifier)",
            "Isbn (Identifier)",
            "Pmid (Identifier)",
            "Arxiv (Identifier)",
            "Bibcode (Identifier)")

    todo_lst = [(0, SEED)]  # The SEED is in layer 0
    todo_set = set(SEED)  # The SEED itself
    done_set = set()  # Nothing is done yet

    g = nx.DiGraph()
    layer, page = todo_lst[0]

    while layer < 2:
        # Remove the name page of the current page from the todo_lst,
        # and add it to the set of processed pages.
        # If the script encounters this page again, it will skip over it.
        del todo_lst[0]
        done_set.add(page)

        # Show progress
        print(layer, page)

        # Attempt to download the selected page.
        try:
            wiki = wikipedia.page(page)  # Specify language as 'en' for English
        except wikipedia.exceptions.DisambiguationError as e:
            print(f"Ambiguous page: {page}. Skipping.")
            layer, page = todo_lst[0]
            continue
        except:
            print("Could not load", page)
            layer, page = todo_lst[0]
            continue

        for link in wiki.links:
            link = link.title()
            if link not in STOPS and not link.startswith("List Of"):
                if link not in todo_set and link not in done_set:
                    todo_lst.append((layer + 1, link))
                    todo_set.add(link)
                g.add_edge(page, link)
        layer, page = todo_lst[0]

    print("{} nodes, {} edges".format(len(g), nx.number_of_edges(g)))
    return g

graphAlbion = graphBuilder("Albion Online")
graphOutlast = graphBuilder("Outlast 2")
graphAge = graphBuilder("Alan Wake 2")
graphCities = graphBuilder("Cities: Skylines II")

composeAlbionOutlast = nx.compose(graphAlbion, graphOutlast)
composeAgeCities = nx.compose(graphAge, graphCities)

composeAll = nx.compose(composeAlbionOutlast, composeAgeCities)

print("{} nodes, {} edges".format(len(composeAll), nx.number_of_edges(composeAll)))

# make a copy of raw graph
original = composeAll.copy()

# remove self loops
composeAll.remove_edges_from(nx.selfloop_edges(composeAll))

# identify duplicates like that: 'network' and 'networks'
duplicates = [(node, node + "s")
              for node in composeAll if node + "s" in composeAll]

for dup in duplicates:
  # *dup is a technique named 'unpacking'
  composeAll = nx.contracted_nodes(composeAll, *dup, self_loops=False)

print(duplicates)

duplicates = [(x, y) for x, y in
              [(node, node.replace("-", " ")) for node in composeAll]
                if x != y and y in composeAll]
print(duplicates)

for dup in duplicates:
  composeAll = nx.contracted_nodes(composeAll, *dup, self_loops=False)

# nx.contracted creates a new node/edge attribute called contraction
# the value of the attribute is a dictionary, but GraphML
# does not support dictionary attributes
nx.set_node_attributes(composeAll, 0,"contraction")
nx.set_edge_attributes(composeAll, 0,"contraction")

print("{} nodes, {} edges".format(len(composeAll), nx.number_of_edges(composeAll)))

plt.style.use("default")
# degree sequence
degree_sequence = sorted([d for n, d in composeAll.degree()], reverse=True)

fig, ax = plt.subplots(1,2,figsize=(8,4))

# all_data has information about degree_sequence and the width of each bin
ax[0].hist(degree_sequence)
ax[1].hist(degree_sequence,bins=[1,2,3,4,5,6,7,8,9,10])

ax[0].set_title("Degree Histogram")
ax[0].set_ylabel("Count")
ax[0].set_xlabel("Degree")
ax[0].set_ylim(0,15000)

ax[1].set_title("Degree Histogram - Zoom")
ax[1].set_ylabel("Count")
ax[1].set_xlabel("Degree")
ax[1].set_xlim(0,10)
ax[1].set_ylim(0,15000)

plt.tight_layout()
plt.show()

# filter nodes with degree greater than or equal to 2
core = [node for node, deg in dict(composeAll.degree()).items() if deg >= 2]

# select a subgraph with 'core' nodes
gsub = nx.subgraph(composeAll, core)

print("{} nodes, {} edges".format(len(gsub), nx.number_of_edges(gsub)))

nx.write_graphml(gsub, "cna.graphml")

print("Nodes removed: {:.2f}%".format(100*(1 - 3420/13775)))
print("Edges removed: {:.2f}%".format(100*(1 - 14771/24856)))
print("Edges per nodes: {:.2f}".format(13775/3420))

top_indegree = sorted(dict(gsub.in_degree()).items(),
                      reverse=True, key=itemgetter(1))[:100]
print("\n".join(map(lambda t: "{} {}".format(*reversed(t)), top_indegree)))

Atividade 03 - Unidade 02/Requisito_01/main.py


from torch import Tensor
import kornia

# Use only if max_length >= 3000 or .mean often, otherwise use RunningMeanStack
# This implementation is faster than RunningMeanStack for large max_length
class RunningMeanStackFast(list):

    def __init__(self, max_length):
        super().__init__()
        self.max_length = max_length
        self.prev_sum = 0
        self.prev_mean = None
        self.added = []
        self.removed = []
        self.correction = 0

    def append(self, x):
        super().append(x)
        self.added.append(x)
        if len(self) > self.max_length:
            self.removed.append(self.tail)
            self.pop(0)
        else:
            self.prev_sum = sum(self)

    @property
    def mean(self):
        self.correction += 1
        if len(self) == 0:
            return 0

        if self.correction % 50 == 0:
            self.correction = 0
            self.prev_mean = sum(self) / len(self)
            return self.prev_mean

        if len(self.added) != 0 and len(self.removed) != 0:
            self.prev_sum += sum(self.added) - sum(self.removed)
            self.prev_mean = self.prev_sum / self.max_length
        else:
            self.prev_mean = self.prev_sum / len(self)

        self.added = []
        self.removed = []
        return self.prev_mean

    @property
    def head(self):
        return self[-1]

    @property
    def tail(self):
        return self[0]

# running mean for max_length samples using FIFO stack
class RunningMeanStack(list):

    def __init__(self, max_length):
        super().__init__()
        self.max_length = max_length

    def append(self, x):
        super().append(x)
        if len(self) > self.max_length:
            self.pop(0)

    @property
    def mean(self):
        if len(self) == 0:
            return 0

        return sum(self) / len(self)

    @property
    def head(self):
        return self[-1]

    @property
    def tail(self):
        return self[0]

# return image to normal rgb appearance and value range
def normalize_image(img):
    img = img.cpu().detach()

    # l_mean: float = 50, l_std: float = 29.59, ab_mean: float = 0, ab_std: float = 74.04
    img[0, 0] = img[0, 0] * 29.59 + 50
    img[0, 1] = img[0, 1] * 74.04
    img[0, 2] = img[0, 2] * 74.04

    # clip values
    img[0, 0] = img[0, 0].clamp(0, 100)
    img[0, 1] = img[0, 1].clamp(-128, 127)
    img[0, 2] = img[0, 2].clamp(-128, 127)

    img = kornia.color.lab_to_rgb(img)
    img = (img.squeeze(0).permute(1, 2, 0).numpy() * 255).astype('uint8')
    return img


__author__ = 'denislavrov'

import sqlite3

DATABASE = 'test.db'

def createtable(filename=''):  # function called to insert a table into a new database
    conn = sqlite3.connect(filename)  # opening/connecting to a database just like a file
    conn.execute('''CREATE TABLE SAVE
       (ID INTEGER PRIMARY KEY AUTOINCREMENT    NOT NULL,
       SAVENAME TEXT    NOT NULL,
       INV_TNAME TEXT     NOT NULL,
       LOC_TNAME TEXT  NOT NULL
       );
       ''')
    conn.close()

def createdb(filename=''):  # this function actually creates a physical file, for database to be stored in
    if filename == '':  # since some functions may be used just to reuse code they have keys to avoid user input
        while (len(filename) == 0) or (filename[len(filename) - 3:len(filename)] != '.db'):
            # check that input is not emtpy and ends with .db
            filename = input("Please enter a filename that ends with '.db': ")
    try:  # check if database exists by trying to open it for reading
        open(filename, mode='r')  # if file exists the following code is not run and jump to 'except:' is made.
        while 1:  # if database does exist ask user if he would like to switch to it
            useri = input("This database already exists. Would you like to switch to it? [Y,N]: ").lower()
            if useri == 'y':
                switchdb(filename=filename)  # invoke function to switch
                break
            elif useri == 'n':  # if user chooses not to switch send him back recursively,by calling this function again
                createdb()
                break
    except IOError:  # if file does not exist, then create it, create the table in it and switch to it.
        open(filename, mode='a').close()  # a quick way to create an empty file in one line.
        createtable(filename=filename)
        switchdb(filename=filename)

def switchdb(filename=''):  # a function to switch databases
    while 1:
        if filename == '':  # check for a preset key as usual if not set ask user for input
            filename = input("Please input a valid existing database name: ")
        try:  # try to open database for reading just to check that the file is there
            file = open(filename, mode='r')
        except IOError:
            print("Error switching the database.")
        else:  # no exception raised everything is fine, set that database to current database and reset current user
            global DATABASE
            DATABASE = filename
            file.close()
            break

def insertuser(username):  # little function to insert a new user into the database
    conn = sqlite3.connect(DATABASE)
    inv_tname = 'inv_' + username
    loc_tname = 'loc_' + username
    conn.execute("INSERT INTO SAVE (SAVENAME, INV_TNAME, LOC_TNAME) \
    VALUES ('%s','%s','%s')" % (username, inv_tname, loc_tname))
    conn.commit()
    conn.execute('''CREATE TABLE %s
       (ITEM_ID INTEGER  NOT NULL
       );
       ''' % inv_tname)

    conn.execute('''CREATE TABLE %s
       (LOC_ID INTEGER  NOT NULL
       );
       ''' % loc_tname)

    conn.close()

def save(inventory, visitedLocations):
    savename = input('Please input a savename: ')
    if savename != '' and not userexists(savename):
        insertuser(savename)
        conn = sqlite3.connect(DATABASE)
        for inv in inventory:
            conn.execute("INSERT INTO %s (ITEM_ID) \
    VALUES (%d)" % (get_inv_tname(savename), inv))
            conn.commit()

        for loc in visitedLocations:
            conn.execute("INSERT INTO %s (LOC_ID) \
    VALUES (%d)" % (get_loc_tname(savename), loc))
            conn.commit()
        conn.close()
    else:
        print('That save name is either invalid or already exists')

def checkdb(db, create=False):  # helper function to check if database exists
    # could be expanded to check data inside database
    try:
        open(db, mode='r').close()
        return True
    except IOError:
        print("Database %s does not exist, please create one." % db)
        if create:
            createdb()
        else:
            return False

def readusers():  # read the users in from the database
    conn = sqlite3.connect(DATABASE)
    rows = conn.execute("SELECT SAVENAME FROM SAVE")
    lrows = list([x[0] for x in rows])
    conn.close()
    return lrows

def readinv(savename):  # read the users in from the database
    conn = sqlite3.connect(DATABASE)
    rows = conn.execute("SELECT ITEM_ID FROM %s" % ('inv_' + savename))
    lrows = list([x[0] for x in rows])
    conn.close()
    return lrows

def readloc(savename):  # read the users in from the database
    conn = sqlite3.connect(DATABASE)
    rows = conn.execute("SELECT LOC_ID FROM %s" % ('loc_' + savename))
    lrows = list([x[0] for x in rows])
    conn.close()
    return lrows

def rmuser(username=''):  # function to remove a user
    global cUser
    if username == '':
        username = input("Please enter username to remove: ")
    conn = sqlite3.connect(DATABASE)
    conn.execute("DELETE FROM SAVE WHERE SAVENAME='%s'" % username)
    conn.commit()  # must commit when making changes
    conn.close()
    if username == cUser:  # if current user is the user being deleted set current user to no one
        cUser = ''
    return username

def getid(username):  # helper function to getid of user by username
    conn = sqlite3.connect(DATABASE)
    uid = list(conn.execute("SELECT ID FROM SAVE WHERE SAVENAME='%s'" % username))[0][0]
    conn.close()
    return uid

def get_inv_tname(username):  # helper function to getid of user by username
    conn = sqlite3.connect(DATABASE)
    uid = list(conn.execute("SELECT INV_TNAME FROM SAVE WHERE SAVENAME='%s'" % username))[0][0]
    conn.close()
    return uid

def get_loc_tname(username):  # helper function to getid of user by username
    conn = sqlite3.connect(DATABASE)
    uid = list(conn.execute("SELECT LOC_TNAME FROM SAVE WHERE SAVENAME='%s'" % username))[0][0]
    conn.close()
    return uid

def userexists(username):  # helper function to check if the user exists
    conn = sqlite3.connect(DATABASE)
    rows = list(conn.execute("SELECT SAVENAME FROM SAVE WHERE SAVENAME='%s'" % username))
    conn.close()
    return rows.__contains__((username,))


# -*- coding: utf-8 -*-
"""Public section, including homepage and signup."""
from flask import Blueprint, flash, redirect, render_template, request, url_for,current_app,send_from_directory
from flask_login import login_required, login_user, logout_user
import qrcode

import pyqrcode
from io import StringIO,BytesIO

from flask import make_response
import image,os
# try:
#     from PIL import Image
# except Exception as e:
#     print(str(e))
#     print('=====')
#     # import Image
#     from PIL.Image import core as image

from school.extensions import login_manager
from school.public.forms import LoginForm
from school.user.forms import RegisterForm
from school.user.models import User
from school.utils import flash_errors,templated

blueprint = Blueprint('public', __name__)

@login_manager.user_loader
def load_user(user_id):
    """Load user by ID."""
    return User.get_by_id(int(user_id))

@blueprint.route('/', methods=['GET', 'POST'])
@login_required
def home():
    """Home page."""
    return render_template('public/home.html')

@blueprint.route('/user_info')
@templated()
def user_info():
    return dict()

#简介
@blueprint.route('/introduction')
@templated()
def introduction():
    return dict()

#获取二维码
@blueprint.route('/get_rq/<string:rq_str>')
def get_rq(rq_str='0'):
    qr = qrcode.QRCode(
        version=1,
        error_correction=qrcode.constants.ERROR_CORRECT_L,
        box_size=10,
        border=4
    )
    qr.add_data(f'{rq_str}')
    qr.make(fit=True)
    img = qr.make_image()
    img_io = BytesIO()
    img.save(img_io, 'PNG')
    img_io.seek(0)
    response = make_response(img_io.read())
    response.headers['Content-Type'] = 'image/png'
    response.headers['Content-Description'] = 'attachment; filename=%s.png' % rq_str
    return response

#获取学生头像
@blueprint.route('/get_student_img')
@blueprint.route('/get_student_img/<path:student_img>')
def get_student_img(student_img='0'):
    path = os.getcwd()+'/'+current_app.config['STUDENTS_IMG']
    return send_from_directory(path, student_img)

@blueprint.route('/logout/')
@login_required
def logout():
    """Logout."""
    logout_user()
    flash('You are logged out.', 'info')
    return redirect(url_for('public.home'))

#flask-sse test
@blueprint.route('/hello')
def publish_hello():
    sse.publish({"user": "alice", "status": "Life is good!"}, type='greeting')
    # sse.publish({"message": "anaf!"}, type='greeting')
    return "Message sent!"
"""
<script>
    var source = new EventSource("{{ url_for('sse.stream') }}");
    source.addEventListener('greeting', function(event) {
        var data = JSON.parse(event.data);
        document.getElementById('inohtml').innerHTML +='<br/>hello';
        // alert(data);
    }, false);
    source.addEventListener('error', function(event) {
        // alert("Failed to connect to event stream. Is Redis running?");
    }, false);
  </script>
"""


#### Worksheet #5 ####

### Q1 ###

def a(n):
    if n == 0:
        return 0
    elif n == 1:
        return 1
    elif n == 2:
        return 1
    else:
        return a(n - 1) + a(n - 2) + 2 * a(n - 3)

### Q2 ###

def GCD(x, y):
    if x % y == 0 and x != y:
        return min(x, y)
    elif x == y:
        return x
    elif x % y == 1:
        return 1
    else:
        Min = min(x, y)
        R = max(x, y) / min(x, y)
        return GCD(R, Min)

### Q3 ###

def Q3(a, b):
    if b == 1:
        return a
    else:
        return a * Q3(a, b - 1)

###### Part 2 - Dictionaries #####

### Q4 ###

def Dict_maker(Str):  ### Assumes Str is a string of small words seperated by commas
    word_list = Str.split(",")
    Dict = {'a': [], 'b': [], 'c': [], 'd': [], 'e': [], 'f': [], 'g': [], 'h': [], 'i': [], 'j': [], 'k': [], 'l': [],
            'm': [], 'n': [], 'o': [], 'p': [], 'q': [], 'r': [], 's': [], 't': [], 'u': [], 'v': [], 'w': [], 'x': [],
            'y': [], 'z': []}
    for i in range(len(word_list)):
        letter = word_list[i][0]
        L = Dict[letter]
        L.append(word_list[i])
        Dict[letter] = L
    return Dict

Str = "dad,mom,omer,man,dog,walk"

print(Dict_maker(Str))

### Q5 ###

def First_counter(Dict):
    a2z = "abcdefghijklmnopqrstuvwxyz"
    result = []
    values = list(Dict.values())  ### values is now a list of lists
    for i in range(len(a2z)):
        c = 0
        for n in values[i]:
            if n[0] == a2z[i]:
                c += 1
        result.append((a2z[i], c))

Dict = {'a': [], 'b': [], 'c': [], 'd': [], 'e': [], 'f': ['fwf'], 'g': [], 'h': [], 'i': [], 'j': [], 'k': [], 'l': [],
        'm': [],
        'n': [], 'o': [], 'p': [], 'q': ['qrfqf'], 'r': [], 's': [], 't': [], 'u': [], 'v': [],
        'w': ['wer', 'wrw', 'wf',
              'wfqrf', 'wqfrefre'], 'x': [], 'y': [], 'z': []}

print(First_counter(Dict))


import pygame
from player_bullet import PlayerBullet

class Player:
    def __init__(self, screen, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.lives = 3
        self.x = x
        self.y = y
        self.speed = 2
        self.screen = screen
        self.firable = True
        self.bullets = []
        self.score = 0
        self.player_sprite = pygame.image.load("imgs/player.png")
        self.player_sprite = pygame.transform.scale(self.player_sprite, (30, 30))
        self.player_rect = pygame.Rect(self.x, self.y, 30, 30)

    def draw(self):
        self.screen.blit(self.player_sprite, self.player_rect)

    def move_left(self):
        if self.player_rect.left > 30:
            self.player_rect.x -= self.speed

    def move_right(self):
        if self.player_rect.right < 770:
            self.player_rect.x += self.speed

    def fire(self):
        if self.firable:
            bullet = PlayerBullet(self.screen, self.player_rect.x, self.player_rect.y - 20)
            self.bullets.append(bullet)
            self.firable = False

    def increase_score(self, amount):
        self.score += amount


# {
#   "competitions": [
#     ["HTML", "C#"],
#     ["C#", "Python"],
#     ["Python", "HTML"]
#   ],
#   "results": [0, 0, 1]
#  }

def updateScore(winningTeam, point, scores):
    if winningTeam not in scores:
        scores[winningTeam] = 0
    scores[winningTeam] += point

def winners(competitions, results):
    currentBestTeam = ""
    scores = {currentBestTeam: 0}
    for i, competition in enumerate(competitions):
        # print(i, competition)
        homeTeam, awayTeam = competition
        # print(homeTeam, awayTeam)
        winningTeam = homeTeam if results[i] == 1 else awayTeam
        updateScore(winningTeam, 3, scores)
        if scores[winningTeam] > scores[currentBestTeam]:
            currentBestTeam = winningTeam
    return currentBestTeam

def Tournament():
    competitions = [["HTML", "C#"],
                    ["C#", "Python"],
                    ["Python", "HTML"]]
    results = [0, 0, 1]
    result = winners(competitions, results)
    print(result)

if __name__ == '__main__':
    Tournament()


from src.config.configuration import queues_configuration
from src.utils.managers import ClientManager
import argparse
import collections
from src.utils.workers import Worker
from src.logging.dsys_logger_client import get_logger
from multiprocessing import Process
import time
import os
import signal

log = get_logger(__name__)

class ServerSetup(object):

    __slots__ = ('address', 'port', 'passkey')

    def __init__(self, address, port, passkey):
        self.address = address
        self.port = port
        self.passkey = passkey

    def __repr__(self):
        return "< ServerSetup address={} port={} passkey={}>".format(self.address, self.port, self.passkey)

class Watchdog(Process):
    def __init__(self, current_workers, jobs_queue, results_queue, rate, initial_workers, max_workers, sample_time,
                 poison_pill, logger):
        super(Watchdog, self).__init__()
        self.current_workers = current_workers
        self.jobs_queue = jobs_queue
        self.results_queue = results_queue
        self.rate = rate
        self.initial_workers = initial_workers
        self.max_workers = max_workers
        self.sample_time = sample_time
        self.poison_pill = poison_pill
        self.logger = logger

    def serve_forever(self):
        self.run()

    def run(self):
        while True:
            self.current_workers = collections.deque([w for w in self.current_workers if w.is_alive()])
            delta = analyze(self.jobs_queue, self.rate, self.current_workers,
                            self.initial_workers, self.max_workers, self.sample_time)
            if delta > 0 and len(self.current_workers) < self.max_workers:

                self.logger.info("====> Creating new worker: delta={}, threshold={}".format(delta, self.rate))
                worker = Worker(self.jobs_queue, self.results_queue, wait=False, poison_pill=self.poison_pill)
                worker.deamon = True
                worker.start()
                self.current_workers.append(worker)
                self.logger.info('{} - delta={}'.format(str(self), delta))

            elif delta < 0 and len(self.current_workers) > self.initial_workers:

                self.logger.info("====> Killing worker: delta={}, threshold={}".format(delta, self.rate))

                stop_worker(jobs_queue=self.jobs_queue,
                            poison_pill=self.poison_pill,
                            current_workers=self.current_workers,
                            workers_to_kill=1)

                self.current_workers = collections.deque([w for w in self.current_workers if w.is_alive()])
                self.logger.info('{} - delta={}'.format(str(self), delta))

            elif delta == self.rate and len(self.current_workers) > self.initial_workers:

                self.logger.info("====> Killing worker: delta={}, threshold={}".format(delta, self.rate))

                stop_worker(jobs_queue=self.jobs_queue,
                            poison_pill=self.poison_pill,
                            current_workers=self.current_workers,
                            workers_to_kill=len(self.current_workers) - self.initial_workers)

                self.current_workers = collections.deque([w for w in self.current_workers if w.is_alive()])
                self.logger.info('{} - delta={}'.format(str(self), delta))

            else:
                self.logger.info('{} - delta={}'.format(str(self), delta))

            time.sleep(1)

    def __repr__(self):
        return "< WatchDog - Running: {} Max: {}>".format(len(self.current_workers), self.max_workers)

def init_job_client(queues_conf):
    conf = ServerSetup(address=queues_conf['jobs_queue']['address'],
                       port=queues_conf['jobs_queue']['port'],
                       passkey=queues_conf['jobs_queue']['auth'])

    return ClientManager(address=(conf.address, conf.port), authkey=conf.passkey, queues=['tasks_queue'])

def init_result_client(queues_conf):
    conf = ServerSetup(address=queues_conf['results_queue']['address'],
                       port=queues_conf['results_queue']['port'],
                       passkey=queues_conf['results_queue']['auth'])

    return ClientManager(address=(conf.address, conf.port), authkey=conf.passkey, queues=['results_queue'])

def get_queues(job_client, results_client):
    return job_client.get_tasks_queue(), results_client.get_results()

def workerpool(jobs, results, initial_workers=2, max_workers=8, poison_pill='-STOP-', consume_rate=10., sample_time=1):

    current_workers = collections.deque()

    def inner(_current_workers):
        for _ in range(initial_workers):
            worker = Worker(jobs, results, wait=False, poison_pill=poison_pill)
            worker.deamon = True
            worker.start()
            _current_workers.append(worker)

        log.info("Started default workers")

        return Watchdog(current_workers=_current_workers,
                        jobs_queue=jobs,
                        results_queue=results,
                        rate=consume_rate,
                        initial_workers=initial_workers,
                        max_workers=max_workers,
                        sample_time=sample_time,
                        poison_pill=poison_pill,
                        logger=get_logger())

    return inner(current_workers)

def analyze(jobs, consume_rate_setpoint, current_workers, initial_workers, max_workers, sample_time=1. / 15.):

    size_t0 = jobs.qsize()
    time.sleep(sample_time)
    size_t1 = jobs.qsize()

    rate = size_t0 - size_t1 / len(current_workers)

    if len(current_workers) < initial_workers:
        return 1

    if len(current_workers) > max_workers:
        return -1

    return rate - consume_rate_setpoint

def stop_worker(jobs_queue, poison_pill, current_workers, workers_to_kill=1):

    if poison_pill is not None:

        _ = [jobs_queue.put(poison_pill, 1) for _ in range(workers_to_kill)]

    else:

        workers = [w.stats for w in current_workers]
        workers = [w for w in workers if w['cpu_percent'] == 0.]
        workers = sorted(workers, key=lambda x: x['memory_percent'])
        _ = [os.kill(workers[i * -1]['pid'], signal.SIGTERM) for i in range(workers_to_kill)]

def start_workers(queues_conf, initial_workers=2, max_workers=8, consume_rate=10., sample_time=1, poison_pill='-STOP-'):
    jobs, results = get_queues(init_job_client(queues_conf), init_result_client(queues_conf))
    pool = workerpool(jobs, results, initial_workers, max_workers, poison_pill,
                      consume_rate=consume_rate, sample_time=sample_time)
    pool.serve_forever()

def parse_commandline_args():
    parser = argparse.ArgumentParser('[dsys] Queues service')

    parser.add_argument(
        '--initial_workers',
        default=1,
        type=int,
        help='min workers',
        dest='initial_workers',
    )
    parser.add_argument(
        '--max_workers',
        default=6,
        type=int,
        help='max workers',
        dest='max_workers',
    )
    parser.add_argument(
        '--rate',
        default=10.,
        type=float,
        help='consuming rate threshold',
        dest='consume_rate',
    )
    parser.add_argument(
        '--sample_time',
        default=1.,
        type=float,
        help='check sample time',
        dest='sample_time',
    )
    parser.add_argument(
        '--poison_pill',
        default='-STOP-',
        type=str,
        help='message for stop',
        dest='poison_pill',
    )
    parsed_args = parser.parse_args()
    return parsed_args

def main():
    args = parse_commandline_args()
    start_workers(queues_configuration, args.initial_workers, args.max_workers,
                  args.consume_rate, args.sample_time, args.poison_pill)

if __name__ == '__main__':
    main()


#!/usr/bin/python
#
# Install SDK dependencies
#
#
# The <dependecies.json file> is a JSON file in its simplest form looking like this:
# [
#   {
#     "Url": "http://os4depot.net/share/library/misc/superduperlib.lha",
#     "SdkInstall":
#        [
#            { "From": "SuperDuper/Dev/include/amigaos4/inline4/superduper.h",    "To": "include/include_h/inline4/superduper.h"},
#            { "From": "SuperDuper/Dev/include/amigaos4/interfaces/superduper.h", "To": "include/include_h/interfaces/superduper.h"},
#        ]
#   }
# ]
# The JSON file can be expanded with SdkInstall instructions as below.

VERSION = "$ver 1.6 (2021-05-09)"
AUTHOR = "Joakim Nordstrom"

import sys
import json
import tempfile
#import urllib
#import shutil
#import urllib.request
#import requests
import argparse
import os.path
import re
from subprocess import call

# SDK location -- always end with slash
SDK_LOCATION = os.getenv('DEPGET_SDK_LOCATION', "/SDK/");
GLOBAL_DEPENDENCIES_FILE = os.getenv('DEPGET_GLOBAL_DEPENDENCIES_FILE', "/etc/amiga-dependencies.json");
GLOBAL_DEPENDENCIES_URL = "https://raw.githubusercontent.com/jaokim/amiga-dev-env/master/support-files/conf/dependencies.json"

parser = argparse.ArgumentParser(
     description='Install SDK dependencies',
     epilog='''\
dep-get uses a JSON file which contains install instructions for archives with SDK-material in them.
 [
   {
     "Url": "http://os4depot.net/share/library/misc/superduperlib.lha",
     "ArchiveType": "lha"
     "SdkInstall":
        [
            { "From": "SuperDuper/Dev/include/amigaos4/inline4/superduper.h",    "To": "include/include_h/inline4/superduper.h"},
            { "From": "SuperDuper/Dev/include/amigaos4/interfaces/superduper.h", "To": "include/include_h/interfaces/superduper.h"},
        ]
   }
 ]
Examples:
  dep-get --install libxml2 "pthreads 2005"       Install libxml2, libicu, and Pthreads
  dep-get --search icu                            Search for dependency "icu"
  dep-get -f myown-dependecies.json               Install dependecies listed in the JSON file
''')
parser.add_argument('-i', '--install', nargs='*', help="list of dependencies to install" )
parser.add_argument('-g', '--generate-dep-file', action="store_true",  help="for each installed package, update the local dependency file (see -f option)")
parser.add_argument('-f','--file', default="./dependencies.json", help="JSON file with dependecies to install")
parser.add_argument('-s', '--search', help="search for a dependency")
parser.add_argument('--update', help='download a new global dependencies file', action="store_true")
parser.add_argument('--test', help='only test what would happen', action="store_true")
parser.add_argument('--verbose', help='be verbose', action="store_true")
parser.add_argument('--version', help='show version', action="store_true")
parser.add_argument('--silent', help='be silent', action="store_true")

args = parser.parse_args()

if args.version:
    print("Version: {}".format(VERSION))
    print("Author:  {}".format(AUTHOR))
    sys.exit(0)

if args.verbose:
    COPY_COMMAND = "cp --verbose -rp {install_from} {install_to}";
else:
    COPY_COMMAND = "cp -rp {install_from} {install_to}";
UNPACK_CMD = {}
UNPACK_CMD['lha'] = "lha xw={tempdir} {archive}"
UNPACK_CMD['tar'] = "tar -C {tempdir} -xvf {archive}"
CHMOD_CMD = "chmod -R a+r {tempdir}"
DL_CMD = "wget {url} -O{destinationfile}"

#+tempdir+"/"+instruction['From']+" "+SDK_LOCATION+instruction['To'];

#######################################################################
# Download file
#######################################################################
def download_file(url, destinationfile):
    #with urllib.request.urlopen(url) as response:
    #    shutil.copyfileobj(response, destinationfile)
    download_cmd = DL_CMD.format(url=url, destinationfile=destinationfile)
    call(download_cmd, shell=True)
    #r = requests.get(url, allow_redirects=True)
    #open(destinationfile, 'wb').write(r.content)
    #urllib.request.FancyURLOpener().retrieve(url, filename=destinationfile)
    #urllib.urlretrieve(GLOBAL_DEPENDENCIES_URL, GLOBAL_DEPENDENCIES_FILE)
    #r = urllib.urlopen(url)
    #open(destinationfile, 'wb').write(r.read())

#######################################################################
# Update dependencies files
#######################################################################
if args.update:
    if not args.silent :
        print("Updating dependencies file from: "+GLOBAL_DEPENDENCIES_URL)

    if args.test:
        print("Downloading from {}, storing to: {}".format(GLOBAL_DEPENDENCIES_URL, GLOBAL_DEPENDENCIES_FILE))
    else:
        download_file(GLOBAL_DEPENDENCIES_URL, GLOBAL_DEPENDENCIES_FILE)

    sys.exit(0)

# Open default dependencies files. If the "local" dependency file doesnt contain
# an SdkInstall instructions, the global will be used.
if os.path.isfile(GLOBAL_DEPENDENCIES_FILE):
    with open(GLOBAL_DEPENDENCIES_FILE, 'r') as f:
        global_deps_dict = json.load(f)
else:
    if not args.silent:
        print("Global dependencies file couldn't be opened: {}", GLOBAL_DEPENDENCIES_FILE)
    global_deps_dict = {}

nothingFound = True
found = False;

#######################################################################
# Search
#######################################################################
if args.search:
    for global_dep in global_deps_dict:
        name = ""
        url = ""
        if "Url" in global_dep:
            url = global_dep["Url"]
        else:
            continue

        if "Name" in global_dep:
            name = global_dep["Name"]
        else:
            idx = url.rfind("/")
            if idx != -1:
                name = url[idx+1:len(url)]

        if url.lower() == args.search.lower():
            found = True;
        elif re.match(".*"+args.search.lower()+".*$", url.lower()):
            found = True;
        elif re.match(args.search.lower(), name.lower()):
            found = True;
        elif args.verbose :
            print("Doesnt match: "+name + " " + global_dep["Url"])

        if found :
            print(name.ljust(32)+" "+url)
            nothingFound = False
        found = False;
    if nothingFound:
        if not args.silent:
            print("No archives found matching \""+args.search+"\".")
        sys.exit(5)
    sys.exit(0)

#######################################################################
# Open JSON file listing and describing download URL and installation procedure.
# "Url" contains the URL to download
# "SdkInstall" is a list of From/To objects, where From is the path in the archive, and To is
# the target path in the SDK.
# [
#   {
#     "Url": "http://os4depot.net/share/library/misc/superduperlib.lha",
#     "SdkInstall":
#        [
#            { "From": "SuperDuper/Dev/include/amigaos4/inline4/superduper.h",    "To": "include/include_h/inline4/superduper.h"},
#            { "From": "SuperDuper/Dev/include/amigaos4/interfaces/superduper.h", "To": "include/include_h/interfaces/superduper.h"},
#        ]
#   }
# ]

if args.file:
    dependency_file = args.file

#######################################################################
# Read from already existing dep file, and then append stuff to it,
# adn then in the end, write to file.
#######################################################################
local_dependency_file_content = []
if args.generate_dep_file:
    if os.path.isfile(dependency_file) and os.path.getsize(dependency_file) > 0:
        with open(dependency_file, 'r') as f:
            local_dependency_file_content = json.load(f)
            if args.verbose:
                print("Read {} dependencies from {}", len(local_dependency_file_content), dependency_file)
    elif args.verbose:
        print("No existing, or empty dependency file found {}, will create new", dependency_file)

#######################################################################
# Install
#######################################################################
if args.install is not None:
    failure = False
    deps_to_install = []
    # Install from dependency file
    if len(args.install) == 0:
        dependencies = []
        if os.path.isfile(dependency_file) and os.path.getsize(dependency_file) > 0:
            if args.verbose:
                print("Loading dependencies from file {}".format(dependency_file))
            with open(dependency_file, 'r') as f:
                local_dep_file = json.load(f)
                if args.verbose:
                    print("Found {} dependencies to possibly install".format(len(local_dep_file)))
                for local_dep in local_dep_file:
                    # If we find the URL and isntall instructions in the local file,
                    # we can download and install, otherwise, we have to find it in global
                    if "Url" in local_dep and "SdkInstall" in local_dep:
                        deps_to_install.append(local_dep)
                    else:
                        for global_dep in global_deps_dict:
                            if ( ("Url" in global_dep and "Url" in local_dep and global_dep['Url'] == local_dep['Url']) or
                                    ("Name" in global_dep and "Name" in local_dep and global_dep['Name'] == local_dep['Name']) ):
                                if "SdkInstall" in global_dep:
                                    deps_to_install.append(global_dep)
                                else:
                                    print("No SDK installation instruction found for: {}, {}".format(dependency, url))
                                    failure = True
                            else:
                                continue
        elif args.verbose:
            failure = True
            print("Is not a file: {}".format(dependency_file))
    # Install from command line list
    else:
        dependencies = args.install

        if args.verbose:
            print("Loading dependencies from command-line {}".format(dependencies))
        for dependency in dependencies:
            deps_candidates = []
            # Find dependency to install
            for global_dep in global_deps_dict:
                name = ""
                url = ""
                if "Url" in global_dep:
                    url = global_dep["Url"]
                else:
                    continue

                archive_name = url.rsplit('/', 1)[-1]

                if "Name" in global_dep:
                    name = global_dep["Name"]
                if dependency == name or dependency.lower() == url or dependency.lower() == archive_name:
                    if "SdkInstall" in global_dep:
                        deps_candidates.append(global_dep)
                    else:
                        print("No SDK installation instruction found for: {}, {}".format(dependency, url))
                        failure = True

            # Make sure we have only matched one dependency
            if len(deps_candidates) == 0:
                failure = True
                if not args.silent :
                    print("Found no dependency for \"{}\"".format(dependency))
            elif len(deps_candidates) > 1:
                failure = True
                print("Found {} matching dependencies for \"{}\":".format(len(deps_candidates), dependency))
                for too_many_deps in deps_candidates :
                    print("   {}".format(too_many_deps['Url']))
                print("Please install using entire URL.")
            else:
                deps_to_install.append(deps_candidates[0])

    if failure:
        print("One or more errors occured, aborting")
        sys.exit(10)
    else:
        for dep_to_install in deps_to_install:
            url = dep_to_install['Url']
            archive_name = url.rsplit('/', 1)[-1]
            archive_type = dep_to_install['ArchiveType'] if 'ArchiveType' in dep_to_install else archive_name[-3:]

            if "SdkInstall" in dep_to_install:
                sdk_install = dep_to_install['SdkInstall']
            else :
                # This should be impossible, check is done above ^
                print("No SDK install instruction for {}".format(url))
                sys.exit(10)

            if not archive_type in UNPACK_CMD:
                print("No handler for archive type {} (filename: {}, url: {})".format(archive_type, archive_name, url))
                sys.exit(10)

            # Download archive and extract
            if args.test:
                tempdir = "tmp"
            else:
                tempdir = tempfile.mkdtemp()

            unpack_cmd = UNPACK_CMD[archive_type].format(tempdir=tempdir, archive=tempdir+"/"+archive_name)
            chmod_cmd = CHMOD_CMD.format(tempdir=tempdir)

            if args.test:
                print("Should download {} to {}/{}".format(url,tempdir,archive_name))
                print("call: "+unpack_cmd)
                print("call: "+chmod_cmd)
            else:
                if args.verbose:
                    print("Downloading {} to {}/{}".format(url,tempdir,archive_name))

                download_file(url, tempdir+"/"+archive_name)
                # r = requests.get(url, allow_redirects=True)
                # open(tempdir+"/"+archive_name, 'wb').write(r.content)

                # urllib.urlretrieve(url, tempdir+"/"+archive_name)

                if args.verbose:
                    print("call: "+unpack_cmd)
                call(unpack_cmd, shell=True)
                if args.verbose:
                    print("call: "+chmod_cmd)
                call(chmod_cmd, shell=True)

            for instruction in sdk_install:
                copy_cmd = COPY_COMMAND.format(install_from=tempdir+"/"+instruction['From'], install_to=SDK_LOCATION+instruction['To'])
                if args.test:
                    print("call: "+copy_cmd)
                else:
                    if args.verbose:
                        print("call: "+copy_cmd)
                    call(copy_cmd, shell=True)

            if not args.silent:
                print("Installed "+archive_name+" successfully.")

            if not dep_to_install in local_dependency_file_content:
                local_dependency_file_content.append({'Url':dep_to_install['Url']})
            elif args.verbose and args.generate_dep_file:
                print("Dependecy {} already in file, not adding".format(dep_to_install['Url']))
    if not args.silent:
        print("Installed {} dependencies".format(len(deps_to_install)))
if args.generate_dep_file:
    if args.verbose:
        print("Adding dependencies to {}".format(dependency_file))
    with open(dependency_file, 'w') as outfile:
        json.dump(local_dependency_file_content, outfile)

sys.exit(0)


import imp
from django.shortcuts import render, redirect
from .models import Destination
from django.contrib.auth.models import User, auth
from django.contrib import messages
# Create your views here.

def game(request):

    gamehome = Destination()
    gamehome.img = 'gamelogo.png'
    return render(request, "game.html", {'gamehome': gamehome})

def register(request):

        if request.method == "POST":

            username = request.POST['username']
            email = request.POST['email']

            if User.objects.filter(username=username):
                messages.info(request,('Username Exists'))
                return redirect('register')
            elif User.objects.filter(email=email):
                messages.info(request, "Email Exists")
                return redirect('register')
            else:
                user = User.objects.create_user(username=username, email=email)
                user.save()
                print("User Created")
            return redirect('/')

        else:
            return render(request, "register.html")

def home(request):
    return redirect('/')


#!/usr/bin/python3
# -*- coding: utf-8 -*-

def hello(name):
    print(f"Hello, {name}!")

if __name__ == "__main__":
    try:
        name = input("What\'s your name?\n")
    except ValueError:
        print("Please enter a name.")
    else:
        hello(name)


from tkinter import *
from tkinter import messagebox
root = Tk()
root.geometry('1000x700')
root.config(bg = '#d3f3f5')
root.title('Aman Contact Book')
root.resizable(0,0)
contactlist = [
    ['Aman yadav','9161915653'],
    ['Abhay Yadav', '8931031423'],
    ['Abhishek Kumar', '7845XXXX51'],
    ['ANCHAL YADAV', '995XXX130'],
    ]

Name = StringVar()
Number = StringVar()
frame = Frame(root)
frame.pack(side = RIGHT)

scroll = Scrollbar(frame, orient=HORIZONTAL)
select = Listbox(frame, yscrollcommand=scroll.set, font=('Times new roman' ,16), bg="#f0fffc", width=20, height=20, borderwidth=3, relief= "groove")
scroll.config (command=select.yview)
scroll.pack(side=RIGHT, fill=Y)
select.pack(side=LEFT,  fill=BOTH, expand=1)

def Selected():
    print("hello",len(select.curselection()))
    if len(select.curselection())==0:
        messagebox.showerror("Error", "Please Select the Name")
    else:
        return int(select.curselection()[0])
def AddContact():
    if Name.get()!="" and Number.get()!="":
        contactlist.append([Name.get() ,Number.get()])
        print(contactlist)
        Select_set()
        messagebox.showinfo("Confirmation", "Successfully Add New Contact")

    else:
        messagebox.showerror("Error","Please fill the information")
def UpdateDetail():
    if Name.get() and Number.get():
        contactlist[Selected()] = [Name.get(), Number.get()]

        messagebox.showinfo("Confirmation", "Successfully Update Contact")
        Select_set()

    elif not(Name.get()) and not(Number.get()) and not(len(select.curselection())==0):
        messagebox.showerror("Error", "Please fill the information")

    else:
        if len(select.curselection())==0:
            messagebox.showerror("Error", "Please Select the Name and \n press Load button")
        else:
            message1 = """To Load the all information of \n
                          selected row press Load button\n.
                          """
            messagebox.showerror("Error", message1)
def Delete_Entry():
    if len(select.curselection())!=0:
        result=messagebox.askyesno('Confirmation','You Want to Delete Contact\n Which you selected')
        if result==True:
            del contactlist[Selected()]
            Select_set()
    else:
        messagebox.showerror("Error", 'Please select the Contact')

def VIEW():
    NAME, PHONE = contactlist[Selected()]
    Name.set(NAME)
    Number.set(PHONE)
def EXIT():
    root.destroy()

def Select_set() :
    contactlist.sort()
    select.delete(0,END)
    for name,phone in contactlist :
        select.insert (END, name)
Select_set()
Label(root, text = 'Name', font=("Times new roman",22,"bold"), bg = 'white').place(x= 30, y=20)
Entry(root, textvariable = Name, width=30).place(x= 200, y=30)
Label(root, text = 'Contact No.', font=("Times new roman",20,"bold"),bg = 'white').place(x= 30, y=70)
Entry(root, textvariable = Number, width=30).place(x= 200, y=80)
Button(root,text=" ADD", font='Helvetica 18 bold',bg='#e8c1c7', command = AddContact, padx=20). place(x= 50, y=140)
Button(root,text="EDIT", font='Helvetica 18 bold',bg='#e8c1c7',command = UpdateDetail, padx=20).place(x= 50, y=200)
Button(root,text="DELETE", font='Helvetica 18 bold',bg='#e8c1c7',command = Delete_Entry, padx=20).place(x= 50, y=260)
Button(root,text="VIEW", font='Helvetica 18 bold',bg='#e8c1c7', command = VIEW).place(x= 50, y=325)
Button(root,text="EXIT", font='Helvetica 24 bold',bg='tomato', command = EXIT).place(x= 250, y=470)

root.mainloop()


# Third-party Libraries
from unittest import TestCase
from unittest import mock

# Own's Libraries
from test.data.request_office_all import REQUEST_OFFICE_ALL
from apps.office_app import office_list

from libs.sources.dynamodb_source import DynamoDBSource

class OfficeAppTest(TestCase):

    def test_ListSuccess(self):
        with mock.patch.object(DynamoDBSource, "select_Many") as a:
            a.return_value = [
                {
                    'department': 'Marketing 2',
                    'id': 'EI8312',
                    'name': 'Jorge Jimenez',
                    'phone': 892123122
                }, {
                    'department': 'Marketing 2',
                    'id': 'ID25101',
                    'name': 'Carlos A. Martinez',
                    'position': 'Development'
                }, {
                    'department': 'Marketing 2',
                    'id': 'RF231',
                    'name': 'Gabriela Rivero',
                    'position': 'Gerencia'
                }
            ]

            response = office_list(REQUEST_OFFICE_ALL, None)
            print(response)
            self.assertEqual(200, response['statusCode'])


from __future__ import print_function
import grpc
import msg_pb2
import msg_pb2_grpc

def run():
    # 客户端很好理解,网络连接得到一个channel,拿channel去实例化一个stub,通过stub调用RPC函数
    channel = grpc.insecure_channel('localhost:50051')
    # 使用grpc.insecure_channel('localhost:50051')进行连接服务端,接着在这个channel上创建stub
    stub = msg_pb2_grpc.MsgServiceStub(channel)
    # 在msg_pb2_grpc里可以找到MsgServiceStub这个类相关信息。这个stub可以调用远程的GetMsg函数

    a1 = float(input());# 输入运算数1，并转为float型
    op1 = input();# 输入运算符号类型
    b1 = float(input());# 输入运算数2，并转为float型

    response = stub.GetMsg(msg_pb2.MsgRequest(a=a1,op=op1,b=b1))# response为服务器端发来的内容
    # MsgRequest中的内容即msg.proto中定义的数据。在回应里可以得到msg.proto中定义的msg

    msg = "服务器端运算结果为：{}\n".format(response.result)#打印从服务器端接收到的数据，即运算结果
    print(msg)

if __name__ == '__main__':
    run()


import re
from collections import Counter

import pytest

import gen_factor_sat.circuit.tseitin.encoding as te
from gen_factor_sat.factoring_sat import FactoringSat
from gen_factor_sat.formula.cnf import CNF
from gen_factor_sat.formula.symbol import variable

comment_line = re.compile('c (?P<comment>.*)')
problem_line = re.compile('p cnf (?P<variables>\\d*) (?P<clauses>\\d*)')
clause_line = re.compile('(-?[1-9][0-9]* )*0')

@pytest.mark.parametrize('clause', [
    te.empty_clause(),
    te.unit_clause(variable(42)),
    te.clause(list(map(variable, [1, -2, -4, 17])))
])
def test_clauses_to_dimacs_conversion(clause):
    dimacs_clause = CNF.clause_to_dimacs(clause)
    assert clause_line.match(dimacs_clause), 'Clauses should match the DIMACS format'

    numbers = list(map(int, dimacs_clause.split(' ')))
    assert numbers[-1] == 0, 'Clauses (including empty clauses) should have a trailing zero'

    literals = numbers[:-1]
    assert literals == list(clause), 'The conversion should write the same literals in the same order'

@pytest.mark.parametrize('num_vars, clauses', [
    (0, {}),
    (1, {te.clause(list(map(variable, [-1, 3])))}),
    (17, {te.clause(list(map(variable, [-1, -12, -4]))), te.empty_clause()})
])
def test_cnf_to_dimacs_conversion(num_vars, clauses):
    cnf = CNF(num_vars, clauses)
    dimacs = cnf.to_dimacs()

    lines = dimacs.splitlines(keepends=False)
    assert len(lines) == 1 + len(clauses), "All clauses should be written"

    assert problem_line.match(lines[0]), "The first line should contain the instance parameters"
    match = problem_line.match(lines[0])

    num_variables = int(match.group('variables'))
    num_clauses = int(match.group('clauses'))

    assert num_variables == num_vars, "The conversion should use the provided number of variables"
    assert num_clauses == len(clauses), "The conversion should write the number of clauses"

@pytest.mark.parametrize('comments', [[], ['Comment 1'], ['Comment 1', ' ', '', 'Comment 2']])
def test_comments_should_be_prepended(comments):
    num_vars = 13
    clauses = {te.clause(list(map(variable, [-1, 3]))),
               te.clause(list(map(variable, [-10, -5, 14])))}

    cnf = CNF(num_vars, clauses)
    dimacs = cnf.to_dimacs(comments=comments)

    lines = dimacs.splitlines(keepends=False)
    assert len(lines) == len(comments) + 1 + len(clauses)

    for index in range(len(comments)):
        assert comment_line.match(lines[index])
        match = comment_line.match(lines[index])
        parsed_comment = match.group('comment')
        assert parsed_comment == comments[index]

@pytest.fixture(scope='module', params=[2, 17, 2 ** 15 + 17896, 2 ** 23 + 1247561])
def factoring_instance(request):
    factor_sat = FactoringSat.factorize_number(request.param)
    return factor_sat

def test_dimacs_format(factoring_instance):
    dimacs = factoring_instance.to_dimacs()

    parsed_problem_line = False
    lines = dimacs.splitlines(keepends=False)
    for line in lines:
        if comment_line.match(line):
            assert not parsed_problem_line, 'Comments are only permitted before the problem line'
        elif problem_line.match(line):
            assert not parsed_problem_line, 'The DIMACS format should have exactly one problem line'
            parsed_problem_line = True
        elif clause_line.match(line):
            assert parsed_problem_line, 'Clauses are only permitted after the problem line'
        else:
            assert not line, "Only comment lines, problem lines, or clauses are allowed"

    assert parsed_problem_line, 'The DIMACS format should have exactly one problem line'

def test_encoded_cnf(factoring_instance):
    dimacs = factoring_instance.to_dimacs()

    clauses = []
    lines = dimacs.splitlines(keepends=False)
    for line in lines:
        if problem_line.match(line):
            match = problem_line.match(line)

            num_variables = int(match.group('variables'))
            num_clauses = int(match.group('clauses'))

            assert num_variables == factoring_instance.cnf.number_of_variables
            assert num_clauses == len(factoring_instance.cnf.clauses)

        elif clause_line.match(line):
            clause = list(map(int, line.split(' ')[:-1]))

            occurrences = Counter(clause)
            assert all(occurrences[-literal] == 0 for literal in clause)
            assert all(occurrences[literal] == 1 for literal in clause)

            clauses.append(frozenset(clause))

    assert len(clauses) == len(factoring_instance.cnf.clauses)
    assert set(clauses) == factoring_instance.cnf.clauses


# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import gc
import lightgbm as lgb
import xgboost as xgb
from sklearn.metrics import mean_squared_error
from sklearn.model_selection import KFold
import matplotlib.pyplot as plt
import seaborn as sns
from hyperopt import fmin,tpe,hp,partial,space_eval
from sklearn.model_selection import KFold, StratifiedKFold
from hyperopt import STATUS_OK
import warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
pd.set_option('display.max_columns', None)
from sklearn.metrics import average_precision_score

train_df = pd.read_csv('creditcard_train.csv')

#特征工程1:时间特征处理
timedelta = pd.to_timedelta(train_df['Time'], unit='s')
train_df['Minute'] = (timedelta.dt.components.minutes).astype(int)
train_df['Hour'] = (timedelta.dt.components.hours).astype(int)

feats = [f for f in train_df.columns if f not in ['Class','Index']]
folds = StratifiedKFold(n_splits=5,shuffle=True,random_state=0)

def average_precision_score_vali(preds, data_vali):
    labels = data_vali.get_label()
    score_vali = average_precision_score(labels, preds)
    return 'average_precision_score', score_vali, True

def kfold_lightgbm(params):

    oof_preds = np.zeros(train_df.shape[0])

    for n_fold, (train_idx, valid_idx) in enumerate(folds.split(train_df[feats], train_df['Class'])):

        dtrain = lgb.Dataset(data=train_df[feats].iloc[train_idx],
                             label=train_df['Class'].iloc[train_idx],
                             free_raw_data=False, silent=True)
        dvalid = lgb.Dataset(data=train_df[feats].iloc[valid_idx],
                             label=train_df['Class'].iloc[valid_idx],
                             free_raw_data=False, silent=True)

        clf = lgb.train(
            params=params,
            train_set=dtrain,
            num_boost_round=1000,
            valid_sets=[dtrain, dvalid],
            early_stopping_rounds=20,
            feval=average_precision_score_vali,
            verbose_eval=False
        )

        oof_preds[valid_idx] = clf.predict(dvalid.data)

        del clf, dtrain, dvalid
        gc.collect()

    return average_precision_score(train_df['Class'], oof_preds)

#objective function
def lgb_objective(params,n_folds=5):

    loss = -kfold_lightgbm(params)

    return {'loss':-loss,'params':params,'status':STATUS_OK}

# Define the search space
space = {
    'objective':'regression',
    'boosting_type': 'gbdt',
    'subsample':0.8,
    'colsample_bytree':hp.uniform('colsample_bytree',0.8,0.9),
    'max_depth':7,
    'learning_rate':0.01,
    "lambda_l1":hp.uniform('lambda_l1',0.0,0.2),
    'seed':0,
}

#define algorithm
tpe_algorithm = tpe.suggest

best = fmin(fn = lgb_objective,space = space,algo=tpe_algorithm,max_evals=50)

print(best)
result=space_eval(space, best)
print(space_eval(space, best))


import sys

sys.stdin = open('./input.txt', 'rt')

input = sys.stdin.readline

num, k_limit = map(int,input().split())

list_bag = []

for i in range(num):
    tmp_bag = list(map(int,input().split()))
    if tmp_bag[0] > k_limit:
        continue
    list_bag.append(tmp_bag)

max_size = - sys.maxsize

for i in range(num):
    tmp_k_limit = k_limit
    tmp_max_size = 0
    visited = [0] * num
    if tmp_k_limit >= list_bag[i][0]:
        tmp_k_limit -= list_bag[i][0]
        tmp_max_size = list_bag[i][1]
        visited[i] = 1
    for j in range(num):
        if tmp_k_limit == 0:
            break
        if tmp_k_limit >= list_bag[j][0] and not visited[j]:
            tmp_k_limit -= list_bag[j][0]
            tmp_max_size += list_bag[j][1]
            visited[j] = 1
    max_size = max(tmp_max_size,max_size)

print(max_size)


import os
import json
import argparse
from collections import OrderedDict
import torch

from src.utils import bool_flag, initialize_exp
from src.models import build_model
from src.trainer import Trainer
from src.evaluation import Evaluator

VALIDATION_METRIC_SUP = 'precision_at_1-csls_knn_10'
VALIDATION_METRIC_UNSUP = 'mean_cosine-csls_knn_10-S2T-10000'

# main
parser = argparse.ArgumentParser(description='Supervised training')
parser.add_argument("--seed", type=int, default=-1, help="Initialization seed")
parser.add_argument("--verbose", type=int, default=2, help="Verbose level (2:debug, 1:info, 0:warning)")
parser.add_argument("--exp_path", type=str, default="", help="Where to store experiment logs and models")
parser.add_argument("--exp_name", type=str, default="debug", help="Experiment name")
parser.add_argument("--exp_id", type=str, default="", help="Experiment ID")
parser.add_argument("--cuda", type=bool_flag, default=True, help="Run on GPU")
parser.add_argument("--export", type=str, default="txt", help="Export embeddings after training (txt / pth)")

# data
parser.add_argument("--src_lang", type=str, default='en', help="Source language")
parser.add_argument("--tgt_lang", type=str, default='es', help="Target language")
parser.add_argument("--emb_dim", type=int, default=300, help="Embedding dimension")
parser.add_argument("--max_vocab", type=int, default=200000, help="Maximum vocabulary size (-1 to disable)")
# training refinement
parser.add_argument("--n_refinement", type=int, default=5, help="Number of refinement iterations (0 to disable the refinement procedure)")
# dictionary creation parameters (for refinement)
parser.add_argument("--dico_train", type=str, default="default", help="Path to training dictionary (default: use identical character strings)")
parser.add_argument("--dico_eval", type=str, default="default", help="Path to evaluation dictionary")
parser.add_argument("--dico_method", type=str, default='csls_knn_10', help="Method used for dictionary generation (nn/invsm_beta_30/csls_knn_10)")
parser.add_argument("--dico_build", type=str, default='S2T&T2S', help="S2T,T2S,S2T|T2S,S2T&T2S")
parser.add_argument("--dico_threshold", type=float, default=0, help="Threshold confidence for dictionary generation")
parser.add_argument("--dico_max_rank", type=int, default=10000, help="Maximum dictionary words rank (0 to disable)")
parser.add_argument("--dico_min_size", type=int, default=0, help="Minimum generated dictionary size (0 to disable)")
parser.add_argument("--dico_max_size", type=int, default=0, help="Maximum generated dictionary size (0 to disable)")
# reload pre-trained embeddings
parser.add_argument("--src_emb", type=str, default='', help="Reload source embeddings")
parser.add_argument("--tgt_emb", type=str, default='', help="Reload target embeddings")
parser.add_argument("--normalize_embeddings", type=str, default="", help="Normalize embeddings before training")

# parse parameters
params = parser.parse_args()

# check parameters
assert not params.cuda or torch.cuda.is_available()
assert params.dico_train in ["identical_char", "default"] or os.path.isfile(params.dico_train)
assert params.dico_build in ["S2T", "T2S", "S2T|T2S", "S2T&T2S"]
assert params.dico_max_size == 0 or params.dico_max_size < params.dico_max_rank
assert params.dico_max_size == 0 or params.dico_max_size > params.dico_min_size
assert os.path.isfile(params.src_emb)
assert os.path.isfile(params.tgt_emb)
assert params.dico_eval == 'default' or os.path.isfile(params.dico_eval)
assert params.export in ["", "txt", "pth"]

# build logger / model / trainer / evaluator
logger = initialize_exp(params)
src_emb, tgt_emb, mapping, _ = build_model(params, False)
trainer = Trainer(src_emb, tgt_emb, mapping, None, params)
evaluator = Evaluator(trainer)

# load a training dictionary. if a dictionary path is not provided, use a default
# one ("default") or create one based on identical character strings ("identical_char")
trainer.load_training_dico(params.dico_train)

# define the validation metric
VALIDATION_METRIC = VALIDATION_METRIC_UNSUP if params.dico_train == 'identical_char' else VALIDATION_METRIC_SUP
logger.info("Validation metric: %s" % VALIDATION_METRIC)

"""
Learning loop for Procrustes Iterative Learning
"""
for n_iter in range(params.n_refinement + 1):

    logger.info('Starting iteration %i...' % n_iter)

    # build a dictionary from aligned embeddings (unless
    # it is the first iteration and we use the init one)
    if n_iter > 0 or not hasattr(trainer, 'dico'):
        trainer.build_dictionary()

    # apply the Procrustes solution
    trainer.procrustes()

    # embeddings evaluation
    to_log = OrderedDict({'n_iter': n_iter})
    evaluator.all_eval(to_log)

    # JSON log / save best model / end of epoch
    logger.info("__log__:%s" % json.dumps(to_log))
    trainer.save_best(to_log, VALIDATION_METRIC)
    logger.info('End of iteration %i.\n\n' % n_iter)

# export embeddings
if params.export:
    trainer.reload_best()
    trainer.export()


class Solution:
    def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
        req = (1 << len(req_skills)) - 1
        req_skills = {s: k for k, s in enumerate(req_skills)}
        pp = {}

        for i, p in enumerate(people):
            if not p:
                continue
            t = sum(1 << req_skills[s] for s in p)
            pp[t] = 1 << i

        dp = pp.copy()

        while req not in dp:
            dp2 = {}
            k = {j: False for j in pp.values()}
            for t, j in pp.items():
                for s, i in dp.items():
                    u = t | s
                    if u > s:
                        dp2[u] = i | j
                        k[j] = True

            pp = {t: j for t, j in pp.items() if k[j]}
            dp = dp2

        return [i for i in range(len(people)) if (1 << i) & dp[req]]

LeetCode/Hard/1125. Smallest Sufficient Team.py


# voorbeeld 1

names = ["Ann", "Bob", "Lucie", "Louis"]

for name in names:
    print(name, "starts with:", name[0])

#voorbeeld 2

total = 0

for i in range(10):
    total +=i

print(total)


import pbl

import unittest

def test():
    # gather all tests
    loader = unittest.TestLoader()
    suite_list = []
    for module in pbl.all_modules:
        if hasattr(module, 'Tests'):
            suite_list.append(loader.loadTestsFromTestCase(getattr(module, 'Tests')))

    master_suite = unittest.TestSuite(suite_list)
    runner = unittest.TextTestRunner()
    runner.run(master_suite)


'''
IN MAX HEAP, THE PARENT NODE HAS THE HIGHEST VALUE AND
DECREASES AS YOU GO DOWN THE BINARY TREE
'''

from binarytree import heap

root = heap(height=3, is_max=True, is_perfect=False)
print('Max-heap of height 3', root)

root2 = heap(height=3, is_max=False, is_perfect=True)
print('Min-heap of height 3', root2)

root3 = heap()