# Chat Encryption Helper - ch9_crypto_chat.py
import os, base64, json
#from Crypto.Cipher import PKCS1_OAEP, AES
#from Crypto.PublicKey import RSA, ECC
from binascii import hexlify, unhexlify
from base64 import b64encode, b64decode

# encryption method used by all calls
def encrypt(message, usePKI, useDH, dhSecret):
    em=cipherEncrypt(message, dhSecret, 1)
    return em

# decryption method used by all calls
def decrypt(message, usePKI, useDH, dhSecret):
    dm=cipherEncrypt(message, dhSecret, -1)
    return dm

# decrypt using RSA (for future reference, not needed for this homework)
#def decrypt_rsa(ciphertext):
#    return ciphertext

# encrypt using RSA (for future reference, not needed for this homework)
#def encrypt_rsa(message):
#    return message

# check client commands (for future reference, not needed for this homework)
def check_client_command(data):
    return 1

# check server commands (for future reference, not needed for this homework)
def check_server_command(data):
    return 1

def reversed_string(a_string):
    return a_string[::-1]

def cipherEncrypt(inputText, n, d):

# Define valid characters
    valid_chars = set(chr(i) for i in range(34, 127)) - set([" ", "!"])

    # Reverse input text
    inputText = inputText[::-1]

    # Shift characters by N positions
    encrypted_text = ""
    for char in inputText:
        if char in valid_chars:
            char_code = ord(char)
            char_code -= 34
            char_code += n * d
            char_code %= len(valid_chars)
            char_code += 34
            encrypted_text += chr(char_code)
        else:
            encrypted_text += char

    return encrypted_text


# -*- coding: utf-8 -*-
"""
Created on Mon Mar 30 15:52:29 2020

@author: Acer
"""

from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = plt.axes(projection='3d')

def f(x, y):
    return np.sin(np.sqrt(x ** 2 + y ** 2))

x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)

X, Y = np.meshgrid(x, y)
Z = f(X, Y)

#ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');

theta = 2 * np.pi * np.random.random(1000)
r = 6 * np.random.random(1000)
x = np.ravel(r * np.sin(theta))
y = np.ravel(r * np.cos(theta))
z = f(x, y)
ax.scatter(x, y, z, c=z, cmap='cubehelix', linewidth=0.5);
ax.plot_trisurf(x, y, z, cmap='cubehelix', edgecolor='none');


import base64
import os
from email.mime.image import MIMEImage
from io import BytesIO

from PIL import Image
from celery import shared_task
from constance import config
from django.apps import apps
from django.core.files.uploadedfile import SimpleUploadedFile
from django.core.mail import get_connection
from django.core.mail.message import EmailMultiAlternatives
from django.template.loader import render_to_string
from django.utils.text import slugify

from mcod import settings
from mcod.core.api.search import signals as search_signals

@shared_task
def send_application_proposal(app_proposal):
    from mcod.datasets.models import Dataset
    conn = get_connection(settings.EMAIL_BACKEND)
    emails = [config.CONTACT_MAIL, ]

    title = app_proposal["title"]
    applicant_email = app_proposal.get('applicant_email', "")
    img_data = app_proposal.get('image', None)
    if img_data:
        data = img_data.split(';base64,')[-1].encode('utf-8')
        decoded_img = base64.b64decode(data)

        image = MIMEImage(decoded_img)
        img_name = slugify(app_proposal['title'])
        filename = f"{img_name}.{image.get_content_subtype()}"
        image.add_header('content-disposition', 'attachment',
                         filename=filename)
        image.add_header('Content-ID', '<app-logo>')

    datasets = Dataset.objects.filter(id__in=app_proposal.get('datasets', []))
    app_proposal['datasets'] = '\n'.join(
        f"{settings.BASE_URL}/dataset/{ds.id}"
        for ds in datasets
    )
    app_proposal['dataset_links'] = '
'.join(
        f"{ds.title}\n"
        for ds in datasets
    )

    external_datasets = app_proposal.get('external_datasets', [])
    app_proposal['external_datasets'] = '\n'.join(
        f"{eds.get('title', '(nie nazwany)')}: {eds.get('url', '(nie podano url)')}\n" for eds in external_datasets
    )
    app_proposal['external_dataset_links'] = '
