import chess.pgn
import matplotlib.pyplot as plt

locs = [chess.A1, chess.A2, chess.A3, chess.A4, chess.A5, chess.A6, chess.A7, chess.A8,
     chess.B1, chess.B2, chess.B3, chess.B4, chess.B5, chess.B6, chess.B7, chess.B8,
     chess.C1, chess.C2, chess.C3, chess.C4, chess.C5, chess.C6, chess.C7, chess.C8,
     chess.D1, chess.D2, chess.D3, chess.D4, chess.D5, chess.D6, chess.D7, chess.D8,
     chess.E1, chess.E2, chess.E3, chess.E4, chess.E5, chess.E6, chess.E7, chess.E8,
     chess.F1, chess.F2, chess.F3, chess.F4, chess.F5, chess.F6, chess.F7, chess.F8,
     chess.G1, chess.G2, chess.G3, chess.G4, chess.G5, chess.G6, chess.G7, chess.G8,
     chess.H1, chess.H2, chess.H3, chess.H4, chess.H5, chess.H6, chess.H7, chess.H8]

loc_map = {chess.A1: (7, 0), chess.B1: (7, 1), chess.C1: (7, 2), chess.D1: (7, 3), chess.E1: (7, 4), chess.F1: (7, 5), chess.G1: (7, 6), chess.H1: (7, 7),
                chess.A2: (6, 0), chess.B2: (6, 1), chess.C2: (6, 2), chess.D2: (6, 3), chess.E2: (6, 4), chess.F2: (6, 5), chess.G2: (6, 6), chess.H2: (6, 7),
                chess.A3: (5, 0), chess.B3: (5, 1), chess.C3: (5, 2), chess.D3: (5, 3), chess.E3: (5, 4), chess.F3: (5, 5), chess.G3: (5, 6), chess.H3: (5, 7),
                chess.A4: (4, 0), chess.B4: (4, 1), chess.C4: (4, 2), chess.D4: (4, 3), chess.E4: (4, 4), chess.F4: (4, 5), chess.G4: (4, 6), chess.H4: (4, 7),
                chess.A5: (3, 0), chess.B5: (3, 1), chess.C5: (3, 2), chess.D5: (3, 3), chess.E5: (3, 4), chess.F5: (3, 5), chess.G5: (3, 6), chess.H5: (3, 7),
                chess.A6: (2, 0), chess.B6: (2, 1), chess.C6: (2, 2), chess.D6: (2, 3), chess.E6: (2, 4), chess.F6: (2, 5), chess.G6: (2, 6), chess.H6: (2, 7),
                chess.A7: (1, 0), chess.B7: (1, 1), chess.C7: (1, 2), chess.D7: (1, 3), chess.E7: (1, 4), chess.F7: (1, 5), chess.G7: (1, 6), chess.H7: (1, 7),
                chess.A8: (0, 0), chess.B8: (0, 1), chess.C8: (0, 2), chess.D8: (0, 3), chess.E8: (0, 4), chess.F8: (0, 5), chess.G8: (0, 6), chess.H8: (0, 7)
                }
loc_map_2 = {"a1": (7, 0), "b1": (7, 1), "c1": (7, 2), "d1": (7, 3), "e1": (7, 4), "f1": (7, 5), "g1": (7, 6), "h1": (7, 7),
                "a2": (6, 0), "b2": (6, 1), "c2": (6, 2), "d2": (6, 3), "e2": (6, 4), "f2": (6, 5), "g2": (6, 6), "h2": (6, 7),
                "a3": (5, 0), "b3": (5, 1), "c3": (5, 2), "d3": (5, 3), "e3": (5, 4), "f3": (5, 5), "g3": (5, 6), "h3": (5, 7),
                "a4": (4, 0), "b4": (4, 1), "c4": (4, 2), "d4": (4, 3), "e4": (4, 4), "f4": (4, 5), "g4": (4, 6), "h4": (4, 7),
                "a5": (3, 0), "b5": (3, 1), "c5": (3, 2), "d5": (3, 3), "e5": (3, 4), "f5": (3, 5), "g5": (3, 6), "h5": (3, 7),
                "a6": (2, 0), "b6": (2, 1), "c6": (2, 2), "d6": (2, 3), "e6": (2, 4), "f6": (2, 5), "g6": (2, 6), "h6": (2, 7),
                "a7": (1, 0), "b7": (1, 1), "c7": (1, 2), "d7": (1, 3), "e7": (1, 4), "f7": (1, 5), "g7": (1, 6), "h7": (1, 7),
                "a8": (0, 0), "b8": (0, 1), "c8": (0, 2), "d8": (0, 3), "e8": (0, 4), "f8": (0, 5), "g8": (0, 6), "h8": (0, 7)
                }

def increase_board(big_board, index):
    if index[0] >=0 and index[0] <= 7 and index[1] >= 0 and index[1] <= 7:
        big_board[index[0]][index[1]] += 1
    return big_board

def analyze_black_pawn(big_board, loc):
    index = loc_map[loc]
    big_board = increase_board(big_board, (index[0] + 1, index[1] - 1))
    big_board = increase_board(big_board, (index[0] + 1, index[1] + 1))
    return big_board

def analyze_white_pawn(big_board, loc):
    index = loc_map[loc]
    big_board = increase_board(big_board, (index[0] - 1, index[1] - 1))
    big_board = increase_board(big_board, (index[0] - 1, index[1] + 1))
    return big_board

def analyze_rook(big_board, loc):
    index = loc_map[loc]
    for i in range(8):
        big_board = increase_board(big_board, (index[0], i))
        big_board = increase_board(big_board, (i, index[1]))
    return big_board

def analyze_knight(big_board, loc):
    index = loc_map[loc]
    big_board = increase_board(big_board, (index[0] + 2, index[1] + 1))
    big_board = increase_board(big_board, (index[0] + 2, index[1] - 1))
    big_board = increase_board(big_board, (index[0] - 2, index[1] + 1))
    big_board = increase_board(big_board, (index[0] - 2, index[1] - 1))
    big_board = increase_board(big_board, (index[0] + 1, index[1] + 2))
    big_board = increase_board(big_board, (index[0] + 1, index[1] - 2))
    big_board = increase_board(big_board, (index[0] - 1, index[1] + 2))
    big_board = increase_board(big_board, (index[0] - 1, index[1] - 2))
    return big_board

def analyze_bishop(big_board, loc):
    index = loc_map[loc]
    for i in range(8):
        big_board = increase_board(big_board, (index[0] + i, index[1] + i))
        big_board = increase_board(big_board, (index[0] - i, index[1] + i))
        big_board = increase_board(big_board, (index[0] + i, index[1] - i))
        big_board = increase_board(big_board, (index[0] - i, index[1] - i))
    return big_board

def analyze_queen(big_board, loc):
    index = loc_map[loc]
    for i in range(8):
        big_board = increase_board(big_board, (index[0], i))
        big_board = increase_board(big_board, (i, index[1]))
        big_board = increase_board(big_board, (index[0] + i, index[1] + i))
        big_board = increase_board(big_board, (index[0] - i, index[1] + i))
        big_board = increase_board(big_board, (index[0] + i, index[1] - i))
        big_board = increase_board(big_board, (index[0] - i, index[1] - i))
    return big_board

def analyze_king(big_board, loc):
    index = loc_map[loc]
    big_board = increase_board(big_board, (index[0] + 1, index[1] + 1))
    big_board = increase_board(big_board, (index[0] + 1, index[1] - 1))
    big_board = increase_board(big_board, (index[0] - 1, index[1] + 1))
    big_board = increase_board(big_board, (index[0] - 1, index[1] - 1))
    big_board = increase_board(big_board, (index[0] + 1, index[1]))
    big_board = increase_board(big_board, (index[0] - 1, index[1]))
    big_board = increase_board(big_board, (index[0], index[1] + 1))
    big_board = increase_board(big_board, (index[0], index[1] - 1))
    return big_board

def analyze_board(big_board, board):

    # pieces = {'p', 'r', 'n', 'b', 'q', 'k', 'P', 'R', 'N', 'B', 'Q', 'K'}
    for loc in locs:
        piece = board.piece_at(loc)
        if piece is not None:
            p = piece.symbol()
            if p == 'p':
                big_board = analyze_black_pawn(big_board, loc)
            elif p == 'r' or p == 'R':
                big_board = analyze_rook(big_board, loc)
            elif p == 'n' or p == 'N':
                big_board = analyze_knight(big_board, loc)
            elif p == 'b' or p == 'B':
                big_board = analyze_bishop(big_board, loc)
            elif p == 'q' or p == 'Q':
                big_board = analyze_queen(big_board, loc)
            elif p == 'k' or p == 'K':
                big_board = analyze_king(big_board, loc)
            elif p == 'P':
                big_board = analyze_white_pawn(big_board, loc)
    return big_board

def update_move_board(move_board, row, col):
    if row >=0 and row <= 7 and col >= 0 and col <= 7:
        move_board[row][col] += 1
    return move_board

def analyze_move(move_board, mover):
    col_to_num = {"a": 0, "b": 1, "c": 2, "d": 3, "e": 4, "f": 5, "g": 6, "h": 7}
    #convert move to string
    move = str(mover)
    print(move)
    start_row, start_col = loc_map_2[move[0:2]]
    print(start_col, start_row)
    end_row, end_col = loc_map_2[move[2:4]]

    # start_col = int(col_to_num[move[0]])
    # start_row = int(move[1]) - 1
    # end_col = int(col_to_num[move[2]])
    # end_row = int(move[3]) - 1
    if start_col == end_col:
        # vertical move
        for i in range(min(start_row, end_row), max(start_row, end_row)+1):
            move_board = update_move_board(move_board, i, start_col)
    elif start_row == end_row:
        # horizontal move
        for i in range(min(start_col, end_col), max(start_col, end_col)+1):
            move_board = update_move_board(move_board, start_row, i)
    elif abs(start_col - end_col) == abs(start_row - end_row):
        # diagonal move
        for i in range(abs(start_col - end_col)+1):
            move_board = update_move_board(move_board, min(start_row, end_row) + i, min(start_col, end_col) + i)
    else:
        # knight move
        # default to do the 1 first and then the two
        move_board = update_move_board(move_board, start_row, start_col)
        if abs(start_row - end_row) == 1:
            # 1 row shift
            move_board = update_move_board(move_board, end_row, start_col)
            if end_col > start_col:
                move_board = update_move_board(move_board, end_row, start_col + 1)
                move_board = update_move_board(move_board, end_row, start_col + 2)
            else:
                move_board = update_move_board(move_board, end_row, start_col - 1)
                move_board = update_move_board(move_board, end_row, start_col - 2)
        else:
            # 1 col shift
            move_board = update_move_board(move_board, start_row, end_col)
            if end_row > start_row:
                move_board = update_move_board(move_board, start_row + 1, end_col)
                move_board = update_move_board(move_board, start_row + 2, end_col)
            else:
                move_board = update_move_board(move_board, start_row - 1, end_col)
                move_board = update_move_board(move_board, start_row - 2, end_col)
    return move_board

def simulate_game(pgn_file, big_board, move_board):
    with open(pgn_file) as f:
        game = chess.pgn.read_game(f)

    board = game.board()

    print("Simulating chess game...\n")

    for move in game.mainline_moves():
        board.push(move)
        print(f"Move: {move}")
        move_board = analyze_move(move_board, move)
        # print(f"Board:\n{board}\n")
        big_board = analyze_board(big_board, board)
        # print(big_board)
    # print(move_board)
    print("Game over.")
    print("Result: " + game.headers["Result"])

# Example usage:

big_board = [[0 for _ in range(8)] for _ in range(8)]
move_board = [[0 for _ in range(8)] for _ in range(8)]
pgn_file = "gukesh_giri_norway_chess_2023.pgn"
simulate_game(pgn_file, big_board, move_board)
for i in move_board:
    print(i)

# print move_board as a heat map
plt.imshow(move_board, cmap='hot', interpolation='nearest')
plt.show()


#From https://jjmojojjmojo.github.io/time-based-fading.html

import board
import neopixel
import time

import adafruit_fancyled.adafruit_fancyled as fancy

BRIGHTNESS = 0.4

rgb = neopixel.NeoPixel(board.A2, 100, brightness=BRIGHTNESS, auto_write=False)

