import urllib.parse

import requests
from PIL import Image
from scrapy import Selector
from globals import file_path

def beko(raport_lab, product, model):
    html = requests.get(product[6]).content
    sel = Selector(text=html)

    """"""""""""""""" ZDJĘCIA PRODUKTU """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    imgs = sel.xpath('//div[@id="product-main-image"]//a/@href').extract()

    for i in range(len(imgs)):
        res = requests.get(f'https://www.beko.pl{imgs[i]}')
        with open(f'{file_path}/{model}/obrazki_produktu/{i}.jpg', 'wb') as file_format:
            file_format.write(res.content)
        im = Image.open(f'{file_path}/{model}/obrazki_produktu/{i}.jpg')
        file_format = im.format
        width, height = im.size
        if width > height:
            ratio = width / 600
        else:
            ratio = height / 600
        new_width = round(width / ratio)
        new_height = round(height / ratio)
        im = im.resize((new_width, new_height))
        if file_format == 'PNG':
            im.save(f'{file_path}/{model}/obrazki_produktu/{i}.jpg', 'PNG')
        elif file_format == 'JPEG':
            im.save(f'{file_path}/{model}/obrazki_produktu/{i}.jpg', 'JPEG')
        else:
            print(f"Nie umiem zrobić zdjęcia nr {i} :'( (typ {file_format})")

    """"""""""""""""" OPIS TECHNICZNY """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    beko_tech = sel.css('table.table.table-beko ::text').extract()

    # czyszczenie treści opisu technicznego z pustych znaków
    for i in range(len(beko_tech)):
        beko_tech[i] = beko_tech[i].replace('\n', '')
        beko_tech[i] = beko_tech[i].replace('\t', '')
        beko_tech[i] = beko_tech[i].replace('\xa0', '')
        beko_tech[i] = beko_tech[i].replace('\r', '')
        beko_tech[i] = beko_tech[i].replace('  ', '')
        # czyszczenie ekementów, które są samymi spacjami
        if beko_tech[i].isspace():
            beko_tech[i] = beko_tech[i].replace(' ', '')

    # usuwanie psutych elementów
    beko_tech = list(filter(''.__ne__, beko_tech))

    # rozróżnienie wierszy, które są nazwami kategorii (specs_category)
    i = 0
    while i in range(len(beko_tech)):
        if i >= len(beko_tech) - 1:
            break
        if ":" not in beko_tech[i] and ":" not in beko_tech[i + 1]:
            beko_tech.insert(i + 2, '')
            i = i + 2
        i = i + 1
        if i >= len(beko_tech) - 1:
            break

    # usuwanie dwukropków
    for i in range(len(beko_tech)):
        beko_tech[i] = beko_tech[i].replace(':', '')

    # tworzenie gotowych pozycji kodu do wklejenia na stronę MatrixMedia
    i = 0
    opis_techniczny = []
    opis_krotki = []
    while i in range(len(beko_tech)):
        if i >= len(beko_tech) - 1:
            break
        # wykorzystanie rozróżnienia nazwy kategorii do nadania odpowienich znaczników
        if beko_tech[i + 1] == '':
            opis_techniczny.append(
                '
' + beko_tech[i] + '
')
        # dodawanie znaczników do zwykłych linijek nazwa-wartość
        else:
            opis_techniczny.append(
                '
' + beko_tech[i] + '	' + beko_tech[i + 1] + '
')
            if i in range(23, 43):
                opis_krotki.append(f'
{beko_tech[i]}: {beko_tech[i + 1]}
')
        i = i + 2
    opis_k = '
' + ''.join(opis_krotki) + '
'

    # dodanie znaczników początkowych i końcowych zgodnych z kodem strony MatrixMedia
    start = '

'
    end = '

'
    opis_techniczny = [start] + opis_techniczny + [end]

    opis_t = ''.join(opis_techniczny)

    print("==================== Opis Techniczny ====================")
    print(opis_t + '\n\n')

    """"""""""""""""" OPIS GRAFICZNY """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    beko_graph = sel.css('div.row.hero div.col-xs-12 ::text').extract()

    # czyszenie treści opisu graficznego z pustych znaków
    for i in range(len(beko_graph)):
        beko_graph[i] = beko_graph[i].replace('\n', '')
        beko_graph[i] = beko_graph[i].replace('\t', '')
        beko_graph[i] = beko_graph[i].replace('\xa0', '')
        beko_graph[i] = beko_graph[i].replace('  ', '')
        if beko_graph[i].isspace():
            beko_graph[i] = beko_graph[i].replace(' ', '')

    # usuwanie psutych elemenetów
    beko_graph = list(filter(''.__ne__, beko_graph))

    # zdarza się, że jeden z kafelków opisu ma tylko nagłówek. Żeby go też obsłużyć dodałem poniższy warunek
    if len(beko_graph) % 2 != 0:
        for i, ele in enumerate(beko_graph):
            print(f'{i}. {ele}')
        # z jakiegoś powodu po uruchomieniu w konsoli programu następna wczytywana wartość wyrzuca błąd jakby została
        # uzupełniona ciągiem znaków, więc x przyjmuje tę wartość, a dopiero y służy do obsłużenia tej sytuacji
        try:
            x = int(input('\nNajwidoczniej któryś z nagłówków nie ma opisu. Wskaż jego numer, aby program mógł '
                          'kontynuować: '))
        except ValueError:
            x = int(input())
        beko_graph.insert(x + 1, ' ')

    # tworzenie gotowego kodu odpowiedniego dla strony MatrixMedia
    i = 0
    j = 0
    while i in range(len(beko_graph)):
        # dodawanie treści nagłowka
        if i % 2 == 0:
            beko_graph[
                i] = '

' + \
                     beko_graph[i] + '
'
        else:
            beko_graph[i] = '

' + \
                            beko_graph[i] + '
'
        # dodawanie treści paragrafu
        beko_graph[i + 1] = '
' + beko_graph[i + 1] + '

'
        # dodawanie ścieżki do zdjęcia
        beko_graph.insert(i + 2,
                          f'
')
        i = i + 3
        j = j + 1

    # uzupełnienie kodu o znaczniki początkowe i końcowe
    graph_desc_beg = '
'
    graph_desc_end = '
'
    beko_graph = [graph_desc_beg] + beko_graph + [graph_desc_end]

    # wyświetlenie wyniku
    print("==================== Opis Graficzny ====================")
    opis_g = '\n'.join(beko_graph)
    print(opis_g + '\n\n')

    """"""""""""""""" ZDJĘCIA DO OPISU GRAFICZNEGO """""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
    imgs = sel.xpath('//div[@class="tab-content"]//img[@class="img-responsive"]//@src').extract()

    # połączenie domyślnie nieobecnego początku kodu oraz przeformatowanie zebranego tekstu na UTF-8
    for i in range(len(imgs)):
        imgs[i] = 'http://beko.pl' + imgs[i]
        imgs[i] = imgs[i].replace('\n', '')
        imgs[i] = imgs[i].replace('\r', '')

    # pobieranie zdjęć z opisu na dysk lokalny
    for i, img in enumerate(imgs):
        res = requests.get(img)
        with open(f'{file_path}/{model}/obrazki_opisu/{i}.jpg', 'wb') as file_format:
            file_format.write(res.content)

    # zmiana rozdzielczości zdjęć tak, aby szerokość wynosiła 480px. Potrzebne jest to, aby zdjęcia na stronie
    # MatrixMedia wyświetlały się prawidłowo w dwóch kolumnach
    for i in range(len(imgs)):
        im = Image.open(f'{file_path}/{model}/obrazki_opisu/{i}.jpg')
        file_format = im.format
        width, height = im.size
        if width > 480:
            ratio = width / 480
            new_width = round(width / ratio)
            new_height = round(height / ratio)
            im = im.resize((new_width, new_height))
            if file_format == 'PNG':
                im.save(f'{file_path}/{model}/obrazki_opisu/{i}.jpg', 'PNG')
            elif file_format == 'JPEG':
                im.save(f'{file_path}/{model}/obrazki_opisu/{i}.jpg', 'JPEG')
            else:
                print(f"Nie umiem zrobić zdjęcia nr {i} :'( (typ {file_format}, jkbc)")
        elif width < 100:
            print(f"Zdjęcie {i}. jest wyjątkowo małe")
        else:
            print(f"Zdjęcie {i}. jest małe")

    return [opis_g, opis_k, opis_t]


tel=(input("Введите номер телефона: "))
minut=int(input("Введите время разговора(в минутах): " ))
if tel[1:4]== '343' :
    stoim=15*minut
if tel[1:4]== '381':
    stoim=18*minut
if tel [1:4] == '473':
    stoim=13*minut
if tel [1:4] == '485':
    stoim=11*minut
print("Стоимость разговора: ",stoim," рублей")


# vim:ts=4:sts=4:sw=4:expandtab

import copy
import datetime
import dateutil.parser
import glob
import json
import logging
import math
import os
import shutil
import subprocess
import sys
import tempfile
from threading import Thread
import time
import uuid

from kolejka.common import kolejka_config, foreman_config
from kolejka.common import KolejkaTask, KolejkaResult, KolejkaLimits
from kolejka.common import MemoryAction, TimeAction
from kolejka.client import KolejkaClient
from kolejka.worker.stage0 import stage0

def foreman_single(temp_path, client, task):
    config = foreman_config()
    with tempfile.TemporaryDirectory(temp_path) as jailed_path:
        if task.limits.storage is not None:
            subprocess.run(['mount', '-t', 'tmpfs', '-o', 'size='+str(task.limits.storage), 'none', jailed_path], check=True)
        try:
            task_path = os.path.join(jailed_path, 'task')
            result_path = os.path.join(jailed_path, 'result')
            temp_path = os.path.join(jailed_path, 'temp')
            os.makedirs(task_path, exist_ok=True)
            os.makedirs(result_path, exist_ok=True)
            os.makedirs(temp_path, exist_ok=True)
            task.path = task_path
            client.task_get(task.id, task_path)
            for k,f in task.files.items():
                f.path = k
            task.commit()
            stage0(task.path, result_path, temp_path=temp_path, consume_task_folder=True)
            result = KolejkaResult(result_path)
            result.tags = config.tags
            client.result_put(result)
        finally:
            if task.limits.storage is not None:
                subprocess.run(['umount', '-l', jailed_path])

def foreman():
    config = foreman_config()
    limits = KolejkaLimits()
    limits.cpus = config.cpus
    limits.memory = config.memory
    limits.pids = config.pids
    limits.storage = config.storage
    limits.time = config.time
    limits.network = config.network
    client = KolejkaClient()
    while True:
        try:
            tasks = client.dequeue(config.concurency, limits, config.tags)
            if len(tasks) == 0:
                time.sleep(config.interval)
            else:
                while len(tasks) > 0:
                    resources = KolejkaLimits()
                    resources.update(limits)
                    processes = list()
                    cpus_offset = 0
                    for task in tasks:
                        if len(processes) >= config.concurency:
                            break
                        if task.exclusive and len(processes) > 0:
                            break
                        task.limits.update(limits)
                        task.limits.cpus_offset = cpus_offset
                        ok = True
                        if resources.cpus is not None and task.limits.cpus > resources.cpus:
                            ok = False
                        if resources.memory is not None and task.limits.memory > resources.memory:
                            ok = False
                        if resources.pids is not None and task.limits.pids > resources.pids:
                            ok = False
                        if resources.storage is not None and task.limits.storage > resources.storage:
                            ok = False
                        if ok:
                            proc = Thread(target=foreman_single, args=(config.temp_path, client, task))
                            proc.start()
                            processes.append(proc)
                            cpus_offset += task.limits.cpus
                            if resources.cpus is not None:
                                resources.cpus -= task.limits.cpus
                            if resources.memory is not None:
                                resources.memory -= task.limits.memory
                            if resources.pids is not None:
                                resources.pids -= task.limits.pids
                            if resources.storage is not None:
                                resources.storage -= task.limits.storage
                            tasks = tasks[1:]
                            if task.exclusive:
                                break
                        else:
                            break
                    for proc in processes:
                        proc.join()
        except:
            time.sleep(config.interval)

def config_parser(parser):
    parser.add_argument('--auto-tags', type=bool, help='add automatically generated machine tags', default=True)
    parser.add_argument('--tags', type=str, help='comma separated list of machine tags')
    parser.add_argument('--temp', type=str, help='temp folder')
    parser.add_argument('--interval', type=float, help='dequeue interval (in seconds)')
    parser.add_argument('--concurency', type=int, help='number of simultaneous tasks')
    parser.add_argument('--cpus', type=int, help='cpus limit')
    parser.add_argument('--memory', action=MemoryAction, help='memory limit')
    parser.add_argument('--pids', type=int, help='pids limit')
    parser.add_argument('--storage', action=MemoryAction, help='storage limit')
    parser.add_argument('--time', action=TimeAction, help='time limit')
    parser.add_argument('--network',type=bool, help='allow netowrking')
    def execute(args):
        kolejka_config(args=args)
        foreman()
    parser.set_defaults(execute=execute)


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

import webapp2
import logging
import os
import jinja2
from datetime import date
from google.appengine.ext import ndb

JINJA_ENVIRONMENT = jinja2.Environment(
    loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
    extensions=['jinja2.ext.autoescape'],
    autoescape=True
)

class UserData(ndb.Model):
    name = ndb.StringProperty()
    age = ndb.IntegerProperty()
    date = ndb.DateTimeProperty(auto_now_add=True)

class BaseHandler(webapp2.RequestHandler):
    def render(self,html,values={}):
        template = JINJA_ENVIRONMENT.get_template(html)
        self.response.write(template.render(values))

class MainHandler(BaseHandler):
    def get(self):
        users = UserData.query().order(-UserData.date).fetch(10)
        values = {'users': users}
        self.render('main.html', values)

    def post(self):
        name = self.request.get('name')
        age_str = self.request.get('age')
        if name is None or age_str is None:
            self.redirect('/')

        user = UserData()
        user.name = name
        user.age = int(age_str)
        user.put()
        self.redirect('/')

class SayHandler(webapp2.RequestHandler):
    def get(self):
        logging.info("============= /say ==============")
        self.response.write('Say hello')

class Message(ndb.Model):
    name = ndb.StringProperty()
    email = ndb.StringProperty()
    msg = ndb.StringProperty()
    postedon = ndb.DateTimeProperty(auto_now_add=True)

class MyPage(BaseHandler):
    def get(self):
        messages = ndb.gql("SELECT * FROM Message ORDER BY postedon DESC")
        values = {'messages': messages}
        self.render('bbs.html', values)

    def post(self):
        message = Message()
        message.name = self.request.get('name')
        message.msg = self.request.get('msg')
        message.email = self.request.get('email')
        message.put()

        self.redirect('/bbs')

app = webapp2.WSGIApplication([
    ('/', MainHandler),
    ('/say', SayHandler),
    ('/bbs', MyPage)
], debug=True)


import random

from mesa import Agent
import math

#from random_walk import RandomWalker

#define default probability values
flamability_probs = {0:1,1:0.7,2:0.49,3:0.343,4:0.2401}
#min and max time stored by vegetation type
succession_times = {0:(5,15),1:(10,20),2:(10,20),3:(20,40),4:(20,40)}

class Landscape(Agent):
    '''
    A patch of grass that grows at a fixed rate and it is eaten by sheep
    '''

    def __init__(self, pos, model, elevation, burn_s_m_p, burn_s_t_p, vegetation_type, is_patch_burned,
                 time_colonised, is_patch_colonised, succ_s_m_p, succ_s_t_p):

        super().__init__(pos, model)
        self.elevation = elevation
        self.burn_s_m_p=burn_s_m_p
        self.burn_s_t_p=burn_s_t_p
        self.succ_s_m_p = succ_s_m_p
        self.succ_s_t_p = succ_s_t_p
        self.vegetation_type = vegetation_type
        self.is_patch_burned = is_patch_burned
        self.breed = "Landscape"
        self.time_since_last_burnt = 0
        self.time_colonised = time_colonised
        self.is_patch_colonised = is_patch_colonised
        # get all agents in dispersal range
        radius = self.model.grid.get_neighbors(pos, 50, False)
        # filter agent list so that only those in landscape are considered
        self.dispersal_radius = list(filter(lambda x: x.breed == "Landscape", radius))
        self.dispesal_patch_count = len(self.dispersal_radius)

        # flamability probs stored in dictionary by veg type

        self.succ_prob = {0: succession_prob_calc(succession_times[0][0],succession_times[0][1]),
                     1: succession_prob_calc(succession_times[1][0],succession_times[1][1]),
                     2: succession_prob_calc(succession_times[2][0],succession_times[2][1]),
                     3: succession_prob_calc(succession_times[3][0],succession_times[3][1]),
                     4: succession_prob_calc(succession_times[4][0],succession_times[4][1])}

    #automatically update the flamability value when vegetation type is changed
    @property
    def flamability(self):
        return flamability_probs[self.vegetation_type]

    #automatically update succession times based on veg type
    @property
    def min_succession_time(self):
        return succession_times[self.vegetation_type][0]

    @property
    def max_succession_time(self):
        return succession_times[self.vegetation_type][1]

    @property
    def succession_probability(self):
        return self.succ_prob[self.vegetation_type]

    @staticmethod
    def fire_front(patches_to_burn):
        while len(patches_to_burn) != 0:
            patches_to_burn_new = []
            for this_patch in patches_to_burn:
                neighbours = this_patch.model.grid.get_neighbors(this_patch.pos, 1, False)
                #filter list of neighbours to only those that are landcape based and not burned
                land_scape_neighs = list(filter(lambda x: x.breed == 'Landscape' and x.is_patch_burned == False, neighbours))
                for neigh_patch in land_scape_neighs:
                    slope = math.atan(abs(neigh_patch.elevation - this_patch.elevation) / 1000)
                    if this_patch.elevation >= neigh_patch.elevation:
                        slope_burn_prob = (math.exp(3.533 * (math.tan(slope) ** 1.2)))
                    else:
                        slope_burn_prob = (1 - 0.033 * slope + 0.000749 * slope * 2) * math.cos(slope)
                    if random.random() <= 0.57 * slope_burn_prob and does_this_patch_burn(neigh_patch):
                        neigh_patch.is_patch_burned = True
                        patches_to_burn_new.append(neigh_patch)

            patches_to_burn = patches_to_burn_new

    def step(self):
        if self.is_patch_burned == True:
            # this will automatically update flamability
            self.vegetation_type = 0
            self.is_patch_burned = False
            self.is_patch_colonised = 0
            self.time_colonised = 0
        if self.is_patch_colonised == 1:
            self.succession()
        elif self.is_patch_colonised == 0:
            self.dispersal()

    def succession(self):
        self.time_colonised += 1
        #Should maybe include rule to succeed if max colonised time is reached?
        if self.vegetation_type <= 3 and self.time_colonised >= self.min_succession_time:
            if random.random() <= self.succession_probability * self.succ_s_m_p * self.succ_s_t_p * self.model.rainfall_this_year * self.model.temp_this_year:
                self.vegetation_type += 1
                #will further colonisation be required for succession?
                if self.vegetation_type == 1 or self.vegetation_type == 2:
                    self.is_patch_colonised = 0
            self.time_colonised = 0

    def dispersal(self):
        if self.vegetation_type == 0:
            self.is_patch_colonised = 1
        else:
            potential_dis_patches = list(filter(lambda x: x.vegetation_type > self.vegetation_type, self.dispersal_radius))
            try:
                if random.random() <= (len(potential_dis_patches) / self.dispesal_patch_count):
                    self.is_patch_colonised = 1
            except ZeroDivisionError:
                return
        return

class Lightning(Agent):

    def __init__(self, pos, model):
        super().__init__(pos, model)
        self.breed = "Lightning"

    def step(self):
        # Create lightning strikes

        x = random.randrange(self.model.width)
        y = random.randrange(self.model.height)
        strike = Lightning((x, y), self.model)
        self.model.grid.place_agent(strike, (x, y))
        self.model.schedule.add(strike)
        potential_to_burn = []
        struck_land = False

        this_cell = self.model.grid.get_cell_list_contents((x, y))

        #Check to see if lighning hits land
        for obj in this_cell:
            if obj.breed == "Landscape":
                patch_veg = obj
                struck_land = True

        if struck_land == True:
            if patch_veg.is_patch_burned == False:
                if does_this_patch_burn(patch_veg):
                    patch_veg.is_patch_burned = True
                    potential_to_burn.append(patch_veg)
                    Landscape.fire_front(potential_to_burn)

        self.model.grid._remove_agent(self.pos, self)
        self.model.schedule.remove(self)

'''
Early ideas:
This agent should be created as a result of fire - several factors to consider:
1. Size of fire - Macroscopic/Microscopic - will determine how far it travels
2. Wind direction
3. Distance to deposition site - this will mean accurately identifying swamps/lakes on grid
4. Type of vegetation burning
'''
class charcoal(Agent):
    def __init__(self, pos, model, size_of_fire, vegetation_type_burning):
        print("charoal born!")

'''
Early ideas:
This agent should be created each tick??:
1. Amount of pollen produced - could be tricky to portray accurately as varied at species level
2. Age of species/functional type to be considered
2. Distance from deposition site - Can travel along way, maybe not so important
3. New class may not be needed and could just simply be a function of vegetation class?

First Steps!
1. Get center of deposition site...
'''
class pollen(Agent):
    def __init__(self, pos, model, pollen_type):
        print("pollen born!")

'''
Early ideas:
Should be born/die given set birth and death rates:
1. How many fires how often?
2. How many people of GBI before European arrival
3. Where did they go, why? Look at settlement records
'''
class tribe(Agent):
    def __init__(self, pos, model):
        print("Human born, we're all fucked!")

class Deposition_site(Agent):
    def __init__(self, pos, model, deposition_area):
        self.deposition_area = deposition_area
        self.breed = "deposition"

def does_this_patch_burn(patch_veg):
    if random.random() <= patch_veg.flamability * patch_veg.burn_s_m_p * patch_veg.burn_s_t_p\
            * patch_veg.model.rainfall_this_year * patch_veg.model.temp_this_year:
        return True
    else:
        return False

def succession_prob_calc(min, max):
    prob = 1 - (1 - 0.95) ** (1 / (min - max))
    return abs(prob)


import cv2
from matplotlib import pyplot as plt
import numpy as np

imgL = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_L.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
imgR = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_R.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
imgL_colour = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_L.jpg', 1)
imgL_colour = cv2.cvtColor(imgL_colour, cv2.COLOR_BGR2RGB)
imgL_green = imgL_colour[:, :, 1]
imgL_green = np.bitwise_not(imgL_green)
imgL_red = imgL_colour[:, :, 0]
imgL_blue = imgL_colour[:, :, 2]
# imgR_colour = cv2.imread('0A0B4D50-A986-4659-9E5E-2A9BBF19D594_OD_1_R.jpg', 1)
# imgR_colour = cv2.cvtColor(imgR_colour, cv2.COLOR_BGR2RGB)
# rows = imgL.shape[0]
# cols = imgR.shape[1]
# stereo = cv2.StereoBM(cv2.STEREO_BM_BASIC_PRESET, ndisparities=0, SADWindowSize=27)
# disparity = stereo.compute(imgL, imgR)
# # diff = cv2.add(imgL, imgR)
# threshL = cv2.adaptiveThreshold(imgL, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 433, 0)
# threshR = cv2.adaptiveThreshold(imgR, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 433, 0)
# contoursL, hierarchy = cv2.findContours(threshL, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# contoursR, hierarchy2 = cv2.findContours(threshR, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# cv2.drawContours(imgL_colour, contoursL, -1, (255, 255, 255), 1)
# cv2.drawContours(imgL_colour, contoursR, -1, (255, 255, 255), 1)

# pixelShift_y = abs(np.argmax(imgL) // cols - np.argmax(imgR) // cols)  # rows shifted
# pixelShift_x = abs(np.argmax(imgL) % cols - np.argmax(imgR) % cols)  # columns shifted
# 120, 1695
# 891, 916

plt.figure()
plt.title('Red')
plt.imshow(imgL_red)
plt.figure()
plt.title('Green')
plt.imshow(imgL_green, 'Greens')
plt.figure()
plt.title('Blue')
plt.imshow(imgL_blue)
plt.show()
'''
commonPix = []
for i in range(0, rows):
    trueIndex = np.where(indices[i] == True)
    for item in trueIndex[0]:
        commonPix.append([i, item+1])
commonPix = np.array(commonPix)

for item in commonPix:
    diff[item[0], item[1]] = 255
'''


import libnum
import Crypto.Util.number
from random import randint
#Crypto.Util.number.getPrime là hàm tạo số nguyên tố ngẫu nhiên với số bits theo yêu cầu
bits = 16
print("Số bit yêu cầu của bài là:", bits)
# Chọn p,a,b
p = Crypto.Util.number.getPrime(bits, randfunc=Crypto.Random.get_random_bytes)
a = 50
b = 90
print("\nThu được đường cong y^2 = x^3 +",a,"x +",b,"mod(",p,")")
#Tạo đường cong bằng hàm ecc.Curve
curve = libnum.ecc.Curve(a, b, p)

# Hiển thị các điểm có hoành độ nằm trong khoảng từ 1 đến 100
P100=curve.find_points_in_range(1,100)
print(P100)

N = 1
for x in range(p):
    for y in range(p):
        if (y*y - x*x*x - a*x -b) % p == 0:
            N = N + 1

print("Hai bên A và B thống nhất với nhau đường cong E trên trường Fp:","\nE: y^2 = x^3 +",a,"x +",b,"\nFp với p =",p)
#Bên A Chọn bản tin như điểm M thuộc đường cong E, mà số nguyên bí mật mA thỏa mãn gcd(mA,N) = 1
#N là số điểm của đường cong. Nhưng với số bits lớn việc tính tổng số điểm mất nhiều thời gian,phức tạp, phần cứng máy tính chưa đảm bảo
# ==> Để thuận tiện trong demo chọn p khoảng 16bit
#N = p
print("N = ",N)
# Bên A Tính M1=(mA)M rồi gửi cho bên B
M = P100[50]
mA = 5683 #Chọn mA là số nguyên tố
M1=curve.power(M,mA)
print("\nBên A Tính M1=(mA)M rồi gửi cho bên B: \nM =",M,"\nmA =",mA,"\nM1 =",M1)
# Bên B nhận M1 chọn mB thỏa mãn gcd(mB,N) = 1. Tính M2=(mB)M1 rồi gửi cho bên A
mB = 56843 #Chọn mB là số nguyên tố
M2=curve.power(M1,mB)
print("\nBên B nhận M1 chọn mB thỏa mãn gcd(mB,N) = 1. Tính M2=(mB)M1 rồi gửi cho bên A: \nM1 =",M1,"\nmB =",mB,"\nM2 =",M2)
# Bên A nhận M2 tính mA^-1 thuộc ZN. Tính M3=(mA^-1)M2 rồi gửi cho bên B
mA1 = libnum.invmod(mA,N) #Một cách khác để tính nghịch đảo modulo là dùng libnum.invmod()
M3=curve.power(M2,mA1)
print("\nBên A nhận M2 tính mA^-1 thuộc ZN. Tính M3=(mA^-1)M2 rồi gửi cho bên B: \nM2 =",M2,"\nmA^-1 =",mA1,"\nM3 =",M3)
# Bên B nhận M3 tính mB^-1 thuộc ZN. Tính M4=(mb^-1)M3 lúc này M4=M1
mB1 = libnum.invmod(mB,N)
M4=curve.power(M3,mB1)
print("\nBên B nhận M3 tính mB^-1 thuộc ZN. Tính M4=(mB^-1)M3 rồi gửi cho bên B: \nM3 =",M3,"\nmB^-1 =",mB1,"\nM4 =",M4,"\nĐiểm M ban đầu:",M)
if M == M4:
    print("Giải mã thành công....!")


import logging
import string
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from scraper.models import Base, Game
from bs4 import BeautifulSoup
from scraper.models import Game
from scraper.loggers import error_logger, info_logger

domain = 'https://gamesystemrequirements.com/'

engine = create_engine('sqlite:////home/anon/PycharmProjects/canirunthis-scraper/games.db', echo=True)
Session = sessionmaker(bind=engine)
Base.metadata.create_all(engine)
session = Session()

def fetch_page(url):

    try:
        with closing(get(url, stream=True)) as resp:
            if is_good_response(resp):
                return resp.content
            else:
                return None
    except RequestException as e:
        error_logger.exception(e)

def is_good_response(resp):
    """
    Returns True if the response seems to be HTML, False otherwise.
    """
    content_type = resp.headers['Content-Type'].lower()
    return (resp.status_code == 200
            and content_type is not None
            and content_type.find('html') > -1)

def test():
    letters = list(string.ascii_lowercase)
    for l in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k']:
        letters.remove(l)
    for char in letters:
        root_page = "https://gamesystemrequirements.com/database/{}".format(char)
        root_page_html = fetch_page(root_page)
        bs4_root_page = BeautifulSoup(root_page_html, 'html.parser')
        nav = bs4_root_page.find_all('div', class_='pagenav_c')
        pages = len(nav[0].find_all('a')) + 1 if len(nav) > 0 else 1
        for page in range(pages):
            print("STARTING PAGE {} !!!!!!!!!!!!!!!!!!!!!".format(page))
            page_html = root_page_html if page == 0 else fetch_page("{}/page/{}".format(root_page, page+1))
            get_games_on_page(page_html)
            print('FINISHED PAGE!!!!!!!!!!!!!!!!!!!!!')

def get_games_on_page(html):
    bs4_root_page = BeautifulSoup(html, 'html.parser')
    table = bs4_root_page.find_all('table', class_='database_t')[0]
    rows = table.find_all('tr')
    for row in rows:
        game_link = domain + row.find_all('a', href=True)[0]['href']
        get_game_specs(game_link)

def get_game_specs(url):
    gaml_page_html = fetch_page(url)
    bs4_game_page = BeautifulSoup(gaml_page_html, 'html.parser')
    title = bs4_game_page.find_all('div', class_='game_head_title')[0].text
    main_panel = bs4_game_page.find_all('div', class_='main-panel')[0].find_all('div')[0]
    rows = main_panel.find_all('div', class_='srb_row')
    game = {}
    game['title'] = title
    for row in rows:
        subrows = row.find_all('div', class_='tbl')
        len_subrows = len(subrows)
        if len_subrows == 2 or len_subrows == 4:
            col = subrows[0].find_all('b')[0].text.replace(':', '').strip().lower()
            val = subrows[1].text.strip()
            if val.find(domain) > -1:
                val = val.replace(domain, '')
            game[col] = val
    game = Game(**game)
    session.add(game)
    session.commit()


from time import sleep
from selenium import webdriver
from selenium.webdriver.common.by import By

chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
driver = webdriver.Chrome(chrome_options=chrome_options)

# open the url
driver.get('https://www.amazon.com')
sleep(2)
search_button = driver.find_element(By.XPATH, "//div[@id='nav-signin-tooltip']//a[@class='nav-action-button'][@data-nav-role='signin']")
search_button.click()

# Amazon logo
search_logo = driver.find_element(By.XPATH, "//div[@id='a-page']//i[@class='a-icon a-icon-logo'][@role='img']")

# Email field
search_email = driver.find_element(By.XPATH, "//div[@class='a-row a-spacing-base']//input[@type='email']")

# Continue button
search_continue_button = driver.find_element(By.XPATH, "//input[@id='continue']")

# Need help link
search_need_h_link = driver.find_element(By.XPATH, "//div[@class='a-section']//span[@class='a-expander-prompt']")

# Forgot your password link
# Other issues with sign-in link
# "Create your Amazon account" button
search_create_account = driver.find_element(By.XPATH, "//a[@id='createAccountSubmit']")

# Conditions of use link
search_conditions_of_use = driver.find_element(By.XPATH, "//div[@id='legalTextRow']//a[text()='Conditions of Use']")

# Privace notice link
search_privace_notice = driver.find_element(By.XPATH, "//div[@id='legalTextRow']//a[@href='/gp/help/customer/display.html/ref=ap_signin_notification_privacy_notice?ie=UTF8&nodeId=468496']")

driver.quit()


def wordCounter():  # define function
    try:

        with open("File_to_be_counted.txt", "r") as inFile, open("output1.txt","w") as outFile:   # open the file in reading mode
            words = []  # list to save all the words
            word = ""
            for line in inFile:  # loop through every line in the file
                for word in line.split():  # split at every word and append the word to the list
                    words.append(word)

    except FileNotFoundError:
        print("Wrong file or path does not exist. Please make sure file exists or is named correctly")

wordCounter()


# I want to be able to call cumulative_sum from main w/ various lists and
# get returned a list of the cumulative sums.
# You are safe to expect only integers in a flat list.
# Ex. the cumulative sum of [1, 2, 3] is [1, 3, 6]
#  - in the above example I want returned the list [1, 3, 6]
# In your final submission:
#  - Do not print anything extraneous!
#  - Do not put anything but pass in main()

def cumulative_sum(number_list):
    new_sum_list = []
    sum_num = 0
    for number in number_list:
        sum_num += number
        new_sum_list.append(sum_num)
    return new_sum_list

def main():
    sample_list = [1, 2, 3]
    sample_list2 = [1, 20, 30]
    print(cumulative_sum(sample_list))
    print(cumulative_sum(sample_list2))

if __name__ == '__main__':
    main()


#!/usr/bin/env python3

import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from mlxtend.preprocessing import TransactionEncoder
from mlxtend.frequent_patterns import apriori

engine = create_engine("sqlite:///mag.db")
con = engine.connect()
Session = sessionmaker(bind=engine)

clusters_df = pd.read_sql_table("clusters", con)
nc_df = clusters_df[clusters_df["novel"]==1]
catalog = set(nc_df[nc_df["size"] > 10]["cluster_id"])

bag_fp = "bag.csv"
bag_df = pd.read_csv(bag_fp)
transactions = []
for bag in bag_df["bag"].dropna():
    transaction = [int(e) for e in bag.split(';') if int(e) in catalog]
    if len(transaction) > 0:
        transactions.append(transaction)

te = TransactionEncoder()
te_ary = te.fit(transactions).transform(transactions)
df = pd.DataFrame(te_ary, columns=te.columns_)
apriori_df = apriori(df, min_support=20/len(df))
apriori_df.to_csv("apriori.csv", index=False)


"""Add config_settings

Revision ID: 34bb537756b5
Revises:
Create Date: 2021-08-19 15:02:11.396558

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '34bb537756b5'
down_revision = None
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('config_settings',
    sa.Column('namespace', sa.String(length=64), nullable=False),
    sa.Column('group', sa.String(length=64), nullable=False),
    sa.Column('key', sa.String(length=255), nullable=False),
    sa.Column('type', sa.String(length=24), nullable=False),
    sa.Column('value', sa.LargeBinary(), nullable=False),
    sa.PrimaryKeyConstraint('namespace', 'group', 'key')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('config_settings')
    # ### end Alembic commands ###


from datetime import datetime
import json
import os
from django.test import TestCase
from corehq.apps.commtrack.models import Product as Prod
from corehq.apps.commtrack.tests.util import bootstrap_domain as initial_bootstrap
from custom.ilsgateway.api import Product, ILSGatewayAPI
from custom.logistics.commtrack import synchronization
from custom.logistics.models import MigrationCheckpoint
from custom.ilsgateway.tests.mock_endpoint import MockEndpoint

TEST_DOMAIN = 'ilsgateway-commtrack-product-test'

class ProductSyncTest(TestCase):

    def setUp(self):
        self.endpoint = MockEndpoint('http://test-api.com/', 'dummy', 'dummy')
        self.api_object = ILSGatewayAPI(TEST_DOMAIN, self.endpoint)
        self.datapath = os.path.join(os.path.dirname(__file__), 'data')
        initial_bootstrap(TEST_DOMAIN)
        for product in Prod.by_domain(TEST_DOMAIN):
            product.delete()

    def test_create_product(self):
        with open(os.path.join(self.datapath, 'sample_products.json')) as f:
            product = Product(json.loads(f.read())[0])
        self.assertEqual(0, len(Prod.by_domain(TEST_DOMAIN)))
        ilsgateway_product = self.api_object.product_sync(product)
        self.assertEqual(product.sms_code, ilsgateway_product.code.lower())
        self.assertEqual(product.name, ilsgateway_product.name)
        self.assertEqual(product.description, ilsgateway_product.description)
        self.assertEqual(product.units, str(ilsgateway_product.unit))

    def test_locations_migration(self):
        checkpoint = MigrationCheckpoint(
            domain=TEST_DOMAIN,
            start_date=datetime.now(),
            date=datetime.now(),
            api='product',
            limit=100,
            offset=0
        )
        synchronization('product',
                        self.endpoint.get_products,
                        self.api_object.product_sync, checkpoint, None, 100, 0)
        self.assertEqual('product', checkpoint.api)
        self.assertEqual(100, checkpoint.limit)
        self.assertEqual(0, checkpoint.offset)
        self.assertEqual(6, len(list(Prod.by_domain(TEST_DOMAIN))))


import numpy as np
from matplotlib.patches import Circle, Wedge, Polygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
from collections import namedtuple, OrderedDict
import copy as cp

from typing import NewType

from recordclass import recordclass, RecordClass

#import contextlib
#with contextlib.redirect_stdout(None):
#    import pixiedust

System = namedtuple('System', [
    'radius',   # inital, relaxed radius
    'num_balls',     # number of balls to model the balloon
    'center',   # center of the balloon
    'm',        # mass of the balls
    'ball_radius',  # radius of the balls for visualization
    'k',        # spring constant for each spring
    'x0',       # sprint length at equilibrium
    'delP',     # pressure difference between outside and inside
    'dt',       # time step
    'max_iters',  # max number of sol iterations
])

Point = NewType('Point', np.array)

class Ball(object):
    X = 0
    Y = 1

    def __init__(self, x: float = 0, y: float = 0, mass: float = 1, color=None, radius:float = 1):
        self._pos = np.array([x, y])
        self._color = color
        self._mass = mass
        self._radius = radius

    def __str__(self):
        return 'pos=(' + str(self._pos[self.X]) + ', ' + str(self._pos[self.Y]) + '), mass=' + \
               str(self._mass)

    def set_pos(self, new_pos: np.array):
        self._pos = new_pos

    def get_pos(self):
        return self._pos

    def move(self, vector: np.array):
        self._pos = self._pos + vector

    def draw(self, ax):
        pass

class Spring(object):
    #def __init__(self, point1: np.array, point2: np.array, k: float = 1.0):
    def __init__(self, point1: np.array, point2: np.array, k: float = 1.0):
        self._p = point1
        self._q = point2
        self._k = k
        self._length0 = 0

    def get_force(self, x):
        return -self._k*x

class BallsAndSpringsSystem(object):
    Neighbor = namedtuple('Neighbor', ['ball', 'spring', ])

    def __init__(self, ):
        self._balls = []
        self._springs = []
        self._neighbors = OrderedDict()

    def draw(self, ax=None):
        pass

class StraightChain(BallsAndSpringsSystem):
    BOUNDARY_RIGID = 0
    BOUNDARY_OPEN = 1

    def __init__(self, num_balls: int, ball_mass: float = 1.0, spring_const: float = 1.0, spring_length: float = 1.0,
                 left_boundary: int = BOUNDARY_OPEN, right_boundary: int = BOUNDARY_RIGID):
        super().__init__()
        self._num_balls = num_balls
        self._ball_mass = ball_mass
        self._spring_const = spring_const
        self._spring_length = spring_length
        self._left_boundary = left_boundary
        self._right_boundary = right_boundary
        self._create()

    def _create(self):
        y = 0
        x = 0
        prev_ball = None
        prev_spring = None
        if self._left_boundary == self.BOUNDARY_RIGID:
            spring = Spring(np.array([x - self._spring_length, y]), np.array(x, y), k=self._spring_const)
            self._springs.append(spring)
            prev_spring = spring

        for idx in range(self._num_balls):
            new_x = x + idx*self._spring_length
            ball = Ball(x=new_x, y=y, mass=self._ball_mass)
            self._balls.append(ball)

            last_element = (idx < self._num_balls)
            spring = None
            if not last_element or self._right_boundary == self.BOUNDARY_RIGID:
                spring = Spring(np.array([new_x, y]), np.array([new_x + self._spring_length, y]), k=self._spring_const)
                self._springs.append(spring)

            valid_neigh = not (prev_spring is None and prev_ball is None)
            if valid_neigh:
                neigh = self.Neighbor(ball=prev_ball, spring=prev_spring)
                self._neighbors[ball] = neigh
            prev_ball, prev_spring = ball, spring

        if self._right_boundary == self.BOUNDARY_RIGID:
            neigh = self.Neighbor(ball=None, spring=prev_spring)
            self._neighbors[ball] = neigh

class Simulator(object):
    def __init__(self, system: BallsAndSpringsSystem):
        self._sys = system

    def run(self):
        pass

class Ball2(object):
    X = 0
    Y = 1

    def __init__(self, x=0, y=0, neigh1=None, neigh2=None):
        self.xy = np.array([x,y])
        self.neigh1 = neigh1
        self.neigh2 = neigh2
        self.color = None
        self.mass = 1

    def __str__(self):
        return '(' + str(self.xy[self.X]) + ', ' + str(self.xy[self.Y]) + ', ' + \
               str(type(self.neigh1)) + ', ' + str(type(self.neigh2)) + ')'

    def set_xy(self, xy):
        self.xy = xy

    def get_xy(self):
        return self.xy

    def set_neigh1(self, b1):
        self.neigh1 = b1

    def set_neigh2(self, b2):
        self.neigh2 = b2

    def calc_norm_and_dir(self, v):
        #print("DBG: v = " + str(v))
        x = v[self.X]
        y = v[self.Y]
        r = np.sqrt(x*x + y*y)
        #print("DBG: r = " + str(r))
        u = v/r
        #print("DBG: u = " + str(u))
        return r, u

    def get_neigh_vector(self, neigh):
        cv = self.xy - neigh._pos
        #print("DBG: cv = " + str(cv))
        c, cu = self.calc_norm_and_dir(cv)
        return c, cu

    def calc_del_area(self, c1, c2):
        return (c1+c2)/2

    def calc_tension(self, c, cu, k, c0):
        del_c = c - c0
        del_cv = del_c * cu
        #spring force
        F = -del_cv*k
        return F

    def calc_pressure_force(self, del_area, pressure, center):
        rv = self.xy - center
        r, ru = self.calc_norm_and_dir(rv)
        #del_area = 1
        F = del_area * pressure * ru
        return F

    def calc_next_position(self, sys):
        if self.neigh1 is not None:
            c1, cu1 = self.get_neigh_vector(self.neigh1)
            #print("DBG: cu1 = " + str(cu1))
            T1 = self.calc_tension(c1, cu1, sys.k, sys.x0)
        else:
            T1 = np.array([0, 0])
        if self.neigh2 is not None:
            c2, cu2 = self.get_neigh_vector(self.neigh2)
            T2 = self.calc_tension(c2, cu2, sys.k, sys.x0)
        else:
            T2 = np.array([0, 0])

        #del_area = self.calc_del_area(c1, c2)
        del_area = 1
        Fp = self.calc_pressure_force(del_area, sys.delP, sys.center)

        #print("DBG T1 = " + str(T1) + " T2 = " + str(T2) + " FP = " + str(Fp))

        Fnet = T1 + T2 + Fp
        a = Fnet/sys.m
        #print(a)
        delxy = 1/2 * a * sys.dt * sys.dt
        xy = self.xy + delxy

        return xy

class Balloon(object):
    def __init__(self, radius=1, num_balls=25, center=np.array([0, 0])):
        self._balls = []
        self._sticks = []
        self._radius = radius
        self._num_balls = num_balls
        self._center = center
        self._create()

    def _create(self):
        xs, ys = create_polygon(radius=self._radius, N=self._num_balls, x0=self._center[0], y0=self._center[1])
        self._balls = []
        self._sticks = []
        for x, y in zip(xs, ys):
            b = Ball2(x, y)
            self._balls.append(b)
            self._num_balls = len(self._balls)
        for idx, b in enumerate(self._balls):
            b.set_neigh1(self._balls[idx - 1])
            b.set_neigh2(self._balls[(idx + 1) % self._num_balls])

    def relax(self, sys, verbosity=1):
        iter_results = []
        for it in range(sys.max_iters):
            new_xys = []
            for idx, b in enumerate(self._balls):
                new_xy = b.calc_next_position(sys)
                # print("new XY: " + str(new_xy))
                new_xys.append(new_xy)

            del_xys = 0
            for idx, ball in enumerate(self._balls):
                # print("OLD: " + str(ball))
                del_xy = ball.get_xy() - new_xys[idx]
                del_xy = np.sqrt(del_xy[0] * del_xy[0] + del_xy[1] * del_xy[1])
                del_xys += del_xy / np.sqrt(sys.num_balls)

                ball.set_xy(new_xys[idx])
                # print("NEW: " + str(ball))
                if verbosity > 1:
                    print('Itr # {:.0f} dx = {:.4G}'.format(it, del_xys))
            new_balloon = cp.deepcopy(self)
            iter_results.append(new_balloon)
            if del_xys < 0.1:
                if verbosity > 0:
                    print('Itr # {:.0f} dx = {:.4G}'.format(it, del_xys))
                    print('Converged')
                break

        return iter_results

    def inflate(self, sys, verbosity=1):
        return self.relax(sys, verbosity)

    def puncture(self, sys, verbosity=1):
        ### balloon[len(balloon)-1].set_neigh2(None)
        ### balloon[0].set_neigh1(None)
        self._balls[0].set_neigh2(None)
        self._balls[1].set_neigh1(None)
        return self.relax(sys, verbosity)

    def draw(self):
        pass

class BalloonViewer(object):
    def __init__(self, balloon):
        pass

# Todo
# --------
# - Reduce pressure with time
# - Going back to initial shape after busting
# - Volume to pressure conversion
#
# - Plotting improvements
# - Animation

def plot_balls_and_sticks(xs, ys, radius,
                          stick_color=None, ball_color=None, ball_alpha=0.9,
                          xlim=[-50,50], ylim=[-50,50],
                          draw_axes='off', ax=None):
    #print(xs)
    #print(ys)
    radii = radius*np.ones(xs.size)

    if ax is None:
        fig, ax = plt.subplots()
        #plt.ion()
        #plt.show()

    patches = []
    dr = 0
    for x1, y1, r in zip(xs, ys, radii):
        circle = Circle((x1, y1), r+dr)
        patches.append(circle)
        dr += r/len(xs)

    #colors = 100 * np.random.rand(len(patches))
    p = PatchCollection(patches, alpha=ball_alpha)
    #p.set_array(colors)
    ax.plot(xs, ys, '-')
    ax.add_collection(p)
    ax.set_aspect('equal')
    #fig.colorbar(p, ax=ax)
    plt.axis(draw_axes)
    #plt.xlim(xlim)
    #plt.ylim(ylim)
    plt.grid()

    #plt.draw()
    #plt.show()

    return ax

def plot_balls(balls, radius, stick_color=None, ball_color=None, ball_alpha=0.9, ax=None, draw_axes='off'):
    xs = []
    ys = []
    for ball in balls:
        xs.append(ball._pos[ball.X])
        ys.append(ball._pos[ball.Y])
    #xs.append(balls[0].xy[ball.X])
    #ys.append(balls[0].xy[ball.Y])
    #print(xs)
    #print(ys)
    return plot_balls_and_sticks(np.array(xs), np.array(ys), radius, stick_color, ball_color, ball_alpha, ax=ax, draw_axes=draw_axes)

def create_polygon(radius, N=25, x0=0, y0=0):
    two_pi = 2*np.pi
    th = np.linspace(0, two_pi*(N-1)/N, N)
    x = x0 + radius*np.sin(th)
    y = y0 + radius*np.cos(th)
    return x, y

##small_radius=0.5
##x, y = get_circle_balloon(radius=5)
##plot_balls_and_sticks(x, y, small_radius)
##x, y = get_circle_balloon(radius=10)
##plot_balls_and_sticks(x, y, small_radius)
##
##balloon = create_balloon(sys)
##ax = plot_balls(balloon, 0.5)
### plt.show()
### plt.tight_layout()
##
##balloon = relax_balloon(sys, balloon)
##plot_balls(balloon, 0.5, draw_axes='on')
##
### balloon[len(balloon)-1].set_neigh2(None)
### balloon[0].set_neigh1(None)
##balloon[0].set_neigh2(None)
##balloon[1].set_neigh1(None)
##
##balloon = relax_balloon(sys, balloon, plot_iterations=False)
##plot_balls(balloon, 0.5, draw_axes='on')
##
##for idx, b in enumerate(balloon):
##    print("id = " + str(idx) + ": " + str(b))


import turtle
turtle.shape('square')
turtle.penup()
turtle.goto(-100,100)
turtle.pendown()
turtle.goto(0,100)
turtle.stamp()
turtle.goto(0,0)
turtle.stamp()
turtle.goto(-100,0)
turtle.stamp()
turtle.goto(-100,100)

triangle= turtle.clone()
triangle.shape('triangle')
triangle.penup()
triangle.goto(50,50)
triangle.pendown()
triangle.goto(150,50)
triangle.stamp()
triangle.goto(100,100)
triangle.stamp()
triangle.goto(50,50)

square=turtle.clone()
square.shape('turtle')
square.penup()
square.goto(25,25)
square.stamp()
square.goto(100,150)


import tkinter
from tkinter.constants import END
import tkinter.ttk
from typing import Text
import serial
import threading
import time

'''
    調試好了：
        tcp調試好了用tk.place.froget()
        串口連接調試好了，引入一個全局變量控制綫程的開關
    未能調試好的：
        調整tcpsocket 連接

'''

# 窗口初始化，大小
tk=tkinter.Tk()
tk.title('網絡串口連接工具')
tk.geometry('1000x700')
# 創建框架
comout=tkinter.Frame(tk,bd=2,relief='ridge',width=680,height=360).place(x=300,y=30)     #輸出窗口
showconnect=tkinter.Frame(tk,bd=2,relief='ridge',width=250,height=360).place(x=30,y=30) #連接窗口
connect=tkinter.Frame(tk,bd=2,relief='ridge',width=250,height=360)                      #連接窗口
scdconnect=tkinter.Frame(tk,bd=2,relief='ridge',width=250,height=360)                   #連接窗口
osframe=tkinter.Frame(tk,bd=2,relief='ridge',width=950,height=270).place(x=30,y=400)    #輸入窗口

# 創建顯示窗口

text1= tkinter.Text(comout,width=61,height=21)
text1.place(x=305,y=35)
text1.tag_config("tag_1", foreground="red")# 創建窗口時間顯示的字體大小和顔色
text1.tag_config("tag_2", foreground="blue")# 創建窗口數據顯示的字體大小和顔色
text1.insert(END,'歡迎光臨'+'\n')

# 創建輸入窗口

text2= tkinter.Text(comout,width=90,height=16)
text2.place(x=35,y=405)
text2.tag_config("tag_2", foreground="blue")# 創建窗口數據顯示的字體大小和顔色
text2.insert(END,'在這裏輸入數據'+'\n')

# 獲取連接方式,ip地址，端口號，串口號，波特率A
whatcnt=tkinter.IntVar()
ip=tkinter.StringVar()
ip.set('192.168.0.1')
port=tkinter.IntVar()
com=tkinter.StringVar()
bote=tkinter.IntVar()
bote.set('115200')
closecon=tkinter.StringVar()

# 顯示網絡連接tcp ip 端口號
def showcnt():
    if whatcnt.get() == 1:
        scdconnect.place_forget()
        connect.place(x=30,y=30)
        # 顯示tcp窗口
        tkinter.Label(connect,text='IP地址:').place(x=20,y=120)
        tkinter.Label(connect,text='端口號:').place(x=20,y=220)
        tkinter.Entry(connect,textvariable=ip,width=12).place(x=120,y=120)
        tkinter.Entry(connect,textvariable=port,width=12).place(x=120,y=220)
    elif whatcnt.get() == 2:
        connect.pack_forget()
        scdconnect.place(x=30,y=30)
        tkinter.Label(scdconnect,text='串口號:').place(x=20,y=120)
        bote=tkinter.Label(scdconnect,text='波特率:').place(x=20,y=220)
        combobox=tkinter.ttk.Combobox(scdconnect,textvariable=com,values=('com1','com2','com3','com4','com5'),width=10)
        combobox.current(0)
        combobox.place(x=120,y=120)
        botebobox=tkinter.ttk.Combobox(scdconnect,textvariable=bote,values=(115200,57600,38400,19200,9600),width=10)
        botebobox.current(0)
        botebobox.place(x=120,y=220)
    else :
        print('打印錯誤')

#打開串口，調用串口

ser = serial.Serial()#初始化串口數據
ser.baudrate = bote.get()   #設置波特率
ser.bytesize = 8
ser.parity = serial.PARITY_NONE
ser.stopbits = 1
over_time = 30
bool=True

# 讀取串口數據
def serialcon():
    global bool
    def test():
        while bool:
            end_time=time.time()
            if end_time - starttime < over_time:
                ch = ser.readline() # 讀取一行數據   # 如果需要處理發來的數據請在這裏添加函數處理ch
                text1.insert(END,time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))+'\n',"tag_1")
                text1.insert(END,ch,"tag_2")
                text1.see(tkinter.END)
                text1.update()
    if ser.is_open== False:
        try:
            ser.port = com.get() #獲取串口號
            ser.open() # 开启串口
            starttime=time.time()
            thread=threading.Thread(target=test)
            thread.start()
        except:
            ser.close()

#他開TCP，連接TCP

# 關閉串口連接

def serialclose():
    global bool
    try:
        bool=False
        ser.close()
    except:
        print('錯誤')

def open():
    global bool
    if whatcnt.get() ==1:
        pass
    elif whatcnt.get() ==2:
        bool=True
        serialcon()
    else:
        pass

def close():
    if whatcnt.get() ==1:
            pass
    elif whatcnt.get() ==2:
        serialclose() # 關閉串口
    else:
        pass

# 創建tcp串口選擇按鈕
tcp=tkinter.Radiobutton(tk,text='網絡連接',variable=whatcnt,value=1,command=showcnt,width=10,height=1)
tcp.place(x=38,y=40)
serial2=tkinter.Radiobutton(tk,text='串口連接',variable=whatcnt,value=2,command=showcnt,width=10,height=1)
serial2.place(x=140,y=40)
# 創建連接，斷開按鈕
tkinter.Button(tk,text='連接設備',command=open,width=10,height=1).place(x=50,y=320)
tkinter.Button(tk,text='斷開設備',command=close,width=10,height=1).place(x=160,y=320)

def send():
    if whatcnt.get() ==1:
        pass
    elif whatcnt.get() ==2:
        serialsenddata=text2.get(1.0,END)
        # 如果需要處理發出去的數據請在這裏添加一個函數處理
        ser.write(serialsenddata.encode('GBK'))
    else:
        pass
# 創建發送數據按鈕
senddatabut=tkinter.Button(osframe,text='發送數據',command=send,width=10,height=1)
senddatabut.place(x=758,y=405)

tk.mainloop()


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

#        +=========================================+
#        |........♚ łαbørαŧøriø Ŧαηŧαรмα...........|
#        +-----------------------------------------+
#        |♚Coded: @DreadPirateRobertt (Telegram)   |
#        |♚Contact:telegram.me/FullPythonAlchemist |
#        |♚Date: 15/02/2017                        |
#        |♚Chanell:telegram.me/Phantasm_Lab        |
#        |♚Changing the Description of this tool   |
#        |Won't made you the coder ^_^ !!!         |
#        |♚Respect Coderz ^_^ (Open_Source_Project)|
#        |♚I take no responsibilities for the      |
#        |  use of this program !                  |
#        +=========================================+
#        |........♚ łαbørαŧøriø Ŧαηŧαรмα...........|
#        +-----------------------------------------+

import os #----------------#
import sys #---------------#
import logging #-----------#

verde = '\033[32;1m'
amarelo = '\033[1;33m'
vermelho = '\033[31;1m'
cyanClaro = '\033[1;36m'

os.system('clear')
Banner = vermelho + """
─────────────────────────────────────────────────────────────────────────────
─████████████───██████████████─██████──────────██████─██████──────────██████─
─██░░░░░░░░████─██░░░░░░░░░░██─██░░██──────────██░░██─██░░██████████──██░░██─
─██░░████░░░░██─██░░██████░░██─██░░██──────────██░░██─██░░░░░░░░░░██──██░░██─
─██░░██──██░░██─██░░██──██░░██─██░░██──────────██░░██─██░░██████░░██──██░░██─
─██░░██──██░░██─██░░██──██░░██─██░░██──██████──██░░██─██░░██──██░░██──██░░██─
─██░░██──██░░██─██░░██──██░░██─██░░██──██░░██──██░░██─██░░██──██░░██──██░░██─
─██░░██──██░░██─██░░██──██░░██─██░░██──██░░██──██░░██─██░░██──██░░██──██░░██─
─██░░██──██░░██─██░░██──██░░██─██░░██████░░██████░░██─██░░██──██░░██████░░██─
─██░░████░░░░██─██░░██████░░██─██░░░░░░░░░░░░░░░░░░██─██░░██──██░░░░░░░░░░██─
─██░░░░░░░░████─██░░░░░░░░░░██─██░░██████░░██████░░██─██░░██──██████████░░██─
─████████████───██████████████─██████──██████──██████─██████──────────██████─
─────────────────────────────────────────────────────────────────────────────
───────────────────────────────────────────────────────────────
─██████████████─██████──██████─██████████████───██████████████─
─██░░░░░░░░░░██─██░░██──██░░██─██░░░░░░░░░░██───██░░░░░░░░░░██─
─██████░░██████─██░░██──██░░██─██░░██████░░██───██░░██████████─
─────██░░██─────██░░██──██░░██─██░░██──██░░██───██░░██─────────
─────██░░██─────██░░██──██░░██─██░░██████░░████─██░░██████████─
─────██░░██─────██░░██──██░░██─██░░░░░░░░░░░░██─██░░░░░░░░░░██─
─────██░░██─────██░░██──██░░██─██░░████████░░██─██░░██████████─
─────██░░██─────██░░██──██░░██─██░░██────██░░██─██░░██─────────
─────██░░██─────██░░██████░░██─██░░████████░░██─██░░██████████─
─────██░░██─────██░░░░░░░░░░██─██░░░░░░░░░░░░██─██░░░░░░░░░░██─
─────██████─────██████████████─████████████████─██████████████─
───────────────────────────────────────────────────────────────"""

Banner2 = verde + """
▒▓▒▓▒▓▒▓▒▓▒▓─▄▀▀▀▄       +=================================================+
─██▀████▀██──▀▄▀──█      |     Download: Videos, Musicas e Playlists       |
O▀████████▀O─────█       +=================================================+
───▀█▄▄█▀────────█       | Coded: @DreadPirateRobertt                      |
──▓▒▓▒▓▒▓▒───────█       | ☎ Contact: t.me/Phantasm_Lab (@Phantasm_Lab)    |
                         | ☮ date : 15.02.2017                             |
                         +=================================================+"""

BARER = '#' * 88
DOLLA = '$' * 78
space = " " * 34

def _header(x, y):
    return "\n{}\n{}  {} | {}  {}\n".format(BARER, BARER[:17], x, y, BARER[:18])

def _formatos(x, y):
    return "{}\n{}  {} : {} {}{}".format(
        BARER, BARER[:3], x, ", ".join(y), space[:22], BARER[:3], BARER
        )

def _comands(x, y):
    return "{}\n{} {}{}|{}{}{}{}\n{}".format(
        BARER, BARER[:3], x, space[:11], space[:11], y, space, BARER[:3], BARER
        )

def _generate_options(flag, llike):
    result = []
    if flag:
        msg = ['Download Faixa de Audio (Youtube)', 'Download de uma Playlist de Audio (Youtube)']
        for item in llike:
            result.append([item, msg[0]])
            result.append(['--playlist{}'.format(item), msg[1]])
        return result
    else:
        msg = ['Download de video em formato ', 'Download de uma Playlist']
        for item in llike:
            result.append([item, msg[0] + item.split('-')[1]])
            result.append(['--playlist{}'.format(item), msg[1]])
        return result

def _generate_help_option(llike):
    result = ""
    for option, msg in llike:
        result += "\n###  {}{} >>> {}{} ###".format(
            option, " "*(24 - len(option)), msg, " "*(50 - len(msg))
            )
        if "playlist" in option:
            result += "\n{}".format(BARER)
    return result

def _usage():
    AUNIQUE = _generate_options(True, ['-mp3', '-best', '-m4a'])
    VUNIQUE = _generate_options(False, ['-mp4', '-fly', '-ogg', '-mkv', '-avi', '-webm'])

    AUDIO = "$$$ AUDIO {}\n{}".format(DOLLA, BARER) + _generate_help_option(AUNIQUE)
    VIDEOS = "$$$ VIDEOS {}\n{}".format(DOLLA[1:], BARER) + _generate_help_option(VUNIQUE)

    print(
        """{}{}\n{}""".format(
        _header('Download Music', 'Videos and Playlist Music Videos'),
        _formatos('Formatos disponiveis', ['mp3', 'mp4', 'flv', 'ogg', 'mkv', 'avi', 'webm']),
        _comands('Comands Options', 'FUNCTIONS')
        )
    )
    print(cyanClaro + AUDIO)
    print(amarelo + VIDEOS)

EXAMPLE = verde + 'Example > python2 D0nwTube.py '
MODO_DE_USO = 'Modo de uso:\n$ python2 download.py [opção] [url]'

################ HELPS ###############
MP3 = EXAMPLE + "-mp3 https://www.youtube.com/watch?v=txmvb7tbAxs&t=57s"
MP4 = EXAMPLE + "-mp4 https://www.youtube.com/watch?v=txmvb7tbAxs&t=57s"
PMP3 = EXAMPLE + "--playlist-mp3 https://www.youtube.com/playlist?list=PLQimmOQ9bzurCStHdAoBnZeRyzESSsc7q\n"
PMP4 = EXAMPLE + "--playlist-mp4 https://www.youtube.com/playlist?list=PLQimmOQ9bzurCStHdAoBnZeRyzESSsc7q\n"
OPENED_PLAYLIST = EXAMPLE + "--playlist-mp4 \"https://.../watch?v=...&index=2&list=PLQimmOQ9bzurCStHdAoBnZeRyzESSsc7q\""
LINE = (MP3, PMP3, MP4, PMP4, OPENED_PLAYLIST, " ")

def help():
    _usage()
    print(verde +  MODO_DE_USO)
    print(vermelho + '$ sudo apt-get install youtube-dl | if not installed\n')
    for LIN in LINE:
        print(LIN)

print(Banner)
print(Banner2)

ARGS_ON = False
GO_NEXT = True
EXISTS_OPTIONS = False

def check_exist_option(opt, options):
    global EXISTS_OPTIONS
    for option in options:
        if opt in option:
            EXISTS_OPTIONS = True

def program_option(nop, url):
    yep = nop.replace('--no', '--yes')
    url = "".join(url.split("\\"))  # zsh: watch\?v\=, playlist\?list\=
    NOP = 'youtube-dl {} {}'.format(nop, url)
    YEP = 'youtube-dl {} {}'.format(yep, url)
    return NOP, YEP

def _unique_url(wf, msg):
    _unique = False
    if os.path.exists(wf):
        with open(wf, 'r') as log_list:
            if msg not in log_list.readlines():
                _unique = True
    return _unique

def parse_args(opt, option, command, url):
    """
    LINUX COMMAND LINE CAN'T IGNORE [SPECIAL CHARACTERS]
    https://unix.stackexchange.com/questions/296141/how-to-use-a-special-character-as-a-normal-one

    INPUT LINK: https:// ... /watch?v=wUDkg8wyROU&list=PLlhaET2L7ba0Vp3otZf6ipXPDhFceWWCz
    SCRIPT GOT: https:// ... /watch?v=wUDkg8wyROU

    """
    lfile = "../urls.log"   # DIRECTORY WAS CHANGED IN LINE: 266
    logging.basicConfig(
        filename=lfile, level=logging.INFO, format="%(message)s"
    )
    HLINK = 'https://www.youtube.com/playlist?'
    PLIST = 'playlist?list='
    LLIST = PLIST.split('?')[1]
    HTTPS = HLINK.split(':')[0]
    global GO_NEXT
    NOP, YEP = program_option(command, url)
    single, with_video, playlist = option
    if opt == single or opt == with_video:
        if ARGS_ON:
            if _unique_url(lfile, NOP):
                logging.info(NOP)
            os.system(NOP)
            GO_NEXT = False
    elif opt == playlist:
        if ARGS_ON:
            if PLIST in YEP:
                if _unique_url(lfile, YEP):
                    logging.info(YEP)
                os.system(YEP)
                GO_NEXT = False
            elif LLIST in YEP:
                get_option = YEP.split(HTTPS)
                LIST = None
                for list in get_option[1].split('&'):
                    if list.startswith(LLIST):
                        LIST = list
                YEP = "{}{}{}".format(get_option[0], HLINK, LIST)
                if _unique_url(lfile, YEP):
                    logging.info(YEP)
                os.system(YEP)
                GO_NEXT = False

def main():
    global ARGS_ON
    global GO_NEXT
    global EXISTS_OPTIONS
    DOWNLOADED_FILES = 'DOWNLOADED_FILES'
    OPTIONS = [
        ['-mp3', '--audio', '--playlist-mp3'], ['-mp4', '--video-mp4', '--playlist-mp4'],
        ['-flv', '--video-flv', '--playlist-flv'], ['-ogg', '--video-ogg', '--playlist-ogg'],
        ['-webm', '--video-webm', '--playlist-webm'], ['-mkv', '--video-mkv', '--playlist-mkv'],
        ['-avi', '--video-avi', '--playlist-avi']
    ]
    YOUTUBE_DL = [
        '-x --no-playlist --audio-format mp3', '--no-playlist --recode-video mp4',
        '--no-playlist --recode-video flv', '--no-playlist --recode-video ogg',
        '--no-playlist --recode-video webm', '--no-playlist --recode-video mkv',
        '--no-playlist --recode-video avi'
    ]
    SINGLE_DL = ['-x ' + option for option in YOUTUBE_DL[1:-1]]
    SINGLE_OPTIONS = [['NOP', 'YEP', option] for _, _, option in OPTIONS[1:-1]]
    try:
        if len(sys.argv) == 2:
            opt = sys.argv[1]
            if opt == '-h' or opt == '--help':
                help()
        elif len(sys.argv) <= 3 and len(sys.argv) >= 2:
            opt = sys.argv[1]
            url = sys.argv[2]
            ARGS_ON = True
            check_exist_option(opt, OPTIONS)
            if EXISTS_OPTIONS:
                ########## CHANGE DIRECTORY ##########
                if not os.path.exists(DOWNLOADED_FILES):
                    os.mkdir(DOWNLOADED_FILES)
                os.chdir(DOWNLOADED_FILES)
                ########## MUSIC, VIDEOS #############
                for idx, itm in enumerate(YOUTUBE_DL):
                    if GO_NEXT:
                        parse_args(opt, OPTIONS[idx], itm, url)
                    else: break
                ########## PLAYLISTS #################
                for idx, itm in enumerate(SINGLE_DL):
                    if GO_NEXT:
                        parse_args(opt, SINGLE_OPTIONS[idx], itm, url)
                    else: break
            else:
                print('Opção invalida, para ver o menu de ajuda use: \n')
                print('$ python2 download.py -h ou | python download.py --help')
        else:
            print('Você deve digitar alguma opção!\n')
            print(MODO_DE_USO)
            print('$ python2 download.py -h, --help')
            quit()
    except KeyboardInterrupt:
        print('[!] 404 - Error Not Found;....[./]')

if __name__ == '__main__':
    main()


import os
import pprint
import string
###
# fonction createDir : prends le nom du repertoire
# crée le repertoire dans le bureau
###
def createDir(path,dirName):
        try:
                fullPath = os.path.join(path,dirName);
                os.mkdir(fullPath);
		#pprint.pprint(fullPath);
                finalPath = createKey(fullPath);
                print("Dossier ",dirName," crée avec succès !");
                return finalPath

        except OSError:
                pass

def choosePath():
        print("1- Bureau\n");
        print("2- Dropbox\n");
        print("3- Documents\n");

        id = input()
        return id

def registerPath():
        id = choosePath();
        if(id=="1"):
                print("Bureau");
                path = "C:\\Users\\"+userName+"\\Desktop\\";

        elif(id=="2"):
                print("Dropbox");
                path = "C:\\Users\\",userName,"\\Dropbox\\";

        elif(id=="3"):
                print("Documents");
                path = "C:\\Users\\",userName,"\Documents\\";
        else:
                print("Path erroné");
                path = null;

        return  path

def createFile(fullPath,fileName,ext):
        try:
                open(fullPath+'\\'+fileName+'.'+ext,'w');
        except:
                pass

def createKey(fullPath):
        try:
                createFile(fullPath,'\\'+userName+'_encryptData','txt');

                #open(fullPath+'\\'+userName+'_encryptData.txt','w');
        except:
                pass
        return fullPath+'\\'+userName+'_encryptData.txt'

def getUser():
        global userName
        userName = os.getlogin();
        print("User courant: ",userName);
        return userName;

def readFile(fullPath):
        file =open(fullPath,'r')
        string = file.read()
        file.close()
        return string

def editFile(fullPath,string):
        file=open(fullPath,'w')
        file.write(string)
        file.close()
        #print("Succès!")

def listToString(data):
        string =""
        for i in range(0,len(data)):
                string= string+str(data[i])+"./"
        return string

def stringToIntList(string):
        data = []
        data = string.split('./')
        data.pop()
        for i in range(0,len(data)):
                data[i]=int(data[i])

        return data


import numpy as np
import imutils
import pickle
import time
import cv2
import os

# float var to set minimum probability to filter weak face detections
CONFIDENCE = 0.5
# float var to set minimum threshold to filter our weak probabilities
THRESHOLD = 0.65

# face detector and pre-trained model
FACE_DETECTOR_DIR = os.path.sep.join(["faceDetectionModel", "deploy.prototxt"])
MODEL_DIR = os.path.sep.join(["faceDetectionModel", "res10_300x300_ssd_iter_140000.caffemodel"])

detector = cv2.dnn.readNetFromCaffe(FACE_DETECTOR_DIR, MODEL_DIR)

# face embedding model
embedder = cv2.dnn.readNetFromTorch("openface_nn4.small2.v1.t7")

# face recognition model
recognizer = pickle.loads(open("output/recognizer.pickle", "rb").read())

# label encoder
le = pickle.loads(open("output/le.pickle", "rb").read())

def recognizeFace(frame):
    # resize the frame
    frame = imutils.resize(frame, width=600)
    # maintain the aspect ratio and get image dimensions
    (h, w) = frame.shape[:2]

    # construct a blob from the image using mean substraction
    # blob = cv2.dnn.blobFromImage(image, scalefactor=1.0, size, mean, swapRB=True)
    imageBlob = cv2.dnn.blobFromImage(
        cv2.resize(frame, (300, 300)), 1.0, (300, 300),
        (104.0, 177.0, 123.0), swapRB=False, crop=False)

    # use OpenCV face detector to find faces in the image
    detector.setInput(imageBlob)
    detections = detector.forward()

    # loop over the detections
    for i in range(0, detections.shape[2]):
        confidence = detections[0, 0, i, 2]

        # filter out weak detections
        if confidence > CONFIDENCE:
            # compute x and y coordinates of the detected face
            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            # extract the face ROI
            face = frame[startY:endY, startX:endX]
            (fH, fW) = face.shape[:2]

            # checks if spatial dimensions are the right size
            if fW < 20 or fH < 20:
                continue

            # create a blob for face ROI, then pass it through
            # the face embedding model to obtain the 128-d
            # embeddings of the face
            faceBlob = cv2.dnn.blobFromImage(face, 1.0 / 255,
				(96, 96), (0, 0, 0), swapRB=True, crop=False)

            embedder.setInput(faceBlob)

            # vector with the embedded face
            vec = embedder.forward()

            # pass vector to the recognizer model, the result will tell
            # who is in the face ROI
            preds = recognizer.predict_proba(vec)[0]
            # take highest probability index  from the predictions
            j = np.argmax(preds)
            # extract the probability
            proba = preds[j]
            # use the label encoder to find the name from the dataset
            name = le.classes_[j]

            # filter out weak recognitions using a threshold
            if proba < THRESHOLD:
                continue

            # draw the bounding box of the face along with the
			# associated probability
            text = "{}: {:.2f}%".format(name, proba * 100)
            y = startY - 10 if startY - 10 > 10 else startY + 10
            cv2.rectangle(frame, (startX, startY), (endX, endY),
                (0, 0, 255), 2)
            cv2.putText(frame, text, (startX, y),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)

    return frame


import pytest
from pymilvus import DataType

import utils.utils as ut
from common.common_type import CaseLabel

default_entities = ut.gen_entities(ut.default_nb, is_normal=True)
raw_vectors, default_binary_entities = ut.gen_binary_entities(ut.default_nb)
default_int_field_name = "int64"
default_float_field_name = "float"
default_pos = 5
default_term_expr = f'{default_int_field_name} in {[i for i in range(default_pos)]}'

def init_data(connect, collection, nb=ut.default_nb, partition_names=None, auto_id=True):
    """
    Generate entities and add it in collection
    """
    if nb == 3000:
        insert_entities = default_entities
    else:
        insert_entities = ut.gen_entities(nb, is_normal=True)
    if partition_names is None:
        if auto_id:
            res = connect.insert(collection, insert_entities)
        else:
            res = connect.insert(collection, insert_entities, ids=[i for i in range(nb)])
    else:
        if auto_id:
            res = connect.insert(collection, insert_entities, partition_name=partition_names)
        else:
            res = connect.insert(collection, insert_entities, ids=[i for i in range(nb)],
                                 partition_name=partition_names)
    connect.flush([collection])
    ids = res.primary_keys
    return insert_entities, ids

def init_binary_data(connect, collection, nb=3000, insert=True, partition_names=None):
    """
    Generate entities and add it in collection
    """
    ids = []
    # global binary_entities
    global raw_vectors
    if nb == 3000:
        insert_entities = default_binary_entities
        insert_raw_vectors = raw_vectors
    else:
        insert_raw_vectors, insert_entities = ut.gen_binary_entities(nb)
    if insert is True:
        if partition_names is None:
            res = connect.insert(collection, insert_entities)
        else:
            res = connect.insert(collection, insert_entities, partition_name=partition_names)
        connect.flush([collection])
        ids = res.primary_keys
    return insert_raw_vectors, insert_entities, ids

class TestQueryPartition:
    """
    test Query interface
    query(collection_name, expr, output_fields=None, partition_names=None, timeout=None)
    """

    @pytest.mark.tags(CaseLabel.L0)
    def test_query_partition(self, connect, collection):
        """
        target: test query on partition
        method: create a partition and query
        expected: verify query result
        """
        connect.create_partition(collection, ut.default_tag)
        entities, ids = init_data(connect, collection, partition_names=ut.default_tag)
        assert len(ids) == ut.default_nb
        connect.load_partitions(collection, [ut.default_tag])
        res = connect.query(collection, default_term_expr, partition_names=[ut.default_tag], output_fields=["*", "%"])
        for _id, index in enumerate(ids[:default_pos]):
            if res[index][default_int_field_name] == entities[0]["values"][index]:
                assert res[index][default_float_field_name] == entities[1]["values"][index]
                ut.assert_equal_vector(res[index][ut.default_float_vec_field_name], entities[2]["values"][index])

def insert_entities_into_two_partitions_in_half(connect, collection):
    """
    insert default entities into two partitions(default_tag and _default) in half(int64 and float fields values)
    :param connect: milvus connect
    :param collection: milvus created collection
    :return: entities of default_tag and entities_2 of _default
    """
    connect.create_partition(collection, ut.default_tag)
    half = ut.default_nb // 2
    entities, _ = init_data(connect, collection, nb=half, partition_names=ut.default_tag)
    vectors = ut.gen_vectors(half, ut.default_dim)
    entities_2 = [
        {"name": "int64", "type": DataType.INT64, "values": [i for i in range(half, ut.default_nb)]},
        {"name": "float", "type": DataType.FLOAT, "values": [float(i) for i in range(half, ut.default_nb)]},
        {"name": ut.default_float_vec_field_name, "type": DataType.FLOAT_VECTOR, "values": vectors}
    ]
    connect.insert(collection, entities_2)
    connect.flush([collection])
    connect.load_collection(collection)
    return entities, entities_2


import pandas
import os

filename_all_table_data = "table_data_all_tables_internal.csv"
filename_baseline_file = "V1_baseline_datalake.tsv"  # EDIT
schema_to_search = "datalake"  # EDIT

def generate_baseline():
    print(f"\n>> Reading Data from {filename_all_table_data}")
    df = pandas.read_csv(filename_all_table_data)

    schema_name = df["schema_name"].tolist()
    table_name = df["table_name"].tolist()
    owner = df["owner"].tolist()
    # Keeping here in case we need to only put one of tables or views in file
    # table_type = df["table_type"].tolist()

    lines = []
    this_schema_tables = []
    this_schema_owners = []

    j = 0
    for i in range(len(table_name)):
        if schema_name[i] == schema_to_search and "_all" not in table_name[i]:
            this_schema_tables.append(table_name[i])
            this_schema_owners.append(owner[i])
            j += 1
    print(f"\n>> Number of tables in {schema_to_search}: {j}")

    current_table_name = ""
    with open(filename_baseline_file) as f:
        while True:
            c = f.read(1)
            if not c:
                print(f">> Finished reading {filename_baseline_file}.")
                break

            for line in f:
                if ";" not in line:
                    if "CREATE TABLE" in line:
                        lines.append(f"\n{line.rstrip()}\n")
                        current_table_name = line.replace(f"CREATE TABLE IF NOT EXISTS {schema_to_search}.", "")
                    else:
                        lines.append(f"{line.rstrip()}\n")
                else:
                    if "DROP TABLE" in line:
                        pass
                    elif "ALTER TABLE" in line:
                        lines.append(f"{line.rstrip()}\n")
                    else:
                        for table in this_schema_tables:
                            if table.strip() == current_table_name.strip():
                                index = this_schema_tables.index(table)
                                lines.append(f";\nALTER TABLE {schema_to_search.strip()}.{this_schema_tables[index].strip()} OWNER TO {this_schema_owners[index].strip()};\n")
                                break

    new_filename = f"V1_baseline_{schema_to_search}.sql"
    new_file_path = f"generated-files/{new_filename}"
    # create generated-files/ subdirectory
    os.makedirs(os.path.dirname(new_file_path), exist_ok=True)

    print(f"\n>> Writing to {new_filename}.\n>> Please review this file. You'll find it in generated-files/")

    with open(new_file_path, "w") as f:
        f.writelines(lines)
    print(f"\n>> Successfully created the new baseline script, saved as {new_filename}")

if __name__ == "__main__":
    generate_baseline()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 29 09:31:48 2018

@author: eduardo-ssr
"""

import sys
import serial
import glob
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from drawnow import drawnow
from time import sleep
from datetime import datetime

read1 = []
read2 = []
read3 = []
read4 = []
read5 = []
read6 = []
read7 = []

acelX = []
acelY = []
acelZ = []
gyroX = []
gyroY = []
gyroZ = []

constant_Calib_Acel = (16384/9.81)
constant_Calib_Gyro = 131

os.system('clear')
print ("======= List of USB devices =======")
serial_ports = glob.glob('/dev/ttyUSB*')
while(len(serial_ports)==0):
    print ("Connect the Arduino...\n")
    sleep(5);
    serial_ports = glob.glob('/dev/ttyUSB*')

for i in range(len(serial_ports)):
    print (i, " - ", serial_ports[i])
    port = input("Choose the arduino port (e.g. 0): ")

ser = serial.Serial(serial_ports[int(port)], 115200)

def main():
    global contador
    #ser.open()
    if ser.is_open:
        print("Established serial communication\n")
    else :
        print("Serial communication error\n")

   # ax.clear()
    input("Pressione 'Enter' para iniciar a leitura e \"Ctrl+C\" para pausar: \n")

    while(True):
        try:
            line = ser.readline().decode("utf-8")
            sleep(0.0001)
            print(line)
            try:
                entry = line.split("\t")
                AcX = np.float(entry[0])
                AcY = np.float(entry[1])
                AcZ = np.float(entry[2])
                temp = np.float(entry[3])
                Gx = np.float(entry[4])
                Gy = np.float(entry[5])
                Gz = np.float(entry[6])

                #print(AcX, AcY, AcZ, temp, Gx, Gy, Gz)

                ACX = AcX/constant_Calib_Acel -9.81 # entre--20 m/s² e + 20 m/s²
                ACY = AcY/constant_Calib_Acel -9.81 # entre--20 m/s² e + 20 m/s²
                ACZ = AcZ/constant_Calib_Acel -9.81 # entre--20 m/s² e + 20 m/s²

                GX = Gx/constant_Calib_Gyro # entre +250º/s e -250º/s
                GY = Gy/constant_Calib_Gyro # entre +250º/s e -250º/s
                GZ = Gz/constant_Calib_Gyro # entre +250º/s e -250º/s

                read1.append(AcX)
                read2.append(AcY)
                read3.append(AcZ)
                read4.append(Gx)
                read5.append(Gy)
                read6.append(Gz)
                read7.append(temp)

                acelX.append(ACX)
                acelY.append(ACY)
                acelZ.append(ACZ)
                gyroX.append(GX)
                gyroY.append(GY)
                gyroZ.append(GZ)

               # print(ACX,ACY,ACZ,GX,GY,GZ)

            except (ValueError):
                print("Erro de valor.")
                pass

        except (KeyboardInterrupt):
            now = datetime.now()
            print ("Voce pressionou Ctrl+C para interromper este programa! Seus dados foram salvos em 'Dados_%s.csv'"%(str(now)[:-7]))
            ser.close()
            #plt.plot(acelX, '-r')
            plt.plot(gyroX)
            plt.show()
           # x = np.vstack((read1,read2,read3,read4,read5,read6,read7))
           # np.savetxt('Dados_%s.csv'%(str(now)[:-7]), np.transpose(x), delimiter=';')
            break
if __name__ == "__main__":
    main()


import sys

D = sys.stdin.readline().split(' ')
Deg = int(D[0])
Dis = int(D[1])

Dir = 'N'
if 112.5 <= Deg < 337.5:
	Dir = 'NNE'
elif Deg < 562.5:
	Dir = 'NE'
elif Deg < 787.5:
	Dir = 'ENE'
elif Deg < 1012.5:
	Dir = 'E'
elif Deg < 1237.5:
	Dir = 'ESE'
elif Deg < 1462.5:
	Dir = 'SE'
elif Deg < 1687.5:
	Dir = 'SSE'
elif Deg < 1912.5:
	Dir = 'S'
elif Deg < 2137.5:
	Dir = 'SSW'
elif Deg < 2362.5:
	Dir = 'SW'
elif Deg < 2587.5:
	Dir = 'WSW'
elif Deg < 2812.5:
	Dir = 'W'
elif Deg < 3037.5:
	Dir = 'WNW'
elif Deg < 3262.5:
	Dir = 'NW'
elif Deg < 3487.5:
	Dir = 'NNW'

Dis = round(Dis / 60 + 0.1, 1)
if Dis <= 0.2:
	W = 0
	Dir = 'C'
elif Dis <= 1.5:
	W = 1
elif Dis <= 3.3:
	W = 2
elif Dis <= 5.4:
	W = 3
elif Dis <= 7.9:
	W = 4
elif Dis <= 10.7:
	W = 5
elif Dis <= 13.8:
	W = 6
elif Dis <= 17.1:
	W = 7
elif Dis <= 20.7:
	W = 8
elif Dis <= 24.4:
	W = 9
elif Dis <= 28.4:
	W = 10
elif Dis <= 32.6:
	W = 11
elif 32.7 <= Dis:
	W = 12

print('%s %d') % (Dir, W)


import pytest  # flake8: noqa

from os.path import dirname
from pathlib import Path

from seminario.config import config

tests_path = Path(dirname(__file__))

default_seminar_name = 'Seminar'
default_path = {
    'database': 'data/database.csv',
    'abstract': 'data/abstract/',
    'css': 'data/poster/css/poster.css',
}
default_tba = {
    'date': 'TBA',
    'begin_time': '',
    'end_time': '',
    'place': 'TBA',
    'speaker': 'TBA',
    'affiliation': '',
    'title': 'TBA',
    'abstract': 'TBA',
}

new_seminar_name = 'New Seminar'
new_path = {
    'database': 'new.csv',
    'abstract': 'new/',
    'css': 'new.css',
}
new_tba = {
    'date': 'New TBA date',
    'begin_time': 'New TBA begin_time',
    'end_time': 'New TBA end_time',
    'place': 'New TBA place',
    'speaker': 'New TBA speaker',
    'affiliation': 'New TBA affiliation',
    'title': 'New TBA title',
    'abstract': 'New TBA abstract',
}

params_default = [
    ('path', default_path),
    ('seminar_name', default_seminar_name),
    ('tba', default_tba),
]

params_new = [
    ('path', new_path),
    ('seminar_name', new_seminar_name),
    ('tba', new_tba),
]

# --------------------------------------------------------------------------------

@pytest.fixture(scope='module', autouse=True)
def reset_setup():
    yield
    config.setup(tests_path / 'data/config/default.yml')

@pytest.mark.parametrize('key, value', params_default)
def test_default(key, value):
    assert getattr(config, key) == value

@pytest.mark.parametrize('key, value', params_new)
def test_setup(key, value):
    config.setup(tests_path / 'cases/config/01.yml')
    assert getattr(config, key) == value


import appex
import clipboard
import console
import requests
import json

class dd:
    def req(self):
        #把第二步中获取到的 timestamp和sign拼接到URL中
        url = ('https://oapi.dingtalk.com/robot/send?access_token=9d35a417fd13301e046c31eb6deb29c47b769531a1e9d5e73b8a37d56dd1f2c1&timestamp=1612263003859&sign=B5Q86Vohcwn5rWKcItthGWGkY4kWudr1CyW0vd7kakk%3D')
        h = {
            'content-type':
            'application/json',
            'User-Agent':
            'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
        }
        #d里面的at参数是需要at的人参数，只有at的人存在这个参数里面才会@成功
        d = json.dumps({
            "msgtype": "text",
            "text": {
                "content": text
            },
            # "at": {
            #     "atMobiles": ["15207163636"],
            #     "isAtAll": "false"
            # }
        })
        req = requests.post(url, data=d, headers=h)
        data = req.json()
        if data.error_code == 0 and data.errmsg == 'ok':
            print('发送成功,请到客户端查看相关信息')
        print(req.text)

# def main():
#     text = appex.get_text()
#     if curl:
#         url, body, headers, method = parse_curl(curl)
#     else:
#         path = appex.get_file_path()
#         url, body, headers, method = parse(path)
# if __name__ == '__main__':
#     dd().req()

text = appex.get_text()
console.hud_alert('已发送,请查收')

if __name__ == '__main__':
    if appex.is_running_extension():
        dd().req()
    else:
        print('请设置为 Share Extension 脚本后使用。')


from django.shortcuts import HttpResponseRedirect
from django.conf import settings

class AuthRequiredMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        if not request.user.is_authenticated():
            path = request.path_info.lstrip('/')
            if path not in ["account/login/", "admin/"]:
                return HttpResponseRedirect(settings.LOGIN_URL)
        else:
            path = request.path_info.lstrip('/')
            if path in "account/login/":
                return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL)
        # Code to be executed for each request/response after
        # the view is called.

        return response


import mxnet as mx
import time
import os
import logging
import numpy as np
import json
import datetime
import glob
from east_symbol import east_symbol
from data_iter.dataset import TrainDataListDataset as dataset
from data_iter.dataloader import DataLoader as dataloader
from icdar_mx import save_train_data

def main():
    batch_per_gpu = 10
    num_gpus = 1
    num_workers = 5
    batch_size = int(batch_per_gpu * num_gpus)
    im_size = 512
    save_model_steps = 2
    update_data_steps = 1
    optimizer = 'adadelta'
    optimizer_params = {'rho': 0.99, 'wd': 0.00001}
    load_epoch = 0
    begin_epoch, num_epoch = load_epoch+1, 300
    train_eval_ratio = 10
    train_data_path = "/home/wangpan/Dataset/OCR/icdar2015/all_train_data/"
    model_prefix = "/home/wangpan/Workspace/OCR/EAST/model/text_det"
    result_path = "/home/wangpan/Workspace/OCR/EAST/output/"

    logger=set_logging(result_path)

    train_data, eval_data = train_eval_dataloader(train_data_path, batch_size, im_size, num_workers, train_eval_ratio)

    _, arg_params, aux_params = mx.model.load_checkpoint(model_prefix, load_epoch)
    train_net = east_symbol()
    sym = train_net.get_symbol(is_training=True)
    mod = mx.mod.Module(symbol=sym, context=[mx.gpu()], logger=logger,
                        data_names=('data',), label_names=('gt_cls','gt_geo','training_mask'))

    mod.bind(data_shapes=[('data',(batch_size, 3, im_size, im_size))],
             label_shapes=[('gt_cls',(batch_size, 1, im_size/4, im_size/4)),
                           ('gt_geo', (batch_size, 5, im_size/4, im_size/4)),
                           ('training_mask', (batch_size, 1, im_size/4, im_size/4))],
             for_training=True, force_rebind=False)
    mod.init_params(arg_params=arg_params, aux_params=aux_params,
                     allow_missing=True, force_init=False)
    mod.init_optimizer(kvstore='device', optimizer=optimizer,
                       optimizer_params=optimizer_params)

    for epoch in range(begin_epoch, begin_epoch+num_epoch):
        tic = time.time()
        nbatch = 0
        train_data_iter = iter(train_data)
        end_of_batch = False
        next_data_batch = next(train_data_iter)
        losses=[]
        while not end_of_batch:
            data_batch = next_data_batch
            mod.forward_backward(data_batch)
            mod.update()
            try:
                next_data_batch = next(train_data_iter)
                mod.prepare(next_data_batch)
            except StopIteration:
                end_of_batch = True
            get_loss= [loss.asnumpy()[0]*batch_size for loss in mod.get_outputs()]
            losses.append(get_loss)
            nbatch+=1
            print('Batch[{}] cls loss={:.4f} loc loss={:.4f}'.format(nbatch, get_loss[0], get_loss[1]))
        toc = time.time()
        mean_loss = np.array(losses).mean(0)
        info = 'Epoch[{}] Time cost={:.3f} Cls loss={:.4f} Loc loss={:.4f}'.format(epoch, (toc - tic), mean_loss[0], mean_loss[1])
        logger.info(info)

        eval_data_iter=iter(eval_data)
        next_data_batch = next(eval_data_iter)
        end_of_batch = False
        losses = []
        while not end_of_batch:
            data_batch = next_data_batch
            mod.forward(data_batch)
            try:
                next_data_batch = next(train_data_iter)
                mod.prepare(next_data_batch)
            except StopIteration:
                end_of_batch = True
            get_loss = [loss.asnumpy()[0] * batch_size for loss in mod.get_outputs()]
            losses.append(get_loss)
        mean_loss = np.array(losses).mean(0)
        info = 'Epoch[{}] evalidation Cls loss={:.4f} Loc loss={:.4f}'.format(epoch,mean_loss[0], mean_loss[1])
        logger.info(info)

        # sync aux params across devices
        arg_params, aux_params = mod.get_params()
        mod.set_params(arg_params, aux_params)

        if epoch%save_model_steps==0:
            mod.save_checkpoint(model_prefix, epoch)
        if (epoch+1-begin_epoch) % update_data_steps == 0:
            tic = time.time()
            save_train_data(input_data_path='/home/wangpan/Dataset/OCR/icdar2015/train/',
                            input_text_path='/home/wangpan/Dataset/OCR/icdar2015/traingt/',
                            ouput_data_path='/home/wangpan/Dataset/OCR/icdar2015/all_train_data/')
            train_data, eval_data = train_eval_dataloader(train_data_path, batch_size, im_size, num_workers, train_eval_ratio)
            print("gen data cost time={:.2f}s".format(time.time() - tic))
        train_data.reset()

def train_eval_dataloader(train_data_path, batch_size, im_size, num_workers, train_eval_ratio):
    samples_list = glob.glob(os.path.join(train_data_path, '*.npy'))
    ids = range(len(samples_list))
    np.random.shuffle(ids)
    train_list = [samples_list[i] for i in ids[len(ids) / train_eval_ratio:]]
    eval_list = [samples_list[i] for i in ids[:len(ids) / train_eval_ratio]]
    train_dataset = dataset(train_data_list=train_list)
    train_data = dataloader(train_dataset,
                            batch_size=batch_size,
                            num_workers=num_workers,
                            provide_data=[('data', (batch_size, 3, im_size, im_size))],
                            provide_label=[('gt_cls', (batch_size, 1, im_size / 4, im_size / 4)),
                                           ('gt_geo', (batch_size, 5, im_size / 4, im_size / 4)),
                                           ('training_mask', (batch_size, 1, im_size / 4, im_size / 4))])
    eval_dataset = dataset(train_data_list=eval_list)
    eval_data = dataloader(eval_dataset,
                           batch_size=batch_size,
                           num_workers=num_workers,
                           provide_data=[('data', (batch_size, 3, im_size, im_size))],
                           provide_label=[('gt_cls', (batch_size, 1, im_size / 4, im_size / 4)),
                                          ('gt_geo', (batch_size, 5, im_size / 4, im_size / 4)),
                                          ('training_mask', (batch_size, 1, im_size / 4, im_size / 4))])
    return train_data, eval_data

def set_logging(output_path):
    now = datetime.datetime.now()
    nowtime = now.strftime("%m-%d-%H:%M:%S")
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
                        datefmt='%a, %d %b %Y %H:%M:%S',
                        filename=os.path.join(output_path,nowtime+'.log'),
                        filemode='w')
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(message)s')
    console.setFormatter(formatter)
    logging.getLogger('').addHandler(console)
    return logging

if __name__ == '__main__':
    main()


import optuna
import subprocess

def objective(trial):

    TEMP_RADIX = trial.suggest_uniform('temp radix', 50, 3000)
    PROBABILITY_COEF = trial.suggest_uniform('probability coefficient', 0.000001, 1)

    total_dist = float(subprocess.check_output(['./route_builder', str(TEMP_RADIX), str(PROBABILITY_COEF)]))

    print('temp radix: %1.3f, probability coefficient: %1.3f, total_dist: %1.3f' % (TEMP_RADIX, PROBABILITY_COEF, total_dist))

    return total_dist

study = optuna.create_study()
study.optimize(objective, n_trials=10000)

print()
print('best parameters: ', study.best_params)
print('minimum total dist: ', study.best_value)
print()
print(study.best_trial)


# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import matplotlib.pyplot as plt
lista = [11, 18, 3, 1, 16, 12, 6, 19, 5, 0, 14, 4, 17, 9, 13, 7, 10, 15, 2, 8] #Valores da Lista
plt.figure()
#Criamos uma figura vazia
plt.plot(range(0,20), lista, 'ok')
#Definimos x como 'range(0,20)' e y como a lista original, antes de ser modificada pelo algoritmo
plt.title("Lista Original")
#Título do Gráfico
plt.xlabel("Posição na lista")
#Nomeamos X
plt.ylabel("Valores da lista")
#Nomeamos Y
plt.savefig("bubble-inicio.png")
#Salvamos a figura
plt.close()
#Fechamos a figura
print("lista original", lista) #para imprimir a lista original sem modificações
a = 0
N = 20 #Numero de Elementos
for i in range(0, N-1, 1): #Andando do primeiro elemento até o penultimo de 1 em 1
    for j in range(i+1, N, 1): #Andando do elemento seguinte a 'i' até o ultimo de 1 em 1
        plt.figure()
        plt.plot(range(0,20), lista, 'ok')
        plt.plot(i, lista[i], 'or') #Marcar em vermelho a carta i
        plt.plot(j, lista[j], 'ob') #Marvar em azul a carta j
        plt.title("Lista Em Todas as Trocas")
        plt.xlabel("Posição na lista")
        plt.ylabel("Valores da lista")
        a = a + 1
        plt.savefig("bubble-it{}.png".format(a))
        plt.close()
        if lista[i] < lista[j]:
            continue
        else:
            temp = lista[i] #Para inverter os valores
            lista[i] = lista[j]
            lista[j] = temp
            plt.figure()
            plt.plot(range(0,20), lista, 'ok')
            plt.title("Lista Em Cada Troca")
            plt.xlabel("Posição na lista")
            plt.ylabel("Valores da lista")
            a = a + 1
            plt.savefig("bubble-troca{}.png".format(a))
            plt.close()
print("lista em ordem crescente", lista) #para imprimir a lista em ordem crescente com modificações
plt.figure()
plt.plot(range(0,20), lista, 'ok')
plt.title("Lista Em Ordem Crescente")
plt.xlabel("Posição na lista")
plt.ylabel("Valores da lista")
plt.savefig("bubble-fim.png")
plt.close()

print("cinco menores valores", lista[0:5]) #usamos esse comando para imprimir apenas os cinco menores valores da lista em ordem crescente, e o nomeamos como 'cinco menores valores'
print("cinco maiores valores", lista[15:20]) #usamos esse comando para imprimir apenas os cinco maiores valores da lista em ordem crescente, e o nomeamos como 'cinco maiores valores'

#Para selecionar o primeiro elemento da lista 'lista[0]'
#Para selecionar os cincos primeiros elementos da lista 'lista[0:4]'