'.join(
        (f"{eds.get('title')}: {eds.get('url')}\n"
         if 'url' in eds else eds.get('title'))
        for eds in external_datasets
    )
    app_proposal['keywords'] = ', '.join(app_proposal.get('keywords', tuple()))
    app_proposal['host'] = settings.BASE_URL

    msg_plain = render_to_string('mails/propose-application.txt', app_proposal)
    msg_html = render_to_string('mails/propose-application.html', app_proposal)

    if settings.DEBUG and config.TESTER_EMAIL:
        emails = [config.TESTER_EMAIL]

    mail = EmailMultiAlternatives(
        f'Zgłoszono propozycję aplikacji {title}',
        msg_plain,
        from_email=config.NO_REPLY_EMAIL,
        to=emails,
        connection=conn
    )
    mail.mixed_subtype = 'related'
    mail.attach_alternative(msg_html, 'text/html')
    if img_data:
        mail.attach(image)
    mail.send()

    return {'application_proposed': f'{title} - {applicant_email}'}

@shared_task
def generate_logo_thumbnail_task(app_id):
    model = apps.get_model('applications', 'Application')
    instance = model.objects.get(pk=app_id)
    if instance.image:
        image = Image.open(instance.image)

        if image.mode not in ('L', 'RGB', 'RGBA'):
            image = image.convert('RGB')

        image.thumbnail(settings.THUMB_SIZE, Image.ANTIALIAS)

        temp_handle = BytesIO()
        image.save(temp_handle, 'png')
        temp_handle.seek(0)

        suf = SimpleUploadedFile(os.path.split(instance.image.name)[-1],
                                 temp_handle.read(),
                                 content_type='image/png')
        thumb_name = '.'.join(suf.name.split('.')[:-1]) + "_thumb.png"
        instance.image_thumb.save(thumb_name, suf, save=False)
    else:
        instance.image_thumb = None

    model.objects.filter(pk=app_id).update(image_thumb=instance.image_thumb)
    search_signals.update_document.send(model, instance)

    return {
        'image_thumb': instance.image_thumb_url
    }


#!/usr/bin/env python3
# -*- encoding: utf-8 -*-

import re
import reprlib

RE_WORD = re.compile('\w+')

class Sentence:
    def __init__(self, text):
        self.text = text
        self.words = RE_WORD.findall(text)

    def __repr__(self):
        return 'Sentence(%s)' % reprlib.repr(self.text)

    def __iter__(self):
        for word in self.words:
            yield word
        return

def test_gen_123():
    def gen_123():
        yield 1
        yield 2
        yield 3

    # for i in gen_123():
    #     print(i)

    g = gen_123()
    print(next(g))
    print(next(g))
    print(next(g))
    print(next(g))

if __name__ == '__main__':
    test_gen_123()


#--------------------------------------#to import ------------(text)
import googletrans
#import pyttsx3
import speech_recognition as sr
import gtts
import pygame
import os
#-------------------------------------#setup----------------------
gts = googletrans.Translator()
#speaker = pyttsx3.init()
pygame.mixer.init()

#-------------------------------------1. setup function---------------------

def listen_recording():
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print('Recording...')
        audio = r.listen(source)
    try:
        unknown_text = (r.recognize_google(audio))
        translate(unknown_text)
    except sr.UnknownValueError:
        print('Unknown Error')

def translate(message):
    lang = input("what lang do u want to translate")
    speak(message, lang)

def speak(message, input_lang):
    print(input_lang)
    output = gts.translate(message, dest=input_lang)
    print(output.text)
    translated_message = output.text
    tts = gtts.gTTS(translated_message, lang=input_lang, slow=True)
    pygame.mixer.music.unload()
    os.remove('audio.mp3')
    filename = 'audio.mp3'
    tts.save(filename)
    pygame.mixer.music.load(filename)
    pygame.mixer.music.play()

    # print(lang)
    # print(output.origin)
    # print(output.text)
    # speaker.say(output.text)
    # speaker.runAndWait()

talk = True

while talk is True:
    listen_recording()
    ans = input("enter Y if you want to leave").lower()
    if ans == "y":
        break

#print(gtts.lang.tts_langs())
#https://gtts.readthedocs.io/en/latest/module.html

1.6 Translation speech to speech(text) in Python(API).py


from scipy.optimize import fmin_l_bfgs_b
import numpy as np