def make_gradient(colors, count=24, cycle=True):
    values = []
    ratio = 1.0/len(colors)
    for index, color in enumerate(colors):
        value = float(index*ratio)
        values.append((value, color))

    if cycle:
        values.append((1.0, colors[0]))

    palette = []
    for expanded in fancy.expand_gradient(values, count):
        palette.append(fancy.gamma_adjust(expanded, brightness=BRIGHTNESS).pack())

    return tuple(palette)

WHITE = fancy.CRGB(255, 255, 255)
BLACK = fancy.CRGB(0, 0, 0)
RED = fancy.CRGB(255, 0, 0)
GREEN = fancy.CRGB(0, 255, 0)
YELLOW = fancy.CRGB(255, 255, 0)
MAGENTA = fancy.CRGB(255, 0, 255)
CYAN = fancy.CRGB(0, 255, 255)
BLUE = fancy.CRGB(0, 0, 255)
ORANGE = fancy.CRGB(255, 127, 0)
VIOLET = fancy.CRGB(139, 0, 255)
INDIGO = fancy.CRGB(46, 43, 95)
PINK = fancy.CRGB(255, 127, 127)
MINT = fancy.CRGB(127, 255, 127)
ROBIN = fancy.CRGB(127, 127, 255)
CANARY = fancy.CRGB(255, 255, 127)

gradient = make_gradient([
    RED, ORANGE, YELLOW, GREEN, BLUE, VIOLET
])

print("gradient = ", gradient)

index = 0

while True:
    rgb.fill(gradient[index])
    rgb.write()

    index += 1
    if index > len(gradient)-1:
        index = 0

    time.sleep(0.2)


from collections import defaultdict

file = 'data.txt'
N =[int(x) for x in open(file).read().strip().split(",")]

X = defaultdict(int)
for n in N:
    if n not in X:
        X[n] = 0
    X[n] += 1

for day in range(256):
    Y = defaultdict(int)
    for x,cnt in X.items():
        if x == 0:
            Y[6] += cnt
            Y[8] += cnt
        else:
            Y[x-1] += cnt
    X = Y
print(sum(X.values()))


from app.forms.auth import RegisterForm
from app.forms.auth import LoginForm

from app.models.user import User
from app.models.base import db

from flask import request, jsonify

from . import web

from app.lib.http import login_required, create_token, verify_token

@web.route('/api/user/logout', methods=['GET'])
def logout():
    try:
        token = request.headers['Authorization']
        user = verify_token(token)
        if user:
            with db.auto_commit():
                result = User.query.filter_by(id=user.id).first()
                result.launched = False
        return jsonify({
            'code': 200,
            'message': '退出成功'
        })
    except:
        return jsonify({
            'code': 200,
            'message': '退出失败'
        })

@web.route('/api/user/info/get', methods=['GET'])
def getuserinfo():
    token = request.headers['Authorization']
    user = verify_token(token)
    id = user.id
    name = user.name
    roles = user.roles.split(',')

    return jsonify({
        'code': 200,
        'message': '请求用户信息成功',
        'data': {
            'userList': {
                'roles': roles,
                'name': name,
                'id': id
            }
        }
    })

@web.route('/api/user/register', methods=['POST'])
def register():
    form = request.form
    form = RegisterForm(request.form)
    if request.method  == 'POST' and form.validate():
        with db.auto_commit():
            user = User()
            user.set_attrs(form.data)
            db.session.add(user)
        return jsonify({
            'code': 200,
            'message': '注册成功'
        })
    return jsonify({
            'code': 201,
            'message': '注册失败'
        })

@web.route('/api/user/login', methods=['POST'])
def login():

    form = request.form
    form = LoginForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User.query.filter_by(name=form.name.data).first()
        if user and user.check_password(form.password.data):
            with db.auto_commit():

                user.launched = True

            token = create_token(user.id)
            return jsonify({
                'code': 200,
                'message': '登录成功',
                'token': token,
                'username': user.name,
                'roles': user.roles.split(',')
            })
        return jsonify({
            'code': 201,
            'message': '用户名或密码有误,请在仔细检查一下重新输入'
        })
    else:
        return jsonify({
            'code': 201,
            'message': '登录失败'
        })


"""mbl URL Configuration"""
from django.urls import include, re_path
from django.contrib import admin

from rest_framework import routers

from browser import views
from browser import rest

router = routers.DefaultRouter()
router.register(r'coursegroups', rest.CourseGroupViewSet)
router.register(r'courses', rest.CourseViewSet)
router.register(r'people', rest.PersonViewSet)
router.register(r'institutions', rest.InstitutionViewSet)
router.register(r'locations', rest.LocationViewSet)