class LBFGSOptimizer(object):
    """
    This class makes it possible to compute loss and gradients in one pass
    while retrieving them via two separate functions, "_loss" and "_grads".
    This is done because scipy.optimize requires separate functions for loss and gradients,
    but computing them separately would be inefficient.
    """

    def __init__(self, img_nrows, img_ncols, f_outputs):
        self.img_nrows = img_nrows
        self.img_ncols = img_ncols
        self.f_outputs = f_outputs
        self.loss = None
        self.grads = None

    def _eval_loss_and_grads(self, x):
        x = x.reshape((1, self.img_nrows, self.img_ncols, 3))

        outputs = self.f_outputs([x])
        loss = outputs[0]
        if len(outputs[1:]) == 1:
            grads = outputs[1].flatten().astype('float64')
        else:
            grads = np.array(outputs[1:]).flatten().astype('float64')
        return loss, grads

    def _loss(self, x):
        loss_value, grad_values = self._eval_loss_and_grads(x)
        self.loss = loss_value
        self.grads = grad_values
        return self.loss

    def _grads(self, _):
        grad_values = np.copy(self.grads)
        self.loss = None
        self.grads = None
        return grad_values

    def run(self, x0, n_iter: int):
        # run scipy-based optimization (L-BFGS) over the pixels of the generated image
        # so as to minimize the neural style loss
        x, f, _ = fmin_l_bfgs_b(self._loss, x0, self._grads, maxiter=n_iter)
        return x, f


# 绘制图案
import matplotlib.pyplot as plt
import numpy as np

theta = np.linspace(0, 2 * np.pi, 200)
a_set = [1.5, 3, 5, 2, 4, 6]
plt.figure(figsize=(6.4 * 2, 7.2))
plt.subplots_adjust(hspace=0.4)
for i, a in enumerate(a_set):
    plt.subplot(2, 3, i + 1)
    r = np.sin(a * theta)
    x = r * np.cos(theta)
    y = r * np.sin(theta)
    plt.plot(x, y, ['b^', 'g^'][int(np.floor(i / 3))], label="a={}".format(a))
    plt.legend(loc=(0.4, 1.01))
plt.show()


import gymnasium as gym
import torch
import torch.nn as nn
import torch.optim as optim
import collections
import argparse
import torch.nn.functional as F
import numpy as np
import os
import sys
import wandb
import time
import torchvision
import pickle
import random
import cv2

sys.path.append(os.path.dirname(__file__) + "/..")

from utils import ReplayBuffer, OU_Noise

ENV_NAME = "CarRacing-v2"

learning_rate = 0.0001
tau = 0.9
device = "cuda:0"
weight_file_prefix = os.path.dirname(__file__) + "/bc_weights/" + os.path.basename(__file__).split(".")[0]
batch_size = 512
sample_data = []

NET_W = 512
# Deterministic policy network, input s, output the action with n degrees of freedom
class Policy(nn.Module):
    def __init__(self, action_count, usebn=False):
        super(Policy, self).__init__()
        BN = nn.BatchNorm1d if usebn else nn.Identity
        self.cnn = torchvision.models.efficientnet_b0(weights='IMAGENET1K_V1')
        # Freeze the second linear layer
        # for param in self.cnn.parameters():
        #     param.requires_grad = False
        self.cnn.classifier = nn.Linear(1280, NET_W)
        self.bn1 = BN(NET_W)

        self.fc2 = nn.Linear(NET_W, NET_W // 2)
        self.bn2 = BN(NET_W // 2)
        self.fc3 = nn.Linear(NET_W // 2, action_count)
        self.optimizer = optim.AdamW(self.parameters(), lr=learning_rate, weight_decay=5e-3)

    def forward(self, s: torch.Tensor):
        x = torch.relu(self.bn1(self.cnn(s)))
        x = torch.relu(self.bn2(self.fc2(x)))
        x = torch.tanh(self.fc3(x))
        return x

def get_sample():
    samples = random.sample(sample_data, batch_size)
    s_arr = []
    action_arr = []
    r_arr = []
    for item in samples:
       s, action, r, done = item
       s_arr.append(s)
       action_arr.append(action)
       r_arr.append(r)

    return (torch.tensor(np.array(s_arr)).float().to(device),
            torch.tensor(np.array(action_arr)).float().to(device),
            torch.tensor(np.array(r_arr)).float().to(device))

# loss_fn = torch.nn.MSELoss()
#loss_fn = torch.nn.L1Loss()
loss_fn = torch.nn.SmoothL1Loss(beta=0.4)

def train(pi):
    pi.train()
    loss_arr = []
    for _ in range(100):
        s, a, r = get_sample()
        s = s.permute(0, 3, 1, 2)
        pred = pi(s)
        loss = (loss_fn(pred, a) * r).mean()
        pi.optimizer.zero_grad()
        loss.backward()
        pi.optimizer.step()
        loss_arr.append(loss.detach().cpu().numpy())
    return np.array(loss_arr).mean()

for i in range(0, 210):
    with open(f'tracks/{i:04d}.pickle', "rb") as f:
        data = pickle.load(f)
        reward_arr = []
        for _,_, r, _, _ in data:
            reward_arr.append(r)
        for idx, item in enumerate(data):
            s, action, r, done, truncated = item
            # print(action)
            s = (np.array(s) - 128) / 255
        # for s, r, done in data:
            # action = np.random.randn(3).clip(-0.9, 0.9)
            steer, throttle, brake = action
            if throttle > brake:
                accel = throttle
            elif throttle < brake:
                accel = -brake
            else:
                accel = 0
            # print(min(2, sum(reward_arr[idx:idx+100])))
            # r = max(1, max(2, sum(reward_arr[idx:idx+100])) ** 0.3)
            r = max(0.1, sum(reward_arr[idx:idx+150]) / min(len(reward_arr) - idx, 150))
            sample_data.append((s, [steer, accel], r, done))
            reward_arr.append(r)

pi = Policy(action_count = 2, usebn = False)
pi = pi.to(device)

ENV_NAME = "CarRacing-v2"
env = gym.make(ENV_NAME, render_mode='human')
def eval_play(render=False):
    if render:
        env = gym.make(ENV_NAME, render_mode='human')
    else:
        env = gym.make(ENV_NAME, render_mode='state_pixels')
    s, _ = env.reset()
    done = False
    truncated = False
    pi.eval()
    max_reward = 0
    total_reward = 0
    while not (done or truncated):
        s = (torch.tensor(s).permute(2, 0, 1) - 128)/ 255
        s = s.unsqueeze(0).float().to(device)
        # print(s.shape)
        with torch.no_grad():
            action = pi(s).detach().cpu().numpy()[0]
        steer = action[0]
        if action[1] > 0:
            throttle = action[1]
            brake = 0
        else:
            throttle = 0
            brake = -action[1]
        # print([steer, throttle, brake])
        sp, r, done, truncated, info = env.step([steer, throttle, brake])
        s = sp
        total_reward += r
        if total_reward > max_reward:
            max_reward = total_reward
    # if render:
    #     env.render()
    return max_reward

def eval_record_play():
    imgs = []
    s, _ = env.reset()
    imgs.append(env.render())
    done = False
    truncated = False
    total_reward = 0
    pi.eval()
    while not (done or truncated):
        s = (torch.tensor(s).permute(2, 0, 1) - 128)/ 255
        s = s.unsqueeze(0).float().to(device)
        # print(s.shape)
        with torch.no_grad():
            action = pi(s).detach().cpu().numpy()[0]
        steer = action[0]
        if action[1] > 0:
            throttle = action[1]
            brake = 0
        else:
            throttle = 0
            brake = -action[1]
        # print([steer, throttle, brake])
        sp, r, done, truncated, info = env.step([steer, throttle, brake])
        total_reward += r
        s = sp
        imgs.append(env.render())
    return total_reward, imgs

if True:
    env = gym.make(ENV_NAME, render_mode='rgb_array')
    pi.load_state_dict(torch.load('bc_weights/behavior_cloning_2_60_893.9.pt', map_location=torch.device(device)))
    img_write_idx = 0
    while True:
        total_reward, imgs = eval_record_play()
        if total_reward < 850:
            continue
        for img in imgs:
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
            cv2.imwrite(f'img/{img_write_idx:05d}.png', img)
            img_write_idx += 1

for it in range(1, 100):
    l = train(pi)
    print("loss:", l)
    if it % 5 == 0:
        max_r = []
        for eval_it in range(50):
            max_r.append(eval_play(eval_it < 3))
        print(f"{np.mean(max_r):.1f}")
        torch.save(pi.state_dict(), weight_file_prefix + f'_{it}_{np.mean(max_r):.1f}.pt' )


import xlwt
import mistune

class ExcelRenderer(mistune.Renderer):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._current_line = 0
        self._workbook = xlwt.Workbook()
        self._sheet = self._workbook.add_sheet("md2xls")
        self._prev_level = 0
        self._current_id = [0] * 3

    def header(self, text, level, raw=None):
        self._current_id[level - 1] += 1
        for i in range(level, 3):
            self._current_id[i] = 0
        self._writeln(level, text)
        self._prev_level = level
        return ""

    def list_item(self, text):
        self._current_id[2] += 1
        self._write(self._prev_level + 1, text)
        self._writeln(self._prev_level + 2, ".".join(map(str, self._current_id)))
        return ""

    def _write(self, x, body):
        self._sheet.write(self._current_line, x - 1, body)

    def _writeln(self, x, body):
        self._sheet.write(self._current_line, x - 1, body)
        self._current_line += 1

    def save(self, fname):
        self._workbook.save(fname)

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("markdown")
    parser.add_argument("output")
    args = parser.parse_args()

    md = open(args.markdown).read()
    renderer = ExcelRenderer()
    mistune.markdown(md, renderer=renderer)
    renderer.save(args.output)

if __name__ == "__main__":
    main()


from random import randint, choice
import costmap

def get_freespace(map=costmap.my_costmap):

    freespace_list =[]
    for i in range (len(map)):
        if (map[i] <254):
            freespace_list.append(i)
    #print(len(freespace_list))
    return freespace_list

def giveIndex( ):
    freespace = get_freespace()
    return choice(freespace)

if __name__ == "__main__":
    #my_list = get_freespace()
    #print (len(my_list))
    element = giveIndex()
    print ("index:", element, "value: ", costmap.my_costmap[element])


N = int(input())
arr = [i for i in range(1, N+1)]
num = list(map(int, input().split()))
for i in range(N):
    # 0이면 스왑할 필요가 없으므로 pass.
    if num[i] != 0:
        # 0이 아니면 주어진 숫자만큼 swap을 진행한다.
        for k in range(num[i]):
            # 주어진 인덱스에서 부터 앞으로 swap진행!
            arr[i-k], arr[i-1-k] = arr[i-1-k], arr[i-k]
# 리스트 출력법 두가지
# print(*arr)
for i in arr:
    print(i, end=" ")


from django.shortcuts import render, redirect, get_object_or_404
from django.utils import timezone
from .models import Item, ItemComment
from .forms import ItemForm, ItemCommentForm
from django.contrib.auth.decorators import login_required

# Create your views here.

def homeitem(request):
    items = Item.objects.all()
    return render(request, 'homeitem.html', {'items_list': items})

def newitem(request):
    if request.method == 'POST':
        form = ItemForm(request.POST, request.FILES)
        if form.is_valid():
            item = form.save(commit=False)
            item.author = request.user
            item.user = item.author
            item.save()
            return redirect('homeitem')

    else:
        form = ItemForm()
    return render(request, 'newitem.html', {'form': form})

def detailitem(request, index):
    item = get_object_or_404(Item, pk=index)
    comment_list = ItemComment.objects.filter(item=item)
    if request.method == "POST":
        comment_form = ItemCommentForm(request.POST)
        if comment_form.is_valid():
            comment = comment_form.save(commit=False)
            # comment.author=request.user
            comment.published_date = timezone.now()
            # comment.user=request.user
            comment.item = item
            comment.save()
            return redirect('detailitem', index=index)
    else:
        comment_form = ItemCommentForm
    return render(request, 'detailitem.html', {'item': item, 'comment_list': comment_list, 'comment_form': comment_form})

def edititem(request, index):
    item = get_object_or_404(Item, pk=index)
    if request.method == 'POST':
        form = ItemForm(request.POST, request.FILES, instance=item)
        if form.is_valid():
            item = form.save(commit=False)
            item.author = request.user
            item.save()
            return redirect('detailitem', index=item.pk)
    else:
        form = ItemForm(instance=item)
    return render(request, 'edititem.html', {'form': form})

def deleteitem(request, pk):
    item = get_object_or_404(Item, pk=pk)
    item.delete()
    return redirect('homeitem')

def delete_comment(request, index, comment_pk):
    comment = get_object_or_404(ItemComment, pk=comment_pk)
    comment.delete()
    return redirect('detailitem', index=index)

# @login_required
# def like_item(request, item_id):
#     item = get_object_or_404(Item, id=item_id)
#     if request.user in item.like_users.all():
#         item.like_users.remove(request.user)
#     else:
#         item.like_users.add(request.user)


# Bianca Pallaro
# Thursday, October 29, 2020
# Homework 2, Part 1

# Make a list of the following numbers: 22, 90, 0, -10, 3, 22, and 48
numbers = [22,90,0,-10,3,22,48]
# Display the number of elements in the list.
print(len(numbers))
#Display the 4th element of this list.
print(numbers[3])
#Display the sum of the 2nd and 4th element of the list.
print(numbers[1] + numbers[3])
#Display the 2nd-largest value in the list.
sort_numbers = sorted(numbers)
print(sort_numbers[-2])
#Display the last element of the original unsorted list
print(numbers[-1])
#Display the sum of all of the numbers divided by two.
print(sum(numbers)/2)
#Print whether the median or the mean of the numbers is higher
mid= round(len(sort_numbers) / 2)
median= (sort_numbers[mid])
amount= len(numbers)
total = sum(numbers)
mean = round(total/amount)

if median > mean:
    print("Median:", median, "is higher than the mean:", mean)
else:
    print("Mean:", mean, "is higher than the median:", median)

# Define a dictionary called movie that works with the following code.

movie = {'title': 'Lion King','year': '1994','director': 'Roger Allers' }
print("My favorite movie is", movie['title'], "which was released in", movie['year'], "and was directed by", movie['director'])

#On the lines after that, add keys to the movie dictionary for budget and revenue
# (you'll use code like movie['budget'] = 1000),
# and print out the difference between the two.

movie['budget'] = 45000000
movie['revenue'] = 766000000
difference = (movie['revenue'] - movie['budget'])
print(difference)

#3) If the movie cost more to make than it made in theaters, print
# "That was a bad investment". If the film's revenue was more than five times
# the amount it cost to make, print "That was a great investment."
# Otherwise print "That was an okay investment."

if movie['budget'] > movie['revenue']:
    print('That was a bad investment')
elif movie['revenue'] > (movie['budget']*5):
    print('That was a great investement')
else:
    print('That was an okay investment')

#4) Manhattan has 1.6 million residents, Brooklyn has 2.6m, Bronx has 1.4m,
# Queens has 2.3m and Staten Island has 470,000. (
# Tip: keeping it all in either millions or thousands is a good idea)

nyc = {
    'Manhattan': 1600000,
    'Brooklyn': 2600000,
    'Bronx': 1400000,
    'Queens': 2300000,
    'Staten Island' : 470000
}
# 5) Display the population of Brooklyn.
print(nyc['Brooklyn'])
#6) Display the combined population of all five boroughs
pop_nyc = sum(nyc.values())
print(pop_nyc)
#7) Display what percent of NYC's population lives in Manhattan.
per_manhattan = round(((nyc['Manhattan'] / pop_nyc) * 100))
print(per_manhattan)


import registroMercadorias

valorTotal = 0
condicao = "s"

while condicao == "s":

    nome = input("Digite o nome da mercadoria: ")
    quantMin = int(input("Digite a quantidade mínima dessa mercadoria: "))
    while quantMin <= 0:
        quantMin = int(input("A quantidade mínima não pode ser zero ou inferior.\nDigite novamente: "))
    quantMax = int(input("Digite a quantidade máxima dessa mercadoria: "))
    while quantMax <= 0 or quantMax < quantMin:
        quantMax = int(input("A quantidade máxima não pode ser zero ou inferior e nem menor do que a quantidade mínima\nDigite novamente: "))
    quantAtual = int(input("Digite a quantidade atual dessa mercadoria no estoque: "))
    while quantAtual < 0:
        quantAtual = int(input("A quantidade atual não pode ser inferior a zero.\nDigite novamente: "))
    valorUni = float(input("Digite o valor unitário dessa mercadoria: "))
    while valorUni <= 0:
        valorUni = int(input("O valor unitário não pode ser igual ou inferior a zero.\nDigite novamente: "))

    mTotal = registroMercadorias.mercadoriaTotal(nome, quantMin, quantMax, quantAtual, valorUni)
    if quantAtual < quantMin:
        mReposicao = registroMercadorias.mercadoriaReposicao(nome, quantMin, quantMax, quantAtual, valorUni)

    valorTotal += quantAtual * valorUni

    condicao = input("Deseja registrar mais produtos? (s - sim /n - não):")

print("\nTodos os produtos registrados: ")
print(mTotal)
print("\nProdutos que precisam de reposição: ")
print(mReposicao)
print("\nValor total do estoque %0.2f" %(valorTotal))


# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.

from setuptools import setup

PACKAGE_NAME = "mozleak"
PACKAGE_VERSION = "1.0.0"

setup(
    name=PACKAGE_NAME,
    version=PACKAGE_VERSION,
    description="Library for extracting memory leaks from leak logs files",
    long_description="see https://firefox-source-docs.mozilla.org/mozbase/index.html",
    classifiers=[
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3.5",
    ],
    # Get strings from http://pypi.python.org/pypi?%3Aaction=list_classifiers
    keywords="mozilla",
    author="Mozilla Automation and Tools team",
    author_email="tools@lists.mozilla.org",
    url="https://wiki.mozilla.org/Auto-tools/Projects/Mozbase",
    license="MPL",
    packages=["mozleak"],
    zip_safe=False,
    install_requires=[],
)


import os
import pytest

from som.vm.current import current_universe

@pytest.mark.parametrize(
    "test_name",
    [
        "Array",
        "Block",
        "ClassLoading",
        "ClassStructure",
        "Closure",
        "Coercion",
        "CompilerReturn",
        "DoesNotUnderstand",
        "Double",
        "Empty",
        "Global",
        "Hash",
        "Integer",
        "Preliminary",
        "Reflection",
        "SelfBlock",
        "SpecialSelectors",
        "Super",
        "Set",
        "String",
        "Symbol",
        "System",
        "Vector",
    ],
)
def test_som(test_name):
    current_universe.reset(True)
    core_lib_path = os.path.dirname(os.path.abspath(__file__)) + "/../core-lib/"
    args = [
        "-cp",
        core_lib_path + "Smalltalk",
        core_lib_path + "TestSuite/TestHarness.som",
        test_name,
    ]

    current_universe.interpret(args)

    assert current_universe.last_exit_code() == 0


# Задайте два числа. Напишите программу, которая найдёт НОК (наименьшее общее кратное) этих двух чисел. nok = a*b/nod(a, b)

a = int(input('input 1 number: '))
b = int(input('input 2 number: '))

nod =1#наибольший общий делитель

for i in range(a*b+1, 2, -1):
    if a % i == 0 and b % i == 0:
        nod = i
        break

nok = int(a*b/nod)
print(nok)

a = int(input())
b = int(input())
for i in range(max(a,b),a*b,max(a,b)):
    print(i)
    if i%a==0 and i%b==0:
        print(i)


import socket
import os
from bs4 import BeautifulSoup as bs

def clear():
	loc = os.getcwd()
	if 'C:' in loc or 'D:' in loc:
		os.system('cls')
	else:
		os.system('clear')

def tcp_client(IP = '127.0.0.1', PORT = 8080):
	clear()
	print('**CONNECTING**')
	global sock
	sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
	sock.connect((IP, PORT))
	while True:
		try:
			msg = input('--> ')
			sock.send(bytes(msg, 'utf-8'))
			res = sock.recv(2097152)
			res = res.decode('utf-8')
			file = open('index.html', 'w')
			file.write(res)
			file.close()
			with open('index.html', 'r') as index:
				if 'Invalid URL' in index.read():
					print('Invalid URL')
				else:
					print('Html code saved in "index.html"')
			break
		except BrokenPipeError:
			continue

def connect():
	while True:
		try:
			IP = input('IP address: ')
			PORT = int(input('PORT: '))
		except ValueError:
			print('PORT must be without letters')
			continue
		else:
			tcp_client(IP, PORT)
			break

# tcp_client()
connect()


from setuptools import setup, find_packages
with open('LICENSE') as f:
    license = f.read()

setup(name = 'etomo',
      version = '0.1',
      description = 'The toolbox for electron tomography.',
      author = 'Zhichao Zhong',
      author_email = 'zhong@cwi.nl',
      license = license,
      packages = find_packages( include = ('etomo',), exclude =('tests', 'example'))
      )