urlpatterns = [
    re_path('', include('social.apps.django_app.urls', namespace='social')),
    re_path(r'^logout/$', views.logout_view, name='logout'),
    re_path(r'^admin/', admin.site.urls),
    re_path(r'^$', views.home, name="home"),
    re_path(r'^bulk/(?P<model>[a-z]+)/$', views.bulk_action, name="bulk-action"),

    re_path(r'^course/(?P<course_id>[0-9]+)/$', views.course, name="course"),
    re_path(r'^course/(?P<course_id>[0-9]+)/delete/$', views.course_delete, name="delete-course"),
    re_path(r'^course/(?P<course_id>[0-9]+)/edit/$', views.edit_course, name="edit-course"),
    re_path(r'^course/(?P<course_id>[0-9]+)/add/$', views.attendee_create, name="add-attendee"),
    re_path(r'^course/$', views.course, name="courses"),
    re_path(r'^course/create/$', views.course_create, name="create-course-nogroup"),
    re_path(r'^person/(?P<person_id>[0-9]+)/$', views.person, name="person"),
    re_path(r'^person/(?P<person_id>[0-9]+)/edit/$', views.handle_person, name="edit-person"),
    re_path(r'^person/(?P<person_id>[0-9]+)/split/$', views.split_person, name="split-person"),
    re_path(r'^person/merge/$', views.merge_people, name="merge-people"),
    re_path(r'^person/$', views.person, name="person_list"),
    re_path(r'^person/add/$', views.handle_person, name="add-person"),
    re_path(r'^person/(?P<person_id>[0-9]+)/investigator/add/$',views.add_investigator_record,name='add-investigator'),
    re_path(r'^person/(?P<person_id>[0-9]+)/investigator/(?P<research_id>[0-9]+)/edit/$',views.edit_investigator_record,name='edit-investigator'),
    re_path(r'^person/(?P<person_id>[0-9]+)/investigator/(?P<research_id>[0-9]+)/delete/$', views.delete_investigator_record, name='delete-investigator'),
    re_path(r'^person/(?P<person_id>[0-9]+)/affiliation/(?P<affiliation_id>[0-9]+)/edit/$', views.edit_affiliation, name='edit-affiliation'),
    re_path(r'^person/(?P<person_id>[0-9]+)/affiliation/(?P<affiliation_id>[0-9]+)/delete/$', views.delete_affiliation_record, name='delete-affiliation'),
    re_path(r'^person/(?P<person_id>[0-9]+)/position(?:/(?P<position_id>[0-9]+))?/$', views.position, name='position'),
    re_path(r'^person/(?P<person_id>[0-9]+)/position/(?P<position_id>[0-9]+)/delete/$', views.delete_position, name='delete-position'),
    re_path(r'^institution/(?P<institution_id>[0-9]+)/$', views.institution, name="institution"),
    re_path(r'^institution/(?P<institution_id>[0-9]+)/edit/$', views.edit_institution, name="edit-institution"),
    re_path(r'^institution/$', views.institution, name="institution_list"),

    re_path(r'^location/(?P<location_id>[0-9]+)/$', views.location, name="location"),
    re_path(r'^location/(?P<location_id>[0-9]+)/edit/$', views.edit_location, name="edit-location"),
    re_path(r'^location/(?P<location_id>[0-9]+)/split/$', views.split_location, name="split-location"),
    re_path(r'^location/$', views.location, name="location_list"),

    re_path(r'^coursegroup/(?P<coursegroup_id>[0-9]+)/$', views.coursegroup, name="coursegroup"),
    re_path(r'^coursegroup/(?P<coursegroup_id>[0-9]+)/edit/$', views.edit_coursegroup, name="edit-coursegroup"),
    re_path(r'^coursegroup/(?P<coursegroup_id>[0-9]+).json$', views.coursegroup_data, name="coursegroup_data"),
    re_path(r'^coursegroup/(?P<coursegroup_id>[0-9]+)/create/$', views.course_create, name="create-course"),
    re_path(r'^coursegroup/$', views.coursegroup, name="coursegroup_list"),
    re_path(r'^about/$', views.about, name="about"),
    re_path(r'^search/$', views.generic_autocomplete, name="search"),

    re_path(r'^rest/', include(router.urls)),
    re_path(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]


import random
from typing import List, Optional
from argparse import ArgumentParser

class RandomChoiceIterator:

    def __init__(self, values: List[int], num_iters: Optional[int] = None, seed: Optional[int|float] = None):
        if not values:
            raise ValueError('List of values is empty! It must contain at least one value!')
        self.values = values
        self.num_iters = num_iters
        random.seed(seed)
        if self.num_iters is not None:
            self.current_iteration = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.num_iters is None:
            return random.choice(self.values)
        elif self.current_iteration >= self.num_iters:
            raise StopIteration()
        else:
            self.current_iteration += 1
            return random.choice(self.values)

if __name__ == '__main__':
    parser = ArgumentParser()
    parser.add_argument('-v', '--values', required=True, nargs='*', type=int)
    parser.add_argument('-n', '--num-iters', required=False, type=int, default=None)
    parser.add_argument('-s', '--seed', required=False, type=float, default=None)
    args = parser.parse_args()

    for value in RandomChoiceIterator(values=args.values, num_iters=args.num_iters, seed=args.seed):
        print(value)


import string
def percent(words):
    words_percents = []
    for i in words:
        percent = round(100*words.count(i)/len(words), 2)
        words_percents.append(percent)
    return words_percents
def text_analysis(text):
    with open(text, 'r', encoding='utf-8') as text:
        t = text.read()
    t = t.lower().translate(t.maketrans('—', ' ', string.punctuation)).split()
    set_t = set(t)
    longest_word = max(set_t, key=len)
    longest_words = set([i for i in t if len(i) == len(longest_word)])
    words_freq = percent(t)
    max_percent = max(words_freq)
    max_freq_words = set([i for i in t if words_freq[t.index(i)] == max_percent])
    lw = ''
    for i in longest_words:
        lw += i
    mfw = ''
    for i in max_freq_words:
        mfw += i
    return lw, mfw
with open('text3.txt', 'w+', encoding='utf-8') as text:
    lines = '''Варкалось. Хливкие шорьки Пырялись по наве, И хрюкотали зелюки, Как мюмзики в мове.
О, бойся Бармаглота, сын! Он так свирлеп и дик! А в глу́ше ры́мит исполин — Злопастный Брандашмыг!
Но взял он меч, и взял он щит, Высоких полон дум. В глущобу путь его лежит Под дерево Тумтум.
Он стал под дерево и ждёт. И вдруг граахнул гром — Летит ужасный Бармаглот И пылкает огнём!
Раз-два, раз-два! Горит трава, Взы-взы — стрижает меч, Ува! Ува! И голова Барабардает с плеч!
О светозарный мальчик мой! Ты победил в бою! О храброславленный герой, Хвалу тебе пою!
Варкалось. Хливкие шорьки Пырялись по наве. И хрюкотали зелюки, Как мюмзики в мове.'''

    text.write(lines)
with open('text3.txt', 'r', encoding='utf-8') as text:
    t = text.read()
print(t)
result = text_analysis('text3.txt')
print(f'Самое длинное слово: {result[0]}\nСамое частое слово: {result[-1]}')


total_compra = 0
maior_mil = 0
produto = 0
menor_preco = 0
n_produto_barato = ''
print('---' * 30)
print('LOJA loja '.center(45))
print('---' * 30)
while True:
    n_produto = str(input('Nome do produto'))
    preco = float(input('Preço: '))
    produto = produto + 1
    total_compra = total_compra + preco
    if preco > 1000:
        maior_mil = maior_mil + 1
    if produto == 1:
        menor_preco = preco
        n_produto_barato = n_produto
    else:
        if preco < menor_preco:
            menor_preco = preco
            n_produto_barato = n_produto
    continuar = ' '
    while continuar not in 'SN':
        continuar = str(input('Quer contiuar [S/N]: ')).strip().upper()[0]
    if continuar == 'N':
        break
print('O total da compra  foi RS:{:.2f}'.format(total_compra))
print('Temos {} custando mais de 1000 reais'.format(maior_mil))
print('O produto mais barato foi {} que custa RS{:.2f}'.format(n_produto_barato, menor_preco))


#If the bill was $150.00, split between 5 people, with 12% tip.
#Each person should pay (150.00 / 5) * 1.12 = 33.6
#Format the result to 2 decimal places = 33.60
#Tip: There are 2 ways to round a number. You might have to do some Googling to solve this.ðŸ’ª
#Write your code below this line ðŸ‘‡

print("Welcome to Tip Calculator")

total_bill=input("What was your total bill? $")
total_bill_int=int(total_bill)

tip_amount=input("How much tip would you like to give? 10? 12? 15?")
tip_amount_int=int(tip_amount)

no_of_people=input("How many people to split the bill?")
no_of_people_int=int(no_of_people)

total_bill_inc_tip=(total_bill_int+((tip_amount_int/100)*total_bill_int))
grand_total=int(total_bill_inc_tip)

final_split=round(grand_total/no_of_people_int,2)
print(f'Each should pay {final_split} including tip!')


# -*- coding: utf-8 -*-
"""
Created on Thu Nov  3 19:34:32 2022

@author: taylo
"""

'''
Disclaimer all code and all examples shown here are for the most part taken from argoverse-api
here is the link:
    https://github.com/argoai/argoverse-api

You'll also want to make sure you have data which you get from their webiste here:
    https://www.argoverse.org/av1.html#stereo-link
Keep scrolling down to the bottom!

Additionally you want to make sure you have all the below imports installed, additionally
you want the following packages installed (you likely have a good amount already
installed):
    logging, pathlib, typing, imageio, typing_extensions, pandas, multiprocessing, argparse,
    functools, dataclasses, glob, scipy
    '''

from pathlib import Path
import json

import os
from argoverse_light.stereo_dataloader import ArgoverseStereoDataLoader
from argoverse_light.camera_stats import RECTIFIED_STEREO_CAMERA_LIST
from argoverse_light.calibration import get_calibration_config
from argoverse_light.eval import StereoEvaluator

#import open3d as o3d <- this ruined everything for me, bad install....
import cv2
import numpy as np
import matplotlib.pyplot as plt
import plotly.io as pio
pio.renderers.default='browser'
import plotly.graph_objects as go
import open3d as o3d

STEREO_FRONT_LEFT_RECT = RECTIFIED_STEREO_CAMERA_LIST[0]
STEREO_FRONT_RIGHT_RECT = RECTIFIED_STEREO_CAMERA_LIST[1]
print(STEREO_FRONT_LEFT_RECT)

#NOTE: YOU WANT HTIS TO BE RELATIVE AT LEAST ON WINDOWS
data_dir = os.path.join('..','..', 'shared', 'data')
stereo_img_dir = os.path.join(data_dir, 'rectified_stereo_images_v1.1')
disparity_img_dir = os.path.join(data_dir, 'disparity_maps_v1.1')

print('Data is in: ', data_dir)

split_name = "train"
log_id = "273c1883-673a-36bf-b124-88311b1a80be"
idx = 34
stereo_data_loader = ArgoverseStereoDataLoader(data_dir, split_name)

# Loading the left rectified stereo image paths for the chosen log.
left_stereo_img_fpaths = stereo_data_loader.get_ordered_log_stereo_image_fpaths(
    log_id=log_id,
    camera_name=STEREO_FRONT_LEFT_RECT,
)

# Loading the right rectified stereo image paths for the chosen log.
right_stereo_img_fpaths = stereo_data_loader.get_ordered_log_stereo_image_fpaths(
    log_id=log_id,
    camera_name=STEREO_FRONT_RIGHT_RECT,
)

# Loading the disparity map paths for the chosen log.
disparity_map_fpaths = stereo_data_loader.get_ordered_log_disparity_map_fpaths(
    log_id=log_id,
    disparity_name="stereo_front_left_rect_disparity",
)

# Loading the disparity map paths for foreground objects for the chosen log.
disparity_obj_map_fpaths = stereo_data_loader.get_ordered_log_disparity_map_fpaths(
    log_id=log_id,
    disparity_name="stereo_front_left_rect_objects_disparity",
)

#Now use those functions there and actually load the data
stereo_front_left_rect_image = stereo_data_loader.get_rectified_stereo_image(left_stereo_img_fpaths[idx])
stereo_front_right_rect_image = stereo_data_loader.get_rectified_stereo_image(right_stereo_img_fpaths[idx])

# Loading the ground-truth disparity maps.
stereo_front_left_rect_disparity = stereo_data_loader.get_disparity_map(disparity_map_fpaths[idx])
# Loading the ground-truth disparity maps for foreground objects only.
stereo_front_left_rect_objects_disparity = stereo_data_loader.get_disparity_map(disparity_obj_map_fpaths[idx])

#Look at the data:
stereo_front_left_rect_disparity_dil = cv2.dilate(
    stereo_front_left_rect_disparity,
    kernel=np.ones((2, 2), np.uint8),
    iterations=7,
)

stereo_front_left_rect_objects_disparity_dil = cv2.dilate(
    stereo_front_left_rect_objects_disparity,
    kernel=np.ones((2, 2), np.uint8),
    iterations=7,
)

plt.figure(figsize=(9, 9))
plt.subplot(2, 2, 1)
plt.title("Rectified left stereo image")
plt.imshow(stereo_front_left_rect_image)
plt.axis("off")
plt.subplot(2, 2, 2)
plt.title("Rectified right stereo image")
plt.imshow(stereo_front_right_rect_image)
plt.axis("off")
plt.subplot(2, 2, 3)
plt.title("Left disparity map")
plt.imshow(
    stereo_front_left_rect_disparity_dil,
    cmap="nipy_spectral",
    vmin=0,
    vmax=192,
    interpolation="none",
)
plt.axis("off")
plt.subplot(2, 2, 4)
plt.title("Left object disparity map")
plt.imshow(
    stereo_front_left_rect_objects_disparity_dil,
    cmap="nipy_spectral",
    vmin=0,
    vmax=192,
    interpolation="none",
)
plt.axis("off")
plt.tight_layout()

#Recovering calibration info:
# First, we need to load the camera calibration. Specifically, we want the camera intrinsic parameters.
calib_data = stereo_data_loader.get_log_calibration_data(log_id=log_id)
camera_config = get_calibration_config(calib_data, camera_name=STEREO_FRONT_LEFT_RECT)

# Getting the focal lenght and baseline. Note that the baseline is constant for the Argoverse stereo rig setup.
focal_lenght = camera_config.intrinsic[0, 0]  # Focal length in pixels.
BASELINE = 0.2986  # Baseline in meters.

# We consider disparities greater than zero to be valid disparities.
# A zero disparity corresponds to an infinite distance.
valid_pixels = stereo_front_left_rect_disparity > 0

# Using the stereo relationship previsouly described, we can recover the depth map by:
stereo_front_left_rect_depth = \
    np.float32((focal_lenght * BASELINE) / (stereo_front_left_rect_disparity + (1.0 - valid_pixels)))

# Recovering the colorized point cloud using Open3D.
left_image_o3d = o3d.geometry.Image(stereo_front_left_rect_image)
depth_o3d = o3d.geometry.Image(stereo_front_left_rect_depth)
rgbd_image_o3d = o3d.geometry.RGBDImage.create_from_color_and_depth(
    left_image_o3d,
    depth_o3d,
    convert_rgb_to_intensity=False,
    depth_scale=1.0,
    depth_trunc=200,
)
pinhole_camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
pinhole_camera_intrinsic.intrinsic_matrix = camera_config.intrinsic[:3, :3]
pinhole_camera_intrinsic.height = camera_config.img_height
pinhole_camera_intrinsic.width = camera_config.img_width
pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image_o3d, pinhole_camera_intrinsic)

# Showing the colorized point cloud using the interactive Plotly.
points = np.asarray(pcd.points)
colors = np.asarray(pcd.colors)

fig = go.Figure(
    data=[
        go.Scatter3d(
            x=points[:, 0],
            y=points[:, 1],
            z=points[:, 2],
            mode="markers",
            marker=dict(size=1, color=colors),
            )
    ],
  layout=dict(
      scene=dict(
            xaxis=dict(visible=False),
            yaxis=dict(visible=False),
          zaxis=dict(visible=False),
            aspectmode="data",
        )
    ),
)
fig.show() #<- not working on my system...

# Defining the SGM parameters (please check the OpenCV documentation for details).
# We found this parameters empirically and based on the Argoverse Stereo data.
max_disp = 192
win_size = 10
uniqueness_ratio = 15
speckle_window_size = 200
speckle_range = 2
block_size = 11
P1 = 8 * 3 * win_size ** 2
P2 = 32 * 3 * win_size ** 2

# Defining the Weighted Least Squares (WLS) filter parameters.
lmbda = 0.1
sigma = 1.0

# Defining the SGM left matcher.
left_matcher = cv2.StereoSGBM_create(
    minDisparity=0,
    numDisparities=max_disp,
    blockSize=block_size,
    P1=P1,
    P2=P2,
    disp12MaxDiff=max_disp,
    uniquenessRatio=uniqueness_ratio,
    speckleWindowSize=speckle_window_size,
    speckleRange=speckle_range,
    mode=cv2.STEREO_SGBM_MODE_SGBM_3WAY,
)

# Defining the SGM right matcher needed for the left-right consistency check in the WLS filter.
right_matcher = cv2.ximgproc.createRightMatcher(left_matcher)

# Defining the WLS filter.
wls_filter = cv2.ximgproc.createDisparityWLSFilter(matcher_left=left_matcher)
wls_filter.setLambda(lmbda)
wls_filter.setSigmaColor(sigma)

# Computing the disparity maps.
left_disparity = left_matcher.compute(stereo_front_left_rect_image, stereo_front_right_rect_image)
right_disparity = right_matcher.compute(stereo_front_right_rect_image, stereo_front_left_rect_image)

# Applying the WLS filter.
left_disparity_pred = wls_filter.filter(left_disparity, stereo_front_left_rect_image, None, right_disparity)

# Recovering the disparity map.
# OpenCV produces a disparity map as a signed short obtained by multiplying subpixel shifts with 16.
# To recover the true disparity values, we need to divide the output by 16 and convert to float.
left_disparity_pred = np.float32(left_disparity_pred) / 16.0

# OpenCV will also set negative values for invalid disparities where matches could not be found.
# Here we set all invalid disparities to zero.
left_disparity_pred[left_disparity_pred < 0] = 0

plt.figure(figsize=(9, 9))
plt.subplot(2, 2, 1)
plt.title("Rectified left stereo image")
plt.imshow(stereo_front_left_rect_image)
plt.axis("off")
plt.subplot(2, 2, 2)
plt.title("Rectified right stereo image")
plt.imshow(stereo_front_right_rect_image)
plt.axis("off")
plt.subplot(2, 2, 3)
plt.title("Ground-truth left disparity map")
plt.imshow(
    stereo_front_left_rect_disparity_dil,
    cmap="nipy_spectral",
    vmin=0,
    vmax=192,
    interpolation="none",
)
plt.axis("off")
plt.subplot(2, 2, 4)
plt.title("Estimated left disparity map")
plt.imshow(
    left_disparity_pred,
    cmap="nipy_spectral",
    vmin=0,
    vmax=192,
    interpolation="none"
)
plt.axis("off")
plt.tight_layout()

# We consider disparities greater than zero to be valid disparities.
# A zero disparity corresponds to an infinite distance.
valid_pixels = left_disparity_pred > 0

# Using the stereo relationship previsouly described, we can recover the predicted depth map by:
left_depth_pred = \
    np.float32((focal_lenght * BASELINE) / (left_disparity_pred + (1.0 - valid_pixels)))

# Recovering the colorized point cloud using Open3D.
#left_image_o3d = o3d.geometry.Image(stereo_front_left_rect_image)
#depth_o3d = o3d.geometry.Image(left_depth_pred)
#rgbd_image_o3d = o3d.geometry.RGBDImage.create_from_color_and_depth(
#    left_image_o3d,
#    depth_o3d,
#    convert_rgb_to_intensity=False,
#    depth_scale=1.0,
#    depth_trunc=200,
#)
#pinhole_camera_intrinsic = o3d.camera.PinholeCameraIntrinsic()
#pinhole_camera_intrinsic.intrinsic_matrix = camera_config.intrinsic[:3, :3]
#pinhole_camera_intrinsic.height = camera_config.img_height
#pinhole_camera_intrinsic.width = camera_config.img_width
#pcd = o3d.geometry.PointCloud.create_from_rgbd_image(rgbd_image_o3d, pinhole_camera_intrinsic)

# Showing the colorized point cloud using the interactive Plotly.
#points = np.asarray(pcd.points)
# Randomly sampling indices for faster rendering.
#indices = np.random.randint(len(points), size=100000)
#points = points[indices]
#colors = np.asarray(pcd.colors)[indices]

#fig = go.Figure(
#     data=[
#         go.Scatter3d(
#             x=points[:, 0],
#             y=points[:, 1],
#             z=points[:, 2],
#             mode="markers",
#             marker=dict(size=1, color=colors),
#         )
#     ],
#     layout=dict(
#         scene=dict(
#             xaxis=dict(visible=False),
#             yaxis=dict(visible=False),
#             zaxis=dict(visible=False),
#             aspectmode="data",
#         ),
#     ),
# )
# fig.show()

# Encoding the real disparity values to an uint16 data format to save as an uint16 PNG file.
left_disparity_pred = np.uint16(left_disparity_pred * 256.0)

timestamp = int(Path(disparity_map_fpaths[idx]).stem.split("_")[-1])

# Change the path to the directory you would like to save the result.
# The log id must be consistent with the stereo images' log id.
save_dir_disp = f"."

# The predicted disparity filename must have the format: 'disparity_[TIMESTAMP OF THE LEFT STEREO IMAGE].png'
filename = f"disparity_{timestamp}.png"

# Writing the PNG file to disk.
cv2.imwrite(filename, left_disparity_pred)

# Path to the predicted disparity maps.
pred_dir = Path(save_dir_disp)

# Path to the ground-truth disparity maps.
gt_dir = Path(f"{data_dir}/disparity_maps_v1.1/{split_name}/{log_id}")
gt_dir = Path(os.path.join(data_dir, 'disparity_maps_v1.1', 'train', log_id))

# Path to save the disparity error image.
save_figures_dir = Path(os.path.join('save_figs'))
save_figures_dir.mkdir(parents=True, exist_ok=True)

print(pred_dir)
print(gt_dir)

# Creating the stereo evaluator.
print('Creating Stereo Evaluator')
evaluator = StereoEvaluator(
    pred_dir,
    gt_dir,
    save_figures_dir,
    save_disparity_error_image=True,
    num_procs=1,
)
print('Running Stereo Evaluator')
# Running the stereo evaluation.
#metrics = evaluator.evaluate() this fails because I only look at a single value, but will come in handy later

# Printing the quantitative results (using json trick for organized printing).
#print(metrics)


from __future__ import annotations

from typing import Callable

import numpy as np

import darsia as da

class Solver:
    """
    Solver base class. Contains an apply method.
    All solvers that are implemented as subclasses should have their own
    apply method, and inherit the stopping criterion.

    Attributes:
        stoppingCriterion (darsia.StoppingCriterion): stopping criterion for the solver
        verbose (bool): set to True to print output data

    """

    def __init__(
        self, stoppingCriterion: da.StoppingCriterion, verbose: bool = False
    ) -> None:
        """
        Constructor for solver class.

        Arguments:
            stoppingCriterion (darsia.StoppingCriterion): stopping criterion for the solver
            verbose (bool): set to True to print output data
        """
        self.stoppingCriterion = stoppingCriterion
        self.stoppingCriterion.verbose = verbose

    # def apply(self) -> None:
    #     print("Please choose a solver!")

class CG(Solver):
    """
    Conjugate Gradients solver.

    Attributes:
        apply: applies the solver method

    """

    def apply(self, operator: Callable, rhs: np.ndarray, im0: np.ndarray) -> np.ndarray:
        """
        Applies the conjugate gradients solver.

        Arguments:
            operator (Callable): The left hand side operator that is to be inverted.
            rhs (np.ndarray): Right-hand side.
            im0 (np.ndarray): Initial guess.
        """

        # Set im to initial guess and compute initial residual and conjugate matrix
        im = im0
        res = operator(im0) - rhs
        p = -res

        # Define iteration counter
        iterations = 0

        # Iterate as long as the stopping criterion is not satisfied
        while not (self.stoppingCriterion.check(res, iterations)):

            # Compute the operator applied to the conjugate matrix
            # (I think that it is more efficient to store this new matrix
            # rather than doing the operation twice).
            po = operator(p)

            # Compute step length
            alpha = -da.im_product(res, p) / da.im_product(po, p)

            # Update the image and compute new residual and conjugate matrix
            im = im + alpha * p
            res = operator(im) - rhs
            beta = da.im_product(res, po) / da.im_product(po, p)
            p = -res + beta * p

            # Update the iteration counter
            iterations += 1

        # Jump once further in the search direction and return the solution image
        alpha = -da.im_product(res, p) / da.im_product(operator(p), p)
        im = im + alpha * p
        return im

class ModifiedRichardson(Solver):
    """
    Modified Richardson solver.

    Attributes:
        apply: applies the solver method

    """

    def apply(
        self, operator: Callable, rhs: np.ndarray, im0: np.ndarray, omega: float
    ) -> np.ndarray:
        """
        Applies the modified Richardson solver.

        Arguments:
            operator (Callable): The left hand side operator that is to be inverted.
            rhs (np.ndarray): Right-hand side.
            im0 (np.ndarray): Initial guess.
            omega (float): Update parameter.
        """
        # Set im to initial guess and compute initial residual
        im = im0
        res = rhs - operator(im)

        # Define iteration counter
        iteration = 0

        # Iterate as long as the stopping criterion is not satisfied
        while not (self.stoppingCriterion.check(res, iteration)):

            # Update the image and compute new residual
            im = im + omega * res
            res = rhs - operator(im)

            # Update the iteration counter
            iteration += 1

        # Return image
        return im


#import all libraries used
import threading
import socket
import sys
import logging
import os

#config logging and create logger object
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)

#creater formatter for logging
format = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')

#create file handler and set formatting
file_handler = logging.FileHandler('server.log')
file_handler.setFormatter(format)

#add file handler to logger object
logger.addHandler(file_handler)

#set encoding type
encoding = 'utf-8'

#set hostname and get port number from terminal
hostname = 'localhost'
port = int(sys.argv[1])

#create TCP/IP server socket and bind to hostname and port
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((hostname, port))

#starts listening for connections
server.listen()

#create lists for client connections and usernames
clients = []
usernames = []

#Function that brodadcasts messages to all connected clients
def message_broadcast(message):
    for client in clients:
        client.send(message)

#Function to handle client connections
def handle_client(client, client_address, parent_directory):
    #while loop to listen for more than one message
    while True:
        try:
            #get the index of current threads client from list of clients and get clients username
            position = clients.index(client)
            username = usernames[position]

            #accept and decode data from client
            message = client.recv(1024)
            decoded = message.decode(encoding)

            #remove client from list of clients and clean up connection
            if decoded == 'quit':
                clients.remove(client)
                client.close()

                #broadcast and log disconnection
                message_broadcast(f'{username} has left\n'.encode(encoding))
                logger.info(f'Client {username}: {client_address} left the server')
                usernames.remove(username)
            else:
                try:
                    #get filename and data of file from client
                    command, filename, text = decoded.split("/")
                    if command == 'upload':
                        #create a new file in clients upload folder
                        path = os.path.join(parent_directory, username)
                        create_file = os.path.join(path, filename)
                        with open(create_file, 'w') as file:
                            file.write(text)
                except:
                    #broadcast and log client message
                    logger.info(f'Message from {username}: {client_address}: {decoded}')
                    message_broadcast(message)
        except:
            break

#Main function to receive the clients connection
def connection():
    valid_username = True
    #while loop to accept multiple client connections
    while True:

        #accept client connections
        print('Server waiting for a connection...')
        client, client_address = server.accept()

        #recieve username from client
        username = client.recv(1024).decode(encoding)
        usernames.append(username)
        clients.append(client)

        print(f'A client has connected from {str(client_address)}')

        #set path for client
        parent_directory = os.getcwd()
        path = os.path.join(parent_directory, username)

        #create upload folder corresponding to clients username if one does not already exist
        if not os.path.exists(path):
            os.mkdir(path)

        #broadcast and log client connection
        print(f'Connection from {username}: {client_address}')
        message_broadcast(f'{username} has joined\n'.encode(encoding))
        logger.info(f'Client {username}: {client_address} joined the server')

        #send welcome message to client and instructions
        client.send('\nWelcome, you have connected to the server\n'.encode(encoding))
        client.send('\nEnter a message, type "quit" to exit or upload a text file using the following format; "upload/filenamme": '.encode(encoding))

        #create and start a thread for the client
        thread = threading.Thread(target=handle_client, args=(client, client_address,parent_directory))
        thread.start()

if __name__ == "__main__":
    connection()


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 在selenium中嵌入js方法
# created by heqingpan
#from page import Page
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

_init_js="""
(function (){
if (window.__e)
{ return;
}
var e=document.createElement('div');
e.setAttribute("id","__s_msg");
e.style.display="none";
document.body.appendChild(e);
window.__e=e;
})();
window.__s_set_msg=function(a){
    window.__e.setAttribute("msg",a.toString()||"");
}
"""
_loadJsFmt="""
var script = document.createElement('script');
script.src = "{0}";
document.body.appendChild(script);
"""
_jquery_cdn="http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"
_warpjsfmt="__s_set_msg({0})"

class ExeJs(object):
    def __init__(self, driver, trytimes=10):

        self.jsdriver=driver
        self.jsdriver.execute_script(_init_js)
        while trytimes >0:
            try:
                self.msgNode=self.jsdriver.find_element_by_id('__s_msg')
                break
            except Exception:
                sleep(1)
                trytimes -= 1
        if self.msgNode is None:
            raise Exception()
    def exeWrap(self,jsstr,**kwargs):
        for (x,y) in kwargs.items():
            #print x,y
            jsstrt = jsstr.replace(x,y)
            jsstr = jsstrt
        jsstrt = jsstr.encode('utf8')
        #print jsstrt
        self.jsdriver.execute_script(_warpjsfmt.format(jsstrt))
    '''
    def exeWrap(self,jsstr,avar=None,bvar=None):
        if bvar is None:
            jsstrt = jsstr
        else:
            jsstrt = jsstr.replace(avar,bvar).encode('utf8')
        print jsstrt
        #jsstrt.encode('utf8')
        """jsstr 执行后有返回值，返回值通过self.getMsg()获取"""
        self.jsdriver.execute_script(_warpjsfmt.format(jsstrt))
    '''
    '''
    def exeWrap(self,jsstr):
        """jsstr 执行后有返回值，返回值通过self.getMsg()获取"""
        self.jsdriver.execute_script(_warpjsfmt.format(jsstr))
    '''
    def loadJs(self,path):
        self.execute(_loadJsFmt.format(path))
    def loadJquery(self,path=_jquery_cdn):
        self.loadJs(path)
    def execute(self,jsstr):
        self.jsdriver.execute_script(jsstr)
    def getMsg(self):
        return self.msgNode.get_attribute('msg')


# coding=utf-8
from kivy.network.urlrequest import UrlRequest

# classe para guardar os dados consumidos na aplicação
class Client:
    # url da api a ser consumida
    base_url = 'http://monitoruv.herokuapp.com/api/'
    # armazena o dispositivo manipulado atualmente na aplicação
    current_dispositivo = None
    # lista de dispositivos
    dispositivos = []
    # lista dos dispositivos locais
    local_dispositivos = []

# classe que representa uma leitura uv armazenada no banco
class Dado:
    def __init__(self, leituraUV=0, data='', dispositivo_id=1):
        self.leituraUV = leituraUV
        self.data = data
        self.dispositivo_id = dispositivo_id

# classe que representa um dispositivo(arduino + sensor + wifi)
class Dispositivo:

    # historico de leituras do dispositivo
    history = []

    def __init__(self, nome='', longitude=0.0, latitude=0.0, is_local=False, ip_addr='', db_id=0, last_reading=0):
        self.nome = nome
        self.longitude = longitude
        self.latitude = latitude
        self.is_selected = False
        self.is_local = is_local
        self.ip_addr = ip_addr
        self.db_id = db_id
        self.last_reading = last_reading

    # devolve a lista de todos os dispositivos cadastrados no banco
    @staticmethod
    def all():
        return Client.dispositivos

    # ========================================================
    # Histórico
    # ========================================================

    # obtém o histórico das últimas 24 horas de leitura do dispositivo
    def fetch_history(self, on_success=None, on_error=None):
        Client.dispositivos_on_fetch_history_success = on_success
        Client.dispositivos_on_fetch_history_error = on_error

        UrlRequest(Client.base_url + "dispositivos/" + str(self.db_id) + '/last_day/',
                   on_success=self.__on_fetch_history_success,
                   on_failure=self.__on_fetch_history_error,
                   on_error=self.__on_fetch_history_error)

    def __on_fetch_history_success(self, req, res):
        self.history = []
        for item in res:
            self.history.append(Dado(leituraUV=item['leituraUV'],
                                     data=item['data'],
                                     dispositivo_id=item['dispositivo']))

        if Client.dispositivos_on_fetch_history_success:
            Client.dispositivos_on_fetch_history_success()

    def __on_fetch_history_error(self, req, res):
        print('ERROR on fetch history')

        if Client.dispositivos_on_fetch_history_error:
            Client.dispositivos_on_fetch_history_error()

    # ========================================================
    # Última leitura
    # ========================================================

    # pega a última leitura leitura realizada pelo dispositivo
    def update_reading(self, on_success=None, on_error=None):
        Client.dispositivos_on_update_reading_success = on_success
        Client.dispositivos_on_update_reading_error = on_error
        if self.is_local:
            UrlRequest('http://' + self.ip_addr + '/read',
                       on_success=self.__on_update_reading_success,
                       on_failure=self.__on_update_reading_error,
                       on_error=self.__on_update_reading_error)
        else:
            UrlRequest(Client.base_url + "dispositivos/" + str(self.db_id) + '/last/',
                       on_success=self.__on_update_reading_success,
                       on_failure=self.__on_update_reading_error,
                       on_error=self.__on_update_reading_error)

    def __on_update_reading_success(self, req, res):
        if self.is_local:
            self.last_reading = int(str(res).split(':')[1])
        else:
            self.last_reading = res[0]['leituraUV']

        if Client.dispositivos_on_update_reading_success:
            Client.dispositivos_on_update_reading_success()

    def __on_update_reading_error(self, req, res):
        print('ERROR on update reading')

        if Client.dispositivos_on_update_reading_error:
            Client.dispositivos_on_update_reading_error()

    # ========================================================
    # Alterar nome de dispositivo local
    # ========================================================

    # troca para um novo nome um dispositivo local
    def change_name(self, new_name, on_success=None, on_error=None):
        if self.is_local:
            Client.dispositivos_on_change_name_success = on_success
            Client.dispositivos_on_change_name_error = on_error

            UrlRequest('http://' + self.ip_addr + '/id/' + new_name,
                       on_success=self.__on_change_name_success,
                       on_failure=self.__on_change_name_error,
                       on_error=self.__on_change_name_error)
        else:
            print('can\'t change name of a remote device')

    def __on_change_name_success(self, req, res):
        self.nome = str(res).splitlines()[0]

        if Client.dispositivos_on_change_name_success:
            Client.dispositivos_on_change_name_success()

    def __on_change_name_error(self, req, res):
        print('ERROR on change name')

        if Client.dispositivos_on_change_name_error:
            Client.dispositivos_on_change_name_error()

    # ========================================================
    # Descoberta
    # ========================================================

    # tenta uma conexão com um dispositivo local, perguntando seu ID
    @staticmethod
    def discover(address, on_success=None, on_error=None):
        Client.dispositivos_on_discover_success = on_success
        Client.dispositivos_on_discover_error = on_error

        Client.local_device = Dispositivo(ip_addr=address, is_local=True)

        UrlRequest('http://' + address + '/id',
                   on_success=Dispositivo.__on_discover_success,
                   on_failure=Dispositivo.__on_discover_error,
                   on_error=Dispositivo.__on_discover_error)

    @staticmethod
    def __on_discover_success(req, res):

        Client.local_device.nome = str(res).splitlines()[0]

        Client.local_dispositivos.append(Client.local_device)

        if Client.dispositivos_on_discover_success:
            Client.dispositivos_on_discover_success()

    @staticmethod
    def __on_discover_error(req, res):
        print('ERROR on discovery')

        if Client.dispositivos_on_discover_error:
            Client.dispositivos_on_discover_error()

    # ========================================================
    # Todos os dispositivos
    # ========================================================

    # obtém a lista completa de dispositivos cadastrados
    @staticmethod
    def fetch_all(on_success=None, on_error=None):
        Client.dispositivos_on_fetch_all_success = on_success
        Client.dispositivos_on_fetch_all_error = on_error

        UrlRequest(Client.base_url + 'dispositivos/',
                   on_success=Dispositivo.__on_fetch_all_success,
                   on_failure=Dispositivo.__on_fetch_all_error,
                   on_error=Dispositivo.__on_fetch_all_error)

    @staticmethod
    def __on_fetch_all_success(req, res):
        Client.dispositivos = []

        count = 1

        for item in res:
            Client.dispositivos.append(Dispositivo(nome=item['nome'],
                                                   longitude=item['longitude'],
                                                   latitude=item['latitude'],
                                                   db_id=count))
            count += 1

        for item in Client.local_dispositivos:
            Client.dispositivos.append(item)

        if Client.dispositivos_on_fetch_all_success:
            Client.dispositivos_on_fetch_all_success()

    @staticmethod
    def __on_fetch_all_error(req, err):
        print('failure')

        if Client.dispositivos_on_fetch_all_error:
            Client.dispositivos_on_fetch_all_error()


from pyven.exceptions.exception import PyvenException

import pyven.constants
from pyven.steps.step import Step
from pyven.steps.utils import retrieve
from pyven.checkers.checker import Checker

from pyven.logging.logger import Logger
from pyven.reporting.content.step import StepListing

class PackageStep(Step):
    def __init__(self, verbose, nb_threads=1):
        super(PackageStep, self).__init__(verbose)
        self.name = 'package'
        self.checker = Checker('Packaging')
        self.nb_threads = nb_threads

    def process(self):
        return self._process_parallel()

    @Step.error_checks
    def _process(self, project):
        ok = retrieve('artifact', project, project.artifacts, self.checker) and retrieve('package', project, project.packages, self.checker)
        if ok:
            for package in [p for p in project.packages.values() if not p.to_retrieve]:
                try:
                    if not package.pack(Step.WORKSPACE):
                        ok = False
                except PyvenException as e:
                    self.checker.errors.append(e.args)
                    for msg in e.args:
                        Logger.get().error(msg)
                    ok = False
        if not ok:
            project.status = pyven.constants.STATUS[1]
            Logger.get().error(self.name + ' errors found')
        else:
            project.status = pyven.constants.STATUS[0]
            Logger.get().info(self.name + ' completed')
        return ok

    def report_content(self):
        listings = []
        if self.checker.enabled():
            listings.append(self.checker.report_content())
        return StepListing(title=self.title(), status=self.report_status(), listings=listings)


# Exercício Python 083: Crie um programa onde o usuário digite uma expressão qualquer que use parênteses. Seu aplicativo
# deverá analisar se a expressão passada está com os parênteses abertos e fechados na ordem correta.
paren = []

exp = (str(input('Digite uma expressão matemática: '))).strip()
for c in exp:
    if '(' in c:
        paren.append(c)
    elif ')' in c:
        if '('in paren:
            paren.pop()
        else:
            paren.append(c)
print(paren)
if len(paren) == 0:
    print('Expressão válida')
else:
    print('Expressão inválida')


from selenium import webdriver
from selenium.webdriver.common.by import By
from minitools.selenium.geetest import ClickSelenium
from selenium.webdriver.support import expected_conditions as EC

class GongShang(ClickSelenium):

    def __init__(self):
        self.driver = webdriver.Chrome('D:\chromedriver.exe')
        self.driver.get("http://www.gsxt.gov.cn/index.html")
        self.init_property()

    def capture_interface(self):
        search = self.waiter.until(EC.element_to_be_clickable((By.ID, 'keyword')))
        submit = self.waiter.until(EC.element_to_be_clickable((By.ID, 'btn_query')))
        self.sleep(2)
        search.clear()
        search.send_keys("武汉数博科技")
        self.sleep(2)
        submit.click()

    def calculate_track(self, picture):
        """How to get track???"""

    def check(self):
        self.waiter.until(EC.presence_of_element_located((By.CSS_SELECTOR, '.search_logo_100000')))
        element = self.driver.find_element_by_xpath('//*[@class="search_list_item db"][1]')
        print(element.get_attribute('href'))
        print(self.driver.get_cookies())

if __name__ == '__main__':
    GongShang().run()


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

import codecs
import exceptions
import locale
import re
import string
import sys
import unicodedata
try:
	from functools import reduce
except ImportError:
	# Python < 2.6
	pass

env_errors = (EnvironmentError, )
if sys.platform == "win32":
	import pywintypes
	env_errors = env_errors + (pywintypes.error, pywintypes.com_error)

from encoding import get_encodings

fs_enc = get_encodings()[1]

ascii_printable = "".join([getattr(string, name) for name in ("digits",
						   "ascii_letters", "punctuation", "whitespace")])

# Control chars are defined as charcodes in the decimal range 0-31 (inclusive)
# except whitespace characters, plus charcode 127 (DEL)
control_chars = "".join([chr(i) for i in list(range(0, 9)) + list(range(14, 32)) + [127]])

# Safe character substitution - can be used for filenames
# i.e. no \/:*?"<>| will be added through substitution
# Contains only chars that are not normalizable
safesubst = {# Latin-1 supplement
			 "\u00a2": "c", # Cent sign
			 "\u00a3": "GBP", # Pound sign
			 "\u00a5": "JPY", # Yen sign
			 "\u00a9": "(C)", # U+00A9 copyright sign
			 "\u00ac": "!", # Not sign
			 "\u00ae": "(R)", # U+00AE registered sign
			 "\u00b0": "deg", # Degree symbol
			 "\u00b1": "+-",
			 "\u00c4": "Ae", # Capital letter A with diaresis (Umlaut)
			 "\u00c5": "Aa", # Capital letter A with ring above
			 "\u00c6": "AE",
			 "\u00d6": "Oe", # Capital letter O with diaresis (Umlaut)
			 "\u00dc": "Ue", # Capital letter U with diaresis (Umlaut)
			 "\u00d7": "x", # U+00D7 multiplication sign
			 "\u00df": "ss",
			 "\u00e4": "ae", # Small letter a with diaresis (Umlaut)
			 "\u00e5": "aa", # Small letter a with ring above
			 "\u00e6": "ae",
			 "\u00f6": "oe", # Small letter o with diaresis (Umlaut)
			 "\u00fc": "ue", # Small letter u with diaresis (Umlaut)
			 # Latin extended A
			 "\u0152": "OE",
			 "\u0153": "oe",
			 # General punctuation
			 "\u2010": "-",
			 "\u2011": "-",
			 "\u2012": "-",
			 "\u2013": "-", # U+2013 en dash
			 "\u2014": "--", # U+2014 em dash
			 "\u2015": "---", # U+2015 horizontal bar
			 "\u2018": "'",
			 "\u2019": "'",
			 "\u201a": ",",
			 "\u201b": "'",
			 "\u201c": "''",
			 "\u201d": "''",
			 "\u201e": ",,",
			 "\u201f": "''",
			 "\u2032": "'",
			 "\u2033": "''",
			 "\u2034": "'''",
			 "\u2035": "'",
			 "\u2036": "''",
			 "\u2037": "'''",
			 "\u2053": "~",
			 # Superscripts and subscripts
			 "\u207b": "-", # Superscript minus
			 "\u208b": "-", # Subscript minus
			 # Currency symbols
			 "\u20a1": "CRC", # Costa Rica 'Colon'
			 "\u20a6": "NGN", # Nigeria 'Naira'
			 "\u20a9": "KRW", # South Korea 'Won'
			 "\u20aa": "ILS", # Isreael 'Sheqel'
			 "\u20ab": "VND", # Vietnam 'Dong'
			 "\u20ac": "EUR",
			 "\u20ad": "LAK", # Laos 'Kip'
			 "\u20ae": "MNT", # Mongolia 'Tugrik'
			 "\u20b2": "PYG", # Paraguay 'Guarani'
			 "\u20b4": "UAH", # Ukraine 'Hryvnja'
			 "\u20b5": "GHS", # Ghana 'Cedi'
			 "\u20b8": "KZT", # Kasachstan 'Tenge'
			 "\u20b9": "INR", # Indian 'Rupee'
			 "\u20ba": "TRY", # Turkey 'Lira'
			 "\u20bc": "AZN", # Aserbaidchan 'Manat'
			 "\u20bd": "RUB", # Russia 'Ruble'
			 "\u20be": "GEL", # Georgia 'Lari'
			 # Letter-like symbols
			 "\u2117": "(P)",
			 # Mathematical operators
			 "\u2212": "-", # U+2212 minus sign
			 "\u2260": "!=",
			 # Enclosed alphanumerics
			 "\u2460": "(1)",
			 "\u2461": "(2)",
			 "\u2462": "(3)",
			 "\u2463": "(4)",
			 "\u2464": "(5)",
			 "\u2465": "(6)",
			 "\u2466": "(7)",
			 "\u2467": "(8)",
			 "\u2468": "(9)",
			 "\u2469": "(10)",
			 "\u246a": "(11)",
			 "\u246b": "(12)",
			 "\u246c": "(13)",
			 "\u246d": "(14)",
			 "\u246e": "(15)",
			 "\u246f": "(16)",
			 "\u2470": "(17)",
			 "\u2471": "(18)",
			 "\u2472": "(19)",
			 "\u2473": "(20)",
			 "\u24eb": "(11)",
			 "\u24ec": "(12)",
			 "\u24ed": "(13)",
			 "\u24ee": "(14)",
			 "\u24ef": "(15)",
			 "\u24f0": "(16)",
			 "\u24f1": "(17)",
			 "\u24f2": "(18)",
			 "\u24f3": "(19)",
			 "\u24f4": "(20)",
			 "\u24f5": "(1)",
			 "\u24f6": "(2)",
			 "\u24f7": "(3)",
			 "\u24f8": "(4)",
			 "\u24f9": "(5)",
			 "\u24fa": "(6)",
			 "\u24fb": "(7)",
			 "\u24fc": "(8)",
			 "\u24fd": "(9)",
			 "\u24fe": "(10)",
			 "\u24ff": "(0)",
			 # Dingbats
			 "\u2776": "(1)",
			 "\u2777": "(2)",
			 "\u2778": "(3)",
			 "\u2779": "(4)",
			 "\u277a": "(5)",
			 "\u277b": "(6)",
			 "\u277c": "(7)",
			 "\u277d": "(8)",
			 "\u277e": "(9)",
			 "\u277f": "(10)",
			 "\u2780": "(1)",
			 "\u2781": "(2)",
			 "\u2782": "(3)",
			 "\u2783": "(4)",
			 "\u2784": "(5)",
			 "\u2785": "(6)",
			 "\u2786": "(7)",
			 "\u2787": "(8)",
			 "\u2788": "(9)",
			 "\u2789": "(10)",
			 "\u278a": "(1)",
			 "\u278b": "(2)",
			 "\u278c": "(3)",
			 "\u278d": "(4)",
			 "\u278e": "(5)",
			 "\u278f": "(6)",
			 "\u2790": "(7)",
			 "\u2791": "(8)",
			 "\u2792": "(9)",
			 "\u2793": "(10)",}

# Extended character substitution - can NOT be used for filenames
# Contains only chars that are not normalizable
subst = dict(safesubst)
subst.update({# Latin-1 supplement
			  "\u00a6": "|",
			  "\u00ab": "<<",
			  "\u00bb": ">>",
			  "\u00bc": "1/4",
			  "\u00bd": "1/2",
			  "\u00be": "3/4",
			  "\u00f7": ":",
			  # General punctuation
			  "\u201c": "\x22",
			  "\u201d": "\x22",
			  "\u201f": "\x22",
			  "\u2033": "\x22",
			  "\u2036": "\x22",
			  "\u2039": "<",
			  "\u203a": ">",
			  "\u203d": "!?",
			  "\u2044": "/",
			  # Number forms
			  "\u2153": "1/3",
			  "\u2154": "2/3",
			  "\u215b": "1/8",
			  "\u215c": "3/8",
			  "\u215d": "5/8",
			  "\u215e": "7/8",
			  # Arrows
			  "\u2190": "<-",
			  "\u2192": "->",
			  "\u2194": "<->",
			  # Mathematical operators
			  "\u226a": "<<",
			  "\u226b": ">>",
			  "\u2264": "<=",
			  "\u2265": "=>",})

class StrList(list):

	""" It's a list. It's a string. It's a list of strings that behaves like a
	string! And like a list."""

	def __init__(self, seq=tuple()):
		list.__init__(self, seq)

	def __iadd__(self, text):
		self.append(text)
		return self

	def __getattr__(self, attr):
		return getattr(str(self), attr)

	def __str__(self):
		return "".join(self)

def asciize(obj):
	"""
	Turn several unicode chars into an ASCII representation.

	This function either takes a string or an exception as argument (when used
	as error handler for encode or decode).

	"""
	chars = ""
	if isinstance(obj, Exception):
		for char in obj.object[obj.start:obj.end]:
			chars += subst.get(char, normalencode(char).strip() or "?")
		return chars, obj.end
	else:
		return obj.encode("ASCII", "asciize")

codecs.register_error("asciize", asciize)

def safe_asciize(obj):
	"""
	Turn several unicode chars into an ASCII representation.

	This function either takes a string or an exception as argument (when used
	as error handler for encode or decode).

	"""
	chars = ""
	if isinstance(obj, Exception):
		for char in obj.object[obj.start:obj.end]:
			if char in safesubst:
				subst_char = safesubst[char]
			else:
				subst_char = "_"
				if char not in subst:
					subst_char = normalencode(char).strip() or subst_char
			chars += subst_char
		return chars, obj.end
	else:
		return obj.encode("ASCII", "safe_asciize")

codecs.register_error("safe_asciize", safe_asciize)

def escape(obj):
	"""
	Turn unicode chars into escape codes.

	This function either takes a string or an exception as argument (when used
	as error handler for encode or decode).

	"""
	chars = ""
	if isinstance(obj, Exception):
		for char in obj.object[obj.start:obj.end]:
			chars += subst.get(char, "\\u%s" % hex(ord(char))[2:].rjust(4, '0'))
		return chars, obj.end
	else:
		return obj.encode("ASCII", "escape")

codecs.register_error("escape", escape)

def make_ascii_printable(text, subst=""):
	return "".join([char if char in ascii_printable else subst for char in text])

def make_filename_safe(unistr, encoding=fs_enc, subst="_", concat=True):
	"""
	Make sure unicode string is safe to use as filename.

	I.e. turn characters that are invalid in the filesystem encoding into ASCII
	equivalents and replace characters that are invalid in filenames with
	substitution character.

	"""
	# Turn characters that are invalid in the filesystem encoding into ASCII
	# substitution character '?'
	# NOTE that under Windows, encoding with the filesystem encoding may
	# substitute some characters even in "strict" replacement mode depending
	# on the Windows language setting for non-Unicode programs! (Python 2.x
	# under Windows supports Unicode by wrapping the win32 ASCII API, so it is
	# a non-Unicode program from that point of view. This problem presumably
	# doesn't exist with Python 3.x which uses the win32 Unicode API)
	unidec = unistr.encode(encoding, "replace").decode(encoding)
	# Replace substitution character '?' with ASCII equivalent of original char
	uniout = ""
	for i, c in enumerate(unidec):
		if c == "?":
			# Note: We prevent IndexError by using slice notation which will
			# return an empty string if unistr should be somehow shorter than
			# unidec. Technically, this should never happen, but who knows
			# what hidden bugs and quirks may linger in the Python 2.x Unicode
			# implementation...
			c = safe_asciize(unistr[i:i + 1])
		uniout += c
	# Remove invalid chars
	pattern = r"[\\/:*?\"<>|]"
	if concat:
		pattern += "+"
	uniout = re.sub(pattern, subst, uniout)
	return uniout

def normalencode(unistr, form="NFKD", encoding="ASCII", errors="ignore"):
	"""
	Return encoded normal form of unicode string

	"""
	return unicodedata.normalize(form, unistr).encode(encoding, errors)

def box(text, width=80, collapse=False):
	"""
	Create a box around text (monospaced font required for display)

	"""
	content_width = width - 4
	text = wrap(safe_unicode(text), content_width)
	lines = text.splitlines()
	if collapse:
		content_width = 0
		for line in lines:
			content_width = max(len(line), content_width)
		width = content_width + 4
	horizontal_line = "\u2500" * (width - 2)
	box = ["\u250c%s\u2510" % horizontal_line]
	for line in lines:
		box.append("\u2502 %s \u2502" % line.ljust(content_width))
	box.append("\u2514%s\u2518" % horizontal_line)
	return "\n".join(box)

def center(text, width = None):
	"""
	Center (mono-spaced) text.

	If no width is given, the longest line
	(after breaking at each newline) is used as max width.

	"""
	text = text.split("\n")
	if width is None:
		width = 0
		for line in text:
			if len(line) > width:
				width = len(line)
	i = 0
	for line in text:
		text[i] = line.center(width)
		i += 1
	return "\n".join(text)

def create_replace_function(template, values):
	""" Create a replace function for use with e.g. re.sub """
	def replace_function(match, template=template, values=values):
		template = match.expand(template)
		return template % values
	return replace_function

def ellipsis(text, maxlen=64, pos="r"):
	""" Truncate text to maxlen characters and add elipsis if it was longer.

	Elipsis position can be 'm' (middle) or 'r' (right).

	"""
	if len(text) <= maxlen:
		return text
	if pos == "r":
		return text[:maxlen - 1] + "\u2026"
	elif pos == "m":
		return text[:maxlen / 2] + "\u2026" + text[-maxlen / 2 + 1:]

def hexunescape(match):
	""" To be used with re.sub """
	return chr(int(match.group(1), 16))

def indent(text, prefix, predicate=None):
	# From Python 3.7 textwrap module
    """Adds 'prefix' to the beginning of selected lines in 'text'.

    If 'predicate' is provided, 'prefix' will only be added to the lines
    where 'predicate(line)' is True. If 'predicate' is not provided,
    it will default to adding 'prefix' to all non-empty lines that do not
    consist solely of whitespace characters.
    """
    if predicate is None:
        def predicate(line):
            return line.strip()

    def prefixed_lines():
        for line in text.splitlines(True):
            yield (prefix + line if predicate(line) else line)
    return ''.join(prefixed_lines())

def universal_newlines(txt):
	"""
	Return txt with all new line formats converted to POSIX newlines.

	"""
	return txt.replace("\r\n", "\n").replace("\r", "\n")

def replace_control_chars(txt, replacement=" ", collapse=False):
	""" Replace all control characters.

	Default replacement character is ' ' (space).
	If the 'collapse' keyword argument evaluates to True, consecutive
	replacement characters are collapsed to a single one.

	"""
	txt = strtr(txt, dict(list(zip(control_chars, [replacement] * len(control_chars)))))
	if collapse:
		while replacement * 2 in txt:
			txt = txt.replace(replacement * 2, replacement)
	return txt

def safe_basestring(obj):
	"""
	Return a unicode or string representation of obj

	Return obj if isinstance(obj, basestring). Otherwise, return unicode(obj),
	string(obj), or repr(obj), whichever succeeds first.

	"""
	if isinstance(obj, env_errors):
		# Possible variations of environment-type errors:
		# - instance with 'errno', 'strerror', 'filename' and 'args' attributes
		#   (created by EnvironmentError with three arguments)
		#   NOTE: The 'args' attribute will contain only the first two arguments
		# - instance with 'errno', 'strerror' and 'args' attributes
		#   (created by EnvironmentError with two arguments)
		# - instance with just 'args' attribute
		#   (created by EnvironmentError with one or more than three arguments)
		# - urllib2.URLError with empty 'args' attribute but 'reason' and
		#   'filename' attributes
		# - pywintypes.error with 'funcname', 'message', 'strerror', 'winerror'
		#   and 'args' attributes
		if hasattr(obj, "reason"):
			if isinstance(obj.reason, str):
				obj.args = (obj.reason, )
			else:
				obj.args = obj.reason
		error = []
		if getattr(obj, "winerror", None) is not None:
			# pywintypes.error or WindowsError
			error.append("[Windows Error %s]" % obj.winerror)
		elif getattr(obj, "errno", None) is not None:
			error.append("[Errno %s]" % obj.errno)
		if getattr(obj, "strerror", None) is not None:
			if getattr(obj, "filename", None) is not None:
				error.append(obj.strerror.rstrip(":.") + ":")
			elif getattr(obj, "funcname", None) is not None:
				# pywintypes.error
				error.append(obj.funcname + ": " + obj.strerror)
			else:
				error.append(obj.strerror)
		if not error:
			error = list(obj.args)
		if getattr(obj, "filename", None) is not None:
			error.append(obj.filename)
		error = [safe_unicode(arg) for arg in error]
		obj = " ".join(error)
	elif isinstance(obj, KeyError) and obj.args:
		obj = "Key does not exist: " + repr(obj.args[0])
	oobj = obj
	if not isinstance(obj, str):
		try:
			obj = str(obj)
		except UnicodeDecodeError:
			try:
				obj = str(obj)
			except UnicodeEncodeError:
				obj = repr(obj)
	if isinstance(oobj, Exception) and not isinstance(oobj, Warning):
		if obj and oobj.__class__.__name__ in dir(exceptions):
			obj = obj[0].capitalize() + obj[1:]
		module = getattr(oobj, "__module__", "")
		package = safe_basestring.__module__.split(".")[0]  # Our own package
		if not module.startswith(package + "."):
			clspth = ".".join([_f for _f in [module, oobj.__class__.__name__] if _f])
			if not obj.startswith(clspth + ":") and obj != clspth:
				obj = ": ".join([_f for _f in [clspth, obj] if _f])
	return obj

def safe_str(obj, enc=fs_enc, errors="replace"):
	""" Return string representation of obj """
	obj = safe_basestring(obj)
	if isinstance(obj, str):
		return obj.encode(enc, errors)
	else:
		return obj

def safe_unicode(obj, enc=fs_enc, errors="replace"):
	""" Return unicode representation of obj """
	obj = safe_basestring(obj)
	if isinstance(obj, str):
		return obj
	else:
		return obj.decode(enc, errors)

def strtr(txt, replacements):
	"""
	String multi-replace, a bit like PHP's strtr.

	replacements can be a dict, a list or a string.
	If list or string, all matches are replaced with the empty string ("").

	"""
	if hasattr(replacements, "iteritems"):
		replacements = iter(replacements.items())
	elif isinstance(replacements, str):
		for srch in replacements:
			txt = txt.replace(srch, "")
		return txt
	for srch, sub in replacements:
		txt = txt.replace(srch, sub)
	return txt

def wrap(text, width = 70):
	"""
	A word-wrap function that preserves existing line breaks and spaces.

	Expects that existing line breaks are posix newlines (\\n).

	"""
	return reduce(lambda line, word, width=width: '%s%s%s' %
		(line,
		' \n'[(len(line)-line.rfind('\n')-1
			+ len(word.split('\n',1)[0]
				) >= width)],
		word),
		text.split(' ')
		)

def test():
	for k, v in subst.items():
		print(k, v)

if __name__ == "__main__":
	test()


"""ジェネレータ基礎
ジェネレータ内包表記の使い方
（タプルやリストに変換して使用する方法）

[説明ページ]
https://tech.nkhn37.net/python-generator-comprehension/#i-3

[内包表記まとめページ]
https://tech.nkhn37.net/python-comprehension/
"""
# ジェネレータからタプルに変換
gen = (i for i in range(10) if i % 2 == 0)
tpl_tmp = tuple(gen)
print(type(tpl_tmp), tpl_tmp)

# ジェネレータからリストに変換
gen = (i for i in range(10) if i % 2 == 0)
list_tmp = list(gen)
print(type(list_tmp), list_tmp)


from django.contrib.auth import get_user_model
from rest_framework import serializers
from comment.serializers import CommentSerializer

User = get_user_model()

class UserSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField()
    background_image_url = serializers.SerializerMethodField()

    def get_avatar_url(self, obj):
        try:
            domain_name = 'https://luna2.propulsion-learn.ch'
            full_path = domain_name + obj.avatar.url
            return full_path
        except Exception:
            return None

    def get_background_image_url(self, obj):
        try:
            domain_name = 'https://luna2.propulsion-learn.ch'
            full_path = domain_name + obj.background_image.url
            return full_path
        except Exception:
            return None

    class Meta:
        model = User
        fields = ['id', 'email', 'username', 'date_joined', 'first_name', 'last_name', 'phone',
                  'interests', 'avatar', 'about_me', 'reviews', 'background_image', 'avatar_url', 'comments',
                  'background_image_url']
        read_only_fields = ['id', 'email', 'username', 'reviews']

    def to_representation(self, instance):
        representation = super().to_representation(instance)
        representation['avatar'] = representation.pop('avatar_url')
        representation['background_image'] = representation.pop('background_image_url')
        representation['comments'] = CommentSerializer(instance.comments, many=True, context=self.context).data
        return representation

class SearchSerializer(serializers.Serializer):
    type = serializers.CharField(min_length=1, max_length=100)
    search_string = serializers.CharField(min_length=1, max_length=500)

    def validate(self, data):
        request_type = data.get('type')
        if request_type.lower() == 'restaurants' or request_type.lower() == 'reviews' \
                or request_type.lower() == 'users':
            return data
        else:
            raise serializers.ValidationError('Incorrect type. You must use either restaurants, reviews or users')


import os
import time
import random
import glob
import pickle
import numpy as np
from random import shuffle
from multiprocessing import Pool
from .data_augmentation import DataAugmentor
from .data_labelling import data_churn
from .myqueue import MyQueue, SharedMemoryQueue
from multiprocessing import Process, Queue
import gzip
import mmap

DA = DataAugmentor()
labelling = data_churn()

def _load_file(file, syn):
    if not syn:
        if file.endswith('gz'):
            return pickle.load(gzip.open(file, 'rb'))
        else:
            return pickle.load(open(file, 'rb'))
    else:
        if file.endswith('gz'):
            return pickle.load(gzip.open(file, 'rb'), encoding='latin1')
        else:
            return pickle.load(open(file, 'rb'), encoding='latin1')

def _data_aug(ins, augment_rate, test_mode=False, real_test=False):
    return DA.augment(ins, augment_rate=augment_rate, test_mode=test_mode, real_test=real_test)

def _data_label(ins):
    data = labelling._data_labeling(ins['img_name'], ins['img'],
                                    ins['contour'], ins['is_text_cnts'],
                                    ins['left_top'], ins['right_bottom'],
                                    ins.get('chars', None))
    return data

def loading_data(file, test_mode=False, real_test=False, syn=True):
    return _data_label(_data_aug(_load_file(file, syn=syn), augment_rate=100, test_mode=test_mode, real_test=real_test))

def MultiRun(func, args, thread_num=32):
    """
    runs the specified functions (func, args) with a Pool size of thread_num
    :param funcs: List(the target function)
    :param args: List[args in Dict], or a single arg for next
    :param thread_num: 32 by default
    :return:
    """

    p = Pool(thread_num)
    result = []
    for i in range(len(args)):
        result.append(p.apply_async(func, args=args[i]))
    p.close()
    p.join()

    return [r.get() for r in result]

def decompress(ins):
    name = ins[0]
    img = ins[1]
    non_zero, radius, cos, sin = ins[2]
    maps = np.zeros(shape=(*(img.shape[:2]), 5))
    maps[:, :, 4] = np.cast['uint8'](ins[3])  # -->TR
    maps[:, :, 0][non_zero] = 1               # -->TCL
    maps[:, :, 1][non_zero] = radius          # -->radius
    maps[:, :, 2][non_zero] = cos             # -->cos
    maps[:, :, 3][non_zero] = sin             # -->TCL
    cnt = ins[4]
    if len(ins) > 5:
        weight = ins[5]
    else:
        weight = np.zeros(shape=(*(img.shape[:2]), 1)) + 1
    return (name, img, maps, cnt, weight)

def load_pre_gen(file):
    try:
        return decompress(pickle.load(gzip.open(file, 'rb')))
    except:
        return None, None, None, None

class data_batch(object):
    def __init__(self, configs, logs):
        self.configs = configs
        self.logs = logs
        self.test_data = []

    def _data_test_set_loader(self):
        name = self.configs.dataset_name + '_' + 'test'
        if self.configs.real_test:
            save_name = name + '_original_size'
        else:
            save_name = name + '_512_size'
        pre_data_path = glob.glob(os.path.join(
            self.configs.pre_labelled_data_path, save_name, '*.bin'))
        #pre_data=glob.glob(pre_data_path)
        if len(pre_data_path)==0:
            test_path=os.path.join(self.configs.pre_labelled_data_path, save_name)
            if not os.path.isdir(test_path):
                os.makedirs(test_path)

            data_path = glob.glob(os.path.join(self.configs.raw_data_path, name, '*.bin'))

            data_output = MultiRun(loading_data,
                                   [(file, True, self.configs.real_test, False) for file in
                                    data_path],  # 32
                                   self.configs.threads)

            for data_ins in data_output:
                names = data_ins[0]
                images = data_ins[1]
                maps = data_ins[2]
                cnt = data_ins[3]
                weight = data_ins[4]
                self.test_data.append((names, images, maps, cnt, weight))
                pickle.dump(data_ins,open(os.path.join(test_path,names.split(':')[-1])+'.bin','wb'))

            self.logs['info']('test_set loaded.')
        else:
            for file in pre_data_path:
                data_ins = pickle.load(open(file,'rb'))
                names = data_ins[0]
                images = data_ins[1]
                maps = data_ins[2]
                cnt = data_ins[3]
                weight = data_ins[4]
                self.test_data.append((names, images, maps, cnt, weight))

    def data_test_set_gen(self, real_test):
        """
        :param task:task="train","dev","test","synth"
        :return:
        """
        if len(self.test_data) == 0:
            self._data_test_set_loader()

        if not real_test:
            for i in range((len(self.test_data) - 1) // self.configs.batch_size + 1):
                names = [ins[0] for ins in self.test_data[i * self.configs.batch_size:(i + 1) * self.configs.batch_size]]
                images = np.stack([ins[1] for ins in self.test_data[
                    i * self.configs.batch_size:(i + 1) * self.configs.batch_size]], axis=0)
                maps = np.stack([ins[2] for ins in self.test_data[
                    i * self.configs.batch_size:(i + 1) * self.configs.batch_size]], axis=0)
                cnts = [ins[3] for ins in self.test_data[
                    i * self.configs.batch_size:(i + 1) * self.configs.batch_size]]
                weights = np.stack([ins[4] for ins in self.test_data[
                    i * self.configs.batch_size:(i + 1) * self.configs.batch_size]],
                    axis=0)
                yield names, images, maps, cnts, weights
        else:
            for ins in self.test_data:
                names = [ins[0]] * len(self.configs.gpu_list)
                images = np.stack([ins[1]] * len(self.configs.gpu_list), axis=0)
                maps = np.stack([ins[2]] * len(self.configs.gpu_list), axis=0)
                cnts = [ins[3]] * len(self.configs.gpu_list)
                weights = np.stack([ins[4]] * len(self.configs.gpu_list), axis=0)
                yield names, images, maps, cnts, weights

    def data_gen_multiprocess(self, task):
        # print("data_gen_multiprocess")

        # while True:
        #    pass

        queue = SharedMemoryQueue(
            self.configs.QueueLength,
            [self.configs.batch_size, 512, 512, 3],
            [self.configs.batch_size, 512, 512, 5])

        def generate_work(id):
            #print("generate_work", id)
            random.seed(int(time.time() * 1000) + id)
            #print("generate_work started", id)

            if task == 'Synth':
                name = 'synthtext_chars'
                data_path = glob.glob(os.path.join(self.configs.SynthPath, '*.bin')) + \
                    glob.glob(os.path.join(self.configs.SynthPath, '*.gz'))
            else:
                name = self.configs.dataset_name + '_' + task
                data_path = glob.glob(os.path.join(self.configs.raw_data_path, name, '*.bin')) + \
                    glob.glob(os.path.join(
                        self.configs.raw_data_path, name, '*.gz'))

            shuffle(data_path)
            p = 0

            while True:
                t = time.time()
                if task != 'test' and p + self.configs.batch_size > len(data_path):
                    p = 0
                    shuffle(data_path)
                if p >= len(data_path):
                    break
                data_output = [loading_data(file, task == 'test', self.configs.real_test, syn=(task == 'Synth'))
                               for file in data_path[p:p + self.configs.batch_size]]
                for i in range(len(data_output) - 1, -1, -1):
                    if data_output[i][0] is None:
                        data_output.pop(i)
                while len(data_output) % len(self.configs.gpu_list) != 0:
                    data_output.pop(0)
                p += self.configs.batch_size
                names = [ins[0] for ins in data_output]
                images = np.stack([ins[1] for ins in data_output], axis=0)
                maps = np.stack([ins[2] for ins in data_output], axis=0)
                weights = np.stack([ins[4] for ins in data_output], axis=0)
                queue.put((names,
                           images,
                           maps,
                           data_output[0][3],
                           weights),
                          os.path.join(self.configs.pre_labelled_data_path, name))
                print(time.time() - t)

        def load_work(id):
            #print("generate_work", id)
            random.seed(int(time.time() * 1000) + id)
            #print("generate_work started", id)

            if task == 'Synth':
                name = 'synthtext_chars'
            else:
                name = self.configs.dataset_name + '_' + task
            data_path = glob.glob(os.path.join(
                self.configs.pre_labelled_data_path, name, '*'))

            shuffle(data_path)
            p = 0

            while True:
                t = time.time()
                if task != 'test' and p + self.configs.batch_size > len(data_path):
                    p = 0
                    shuffle(data_path)
                if p >= len(data_path):
                    break
                data_output = [load_pre_gen(file)
                               for file in data_path[p:p + self.configs.batch_size]]
                for i in range(len(data_output) - 1, -1, -1):
                    if data_output[i][0] is None:
                        data_output.pop(i)
                while len(data_output) % len(self.configs.gpu_list) != 0:
                    data_output.pop(0)
                p += self.configs.batch_size
                names = [ins[0] for ins in data_output]
                images = np.stack([ins[1] for ins in data_output], axis=0)
                maps = np.stack([ins[2] for ins in data_output], axis=0)
                weights = np.stack([ins[4] for ins in data_output], axis=0)
                queue.put((names,
                           images,
                           maps,
                           data_output[0][3],
                           weights), None)
                print(time.time() - t)
        # while True:
        #     pass
        # pool = Pool(30)
        # it takes at least 4 processes for Synth, and more for Totaltext(augmentation)
        for i in range(self.configs.threads):
            if self.configs.use_pre_generated_data:
                print('load from pre-generated files')
                process = Process(target=load_work, args=(i,))
            else:
                print('generate data and save')
                process = Process(target=generate_work, args=(i,))
            process.daemon = True
            process.start()
            # pool.apply_async(generate_work, (i))
        # pool.close()
        print('Background Multi-processing for Data Pre-Processing has started.')
        return queue


import sqlite3

def baza_yenile_qrup(record_list):
    try:
        with sqlite3.connect('baza.db') as db:
            cursor = db.cursor()
            print('Baza ile elaqe yaradildi')

            query="""UPDATE kitabxana set nesr=? where id=?"""
            cursor.executemany(query,record_list)
            db.commit()
            print('Bazada',cursor.rowcount,' data yenilendi')
    except sqlite3.Error as error:
        print('Xeta bas verdi', error)
    finally:
        if db:
            db.close()
            print('Bazaz ile elaqe kesildi')

verilenler=[
    ("4444",3),
    ("5555",4),
    ("6666",5)
]

baza_yenile_qrup(verilenler)


__author__ = 'soloomi'

# import Bio
from Bio import SeqIO, SeqFeature
from collections import defaultdict

def find_annotation(read_cigar_dict, annotation_file, file_format='genbank'):
    """
    Finds the annotation for the locations on the genome where multi-reads map to
    :param read_cigar_dict: a nested dictionary like: {read_id: {CIGAR: [list of mapping positions]}
    :param annotation_file: the path to the reference genome annotation file
    :param file_format: the format of annotation file: 'genbank' or 'fasta'
    """
    position_cigar = defaultdict(list)
    for read_id, cigar_dict in read_cigar_dict.items():
        # if this read has only one CIGAR and has aligned only once; it's a unique read
        if len(cigar_dict) == 1:
             for cigar in cigar_dict:  # it has only one key (CIGAR)
                if len(cigar_dict[cigar]) == 1:  # list of mapping positions
                    # it's not a multi-read
                    pass
                else:
                    # a multi-read with the same alignment
                    for cigar, positions_list in cigar_dict.items():
                        for position in positions_list:
                            # for each position, create a list of read alignments to that location
                            position_cigar[position].append(cigar)

        else:
            # a multi-read with different alignments
            for cigar, positions_list in cigar_dict.items():
                for position in positions_list:
                    # for each position, create a list of read alignments to that location
                    position_cigar[position].append(cigar)

    # All locations on the genome which have a multi-read mapped to
    sorted_positions = sorted(position_cigar.keys())

    i = 0
    out_file = open('ot-annotation.txt', 'w')
    record = SeqIO.read(annotation_file, file_format)
    print(len(record.features))
    # For each gene, find what multi-reads are in its region, if any
    for feature in record.features:
        # print(feature.location.start, feature.location.end, feature.location.strand)
        if feature.type == 'source':
            continue
        cigars_list = []
        while sorted_positions[i] in range(feature.location.start, feature.location.end + 1):
            cigars_list.append((sorted_positions[i], position_cigar[sorted_positions[i]]))
            if i < len(sorted_positions):
                i += 1
        if cigars_list:
            # print(feature.location.start, '-', feature.location.end, feature.type, cigars_list)
            out_file.write("{}-{} {} {}\n".format(feature.location.start, feature.location.end, feature.type, cigars_list))
    out_file.close()


import pyrenn
import LandMarkPointsExtractor.extractAndSaveLandmarkConfigurations as LM
import sys
import glob
import os
import numpy as np

def getDiff(x,y):
    xx = [ [] for i in range(len(x))]
    for i in range(len(x)):
        for j in range(len(x[0])):
            xx[i].append(x[i][j] - y[j])
    return xx

faces_folder_path = sys.argv[1]
caricaturesFolderPath = sys.argv[2]

XFaces = []
XCaricatures = []
YFaces = []
YCaricatures = []

for f in glob.glob(os.path.join(faces_folder_path, "*.jp*g")):
    LandMarkPoints = LM.saveAndReturnLandMarkPoints(f);
    xCoordis = []
    yCoordis = []
    for point in LandMarkPoints:
        xCoordis.append(point[0])
        yCoordis.append(point[1])
    XFaces.append(xCoordis)
    YFaces.append(yCoordis)

for f in glob.glob(os.path.join(caricaturesFolderPath, "*.jp*g")):
    LandMarkPoints = LM.saveAndReturnLandMarkPoints(f);
    xCoordis = []
    yCoordis = []
    for point in LandMarkPoints:
        xCoordis.append(point[0])
        yCoordis.append(point[1])
    XCaricatures.append(xCoordis)
    YCaricatures.append(yCoordis)

meanImageCoordinates = LM.saveAndReturnLandMarkPoints("Dataset/averageFace.jpg")

XFacesMeanDiff = getDiff(XFaces, [ meanImageCoordinates[i][0] for i in range(len(meanImageCoordinates)) ])
YFacesMeanDiff = getDiff(YFaces, [ meanImageCoordinates[i][1] for i in range(len(meanImageCoordinates)) ])

for i in range(len(XCaricatures)):
    for j in range(len(XCaricatures[0])):
        XCaricatures[i][j] = XCaricatures[i][j] - XFaces[i][j]
        YCaricatures[i][j] = YCaricatures[i][j] - YFaces[i][j]

print("XFacesMeand DIff:\n")
for i in XFacesMeanDiff:
    print(i)

print("YFacesMeand DIff:\n")
for i in YFacesMeanDiff:
    print(i)

print("XFacesCaricature DIff:\n")
for i in XCaricatures:
    print(i)

print("YFacesCaricature DIff:\n")
for i in YCaricatures:
    print(i)

net = pyrenn.CreateNN([68,68,68])
import pdb;
pdb.set_trace()
trainX = np.array(XFacesMeanDiff)
trainX = np.transpose(trainX)
outY = np.array(XCaricatures)
outY = np.transpose(outY)

pyrenn.train_LM(trainX, outY, net, verbose=True, k_max=1, E_stop=100 )

Y = pyrenn.NNOut(trainX, net)
print("Output OF NN")
for i in Y:
    print(i)


from django.urls import path
from . import views

app_name = 'ilaclar'

urlpatterns = [
    path('ilaclar', views.IlacList.as_view(), name='ilac-list'),
    # path('ilac/<ilac_adi>/', views.IlacMustahzarList.as_view(), name='ilac-detay'),
    path('etkenmadde/', views.EtkenMaddeList.as_view(), name='etkenmadde-list'),
]


"""backend URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from api.views import router, loggedIn, login, addcomment, deletePost
from api.views import addreply, addpost, deleteReply, deleteComment
from rest_framework import routers
from api.all import PostListView
urlpatterns = [
    path('admin/', admin.site.urls),
    path('login/', login),
    path('api/', include('rest_framework.urls', namespace='rest_framework')),
    path('api/auth', loggedIn),
    path('api/addcomment/', addcomment),
    path('api/addreply/', addreply),
    path('api/addpost/', addpost),
    path('api/deletereply/', deleteReply),
    path('api/deletecomment/', deleteComment),
    path('api/deletepost/', deletePost),
    # path('api/allofpost', PostListView.as_view())
]
r = routers.DefaultRouter()

for route in router  + [PostListView] :
    rn = routers.SimpleRouter()
    rn.register(route.name, route)
    r.registry.extend(rn.registry)

urlpatterns += [path('api/', include(r.urls))]


# ex03.png 그래프의

# 1. DFS 결과를 출력
def dfs(graph, node, visited):
    visited[node] = True

    print(node)

    for i in graph[node]:
        if visited[i] == False:
            dfs(graph, i, visited)

# 2. BFS 결과를 출력
def bfs(graph, node, visited):
    queue = [node]
    visited[node] = True

    while queue:
        node = queue.pop(0)
        print(node)

        for i in graph[node]:
            if visited[i] == False:
                queue.append(i)
                visited[i] = True

graph = [
    [1, 3],
    [0, 2, 5],
    [2, 3, 4, 5],
    [0, 1, 2, 4],
    [2, 3, 6],
    [1, 2],
    [1, 4]
]

visited = [False] * 7
dfs(graph, 1, visited)
print()
visited = [False] * 7
bfs(graph, 1, visited)


#!/bin/python3

import math
import os
import random
import re
import sys

# Complete the minimumBribes function below.
def minimumBribes(q):
    count=0
    n=len(q)
    i=0
    l=[0]*n
    swap=True
    while swap:
        swap=False
        for i in range(n):
            while i<n-1 and q[i]>q[i+1]:
                l[q[i]-1]+=1
                q[i],q[i+1]=q[i+1],q[i]
                swap=True
                i+=1
    k=0
    for s in l:
        k+=s

        if s>2:
            return ("Too chaotic")

    else:
        return k

if __name__ == '__main__':
    t = int(input())

    for t_itr in range(t):
        n = int(input())

        q = list(map(int, input().rstrip().split()))

        print(minimumBribes(q))


n = int(input())
a = list(map(int, input().split()))
a.append(0)
res = 1
t = 1
for i in range(1, n+1):
    if a[i] <= a[i-1]:
        if t > res:
            res = t
        t = 1
    else:
        t += 1
print(res)