"""Helper functions for plotting model evaluation results."""

import numpy as np
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import seaborn as sns

from src.plot.style import PALETTES, RCPARAMS, hex_to_rgb

# Register custom colormaps and set plot style
palettes = {k : hex_to_rgb(PALETTES[k]) for k in PALETTES.keys()}
for k in palettes.keys():
    cmap = LinearSegmentedColormap.from_list(k, palettes[k])
    mpl.colormaps.register(cmap)
sns.set_theme(
    context = 'paper',
    style="white",
    font_scale = 0.60,
    rc=RCPARAMS)

def test_plot():
    """Test the plot style with a dummy plot.

    :return: None
    :rtype: None
    """
    x = [1, 2, 3, 4]
    y = [1, 2, 3, 4]
    plt.plot(x, y)
    plt.savefig('test_plot.png')

def make_plot_data(scores):
    """Make data for plots.

    :param pd.DataFrame scores: scores from model evaluation
    :return: plot data
    :rtype: tuple[pd.DataFrame]
    """
    prob_true = scores.filter(regex='^test_prob_true_', axis=0)
    prob_pred = scores.filter(regex='^test_prob_pred_', axis=0)
    tn = scores.loc['test_tn', 'mean']
    fp = scores.loc['test_fp', 'mean']
    fn = scores.loc['test_fn', 'mean']
    tp = scores.loc['test_tp', 'mean']
    conf_matrix_scores = np.array([[tp, fp],
                                   [fn, tn]])
    return prob_true, prob_pred, conf_matrix_scores

def plot_train_calibration(prob_true, prob_pred, name, save_path):
    """Plot calibration errors.

    :param pd.DataFrame prob_true: true probabilities
    :param pd.DataFrame prob_pred: predicted probabilities
    :param str name: model name
    :param str save_path: path to save plot
    :return: None
    :rtype: None
    """
    fold_names = [col for col in prob_true.columns
                  if col.startswith('fold')]
    num_of_folds = len(fold_names)
    fig, axs = plt.subplots(nrows=1, ncols=2,
                            sharey=True,
                            figsize=(9, 4))
    colors = plt.get_cmap('hellafresh')
    for i in [0, 1]:
        axs[i].plot(
            [0, 1],
            [0, 1],
            linestyle='--',
            color='black',
            alpha=0.5,
            label='Perfect Calibration')
    for i, col in enumerate(fold_names):
        axs[0].plot(
            prob_pred[col],
            prob_true[col],
            color=colors(i / num_of_folds),
            label=f"{col}")
    axs[1].errorbar(
        prob_pred['mean'],
        prob_true['mean'],
        xerr=prob_pred['std'],
        yerr=prob_true['std'],
        fmt='none',
        label='Model Calibration')
    for i in [0, 1]:
        axs[i].set_xlim([0.1, 0.9])
        axs[i].set_ylim([0.1, 0.9])
        axs[i].set_title(f'Calibration Curve ({name})')
        axs[i].set_xlabel('Predicted Probability')
        axs[0].set_ylabel('True Probability')
        axs[i].legend(loc='upper left', framealpha=0.0)
    fig.tight_layout()
    fig.savefig(f"{save_path}/{name}_calibration_curve.png")
    return

def plot_test_calibration(holdout_scores, name, save_path):
    """Plot calibration curve for holdout data.

    :param dict holdout_scores: holdout scores
    :param str name: model name
    :param str save_path: path to save plot
    :return: None
    :rtype: None
    """
    x = [holdout_scores[f] for f in holdout_scores if f.startswith('prob_pred_')]
    y = [holdout_scores[f] for f in holdout_scores if f.startswith('prob_true_')]
    fig, ax = plt.subplots(figsize=(5, 4))
    colors = plt.get_cmap('hellafresh')
    ax.plot(
        [0, 1],
        [0, 1],
        linestyle='--',
        color='black',
        alpha=0.5,
        label='Perfect Calibration')
    ax.plot(x, y, label='Model Calibration')
    ax.set_xlim([0.1, 0.9])
    ax.set_ylim([0.1, 0.9])
    ax.set_title(f'Calibration Curve ({name})')
    ax.set_xlabel('Predicted Probability')
    ax.set_ylabel('True Probability')
    ax.legend(loc='upper left', framealpha=0.0)
    fig.tight_layout()
    fig.savefig(f"{save_path}/{name}_calibration_curve_holdout.png")
    return

def plot_confusion_matrix(scores, name, save_path):
    """Plot normalized confusion matrix using matplotlib.

    :param np.array scores: confusion matrix scores
    :param str name: model name
    :param str save_path: path to save plot
    :return: None
    :rtype: None
    """
    scores = (scores / scores.sum()).round(3)
    fig, ax = plt.subplots(nrows=1, ncols=1,
                           figsize=(4, 4))
    ax.imshow(scores, cmap='hellafresh')
    ax.set_xticks([0, 1])
    ax.set_yticks([0, 1])
    ax.set_xticklabels(['Positive', 'Negative'])
    ax.set_yticklabels(['Positive', 'Negative'])
    ax.set_xlabel('Predicted Label')
    ax.set_ylabel('True Label')
    for i in [0, 1]:
        for j in [0, 1]:
            ax.text(j, i, scores[i, j],
                    ha='center', va='center',
                    color='xkcd:off white',
                    fontsize=18)
    ax.set_title(f'Confusion Matrix ({name})')
    fig.tight_layout()
    fig.savefig(f"{save_path}/{name}_confusion_matrix.png")
    return

def make_and_save_plots(scores, name, save_path):
    """Make and save plots.

    :param pd.DataFrame scores: scores from model evaluation
    :param str name: model name
    :param str save_path: path to save plot
    :return: None
    :rtype: None
    """
    prob_true, prob_pred, conf_matrix_scores = make_plot_data(scores)
    plot_train_calibration(prob_true, prob_pred, name, save_path)
    plot_confusion_matrix(conf_matrix_scores, name, save_path)
    return


import socket

def principal():

    mi_socket  = socket.socket()
    mi_socket.connect(('127.0.0.1', 9090))

    while True:
        mensaje = input(" mensaje a enviar => ")
        mi_socket.send(mensaje.encode())
        if (mensaje == 'cerrar'):
            break
        recibido = mi_socket.recv(1024)
        print("El servidor dice: " +recibido.decode())

    print("Adios")
    mi_socket.close()

if __name__=='__main__':
    principal()


#Library Project
import random

print("Welcome to the library!")

books = ["Lord of the Rings", "Harry Potter", "The Secret Garden", "Pax"] #this is the default library, you can change it
request = ""

while True:
  #This stuff prints out the current library everytime you do an action
  print("")
  print("Current library: ")
  print(books)
  print("")

  #you should either input take, return, volunteer, destroy or goodbye, there are if and elif messages for each of these cases.
  print("Options: take, return, recommend, volunteer")
  request = input("What do you want to do (say goodbye to leave): ")

  if request.lower() == 'take':
    request = input("What book do you want to take: ")
    #this loop ilterates through the library and checks if the request matches any book
    book_not_there = True #boolean, stays True if the book wasn't in the library, will be useful for the elif statement
    for book in books:
      #case insenstive because of .lower() method
      if book.lower() == request.lower():
        #you can't use request because the request might not match the case, so you use book
        print("Great! I found the book at index " + str(books.index(book)))
        #removes the book from the library
        books.remove(book)
        book_not_there = False #set it to False because it was in the library
      #this elif statement will run if the for loop  is at the last book and it didn't find the book. that way we don't run into errors and print the statement at the right instance
      elif book == books[-1] and book_not_there: #if it's the last book, and it was never to be found
        print("Sorry, I can't find your book")

  elif request.lower() == 'return':
    #when you return a book, it appends a book to the list
    request = input("What book do you want to return: ")
    print("Okay!")
    books.append(request)

  elif request.lower() == 'recommend':
    #avoids an error if the library is empty
    if len(books) == 0:
      print("Oh sorry, the library is currently empty")
    else:
      #chooses a random book to recommend
      recommendation = random.choice(books)
      #finds the index of the book
      index = books.index(recommendation)
      #prints out the index of the book and the book
      print("Thank you for asking!")
      print("I recommend this book: " + recommendation)
      print("It's on index " + str(index))

  elif request.lower() == 'volunteer':
    # when you volunteer, it sorts the list
    print("Oh, thank you so much!")
    books.sort()

  elif request.lower() == 'destroy':
    #destroying the library removes it from the list
    print(";-;")
    books.clear()

  elif request.lower() == 'goodbye':
    print("Goodbye! Thank you for coming to the library")
    break

  else:
    #anything else will get a sorry message
    print("Sorry I didn't get that")


from setuptools import setup

with open("README.md") as file:
    long_description = file.read()

setup(
    name="pg_scrubfu",
    version="0.1.0",
    description="PostgreSQL data obfuscation Kung Fu for DBA's and DevOps Masters written in Python",
    long_description=long_description,
    long_description_content_type="text/x-md",
    classifiers=[
        "Development Status :: 1 - Planning",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3",
        "Operating System :: POSIX :: Linux",
        "Topic :: Software Development",
    ],
    keywords="postgres data obfuscation",
    url="https://github.com/Cyber-Mint/pg_scrubfu",
    author="Bank-Builder",
    author_email="bank-builder@cyber-mint.com",
    license="MIT",
    packages=["scrubfu"],
    install_requires=["Faker",],
    include_package_data=True,
    entry_points={"console_scripts": ["pg_scrubfu=scrubfu.pg_scrubfu:cli"],},
    zip_safe=False,
    python_requires=">=3.6",
)


import torch

from other_methods.other_methods_SIR import euler_SIR, implicit_SIR, RK_SIR
from other_methods.other_methods_Kepler import euler_Kepler, semi_Kepler, implicit_Kepler, RK_Kepler, Verlet_Kepler
from other_methods.other_methods_Volterra_Lotka import euler_VL, implicit_VL, RK_VL

from utils import get_derivatives, get_values_from_pinn, get_derivatives_from_pinn
from PINN import dfdt
from plotting import print_loss, plot_loss, plot_1D, plot_1D_in_2D, plot_3D, plot_compare, plot_difference

def test_SIR(loss, pinn, loss_values, t_domain):
    def get_SIR_sum(S, I, R):
        return S + I + R

    # Result of training
    print_loss(loss, pinn)
    plot_loss(loss_values, name="loss_SIR", save="loss_SIR")
    t = torch.linspace(t_domain[0], t_domain[1], 101).reshape(-1, 1)
    t.requires_grad = True
    plot_1D(pinn, t, name="SIR", labels=["S", "I", "R"], ylabel="Population", save="SIR_PINN")

    h = 0.001

    # Euler
    S_euler, I_euler, R_euler, times = euler_SIR(t_domain[1], h)
    v_euler = get_SIR_sum(S_euler, I_euler, R_euler)

    # Semi-implicit Euler
    # S_semi, I_semi, R_semi, times = semi_SIR(t_domain[1], h)
    # v_semi = get_SIR_sum(S_semi, I_semi, R_semi)

    # Implicit Euler
    S_implicit, I_implicit, R_implicit, times = implicit_SIR(t_domain[1], h)
    v_implicit = get_SIR_sum(S_implicit, I_implicit, R_implicit)

    # RK
    S_RK, I_RK, R_RK, times = RK_SIR(t_domain[1], h)
    v_RK = get_SIR_sum(S_RK, I_RK, R_RK)

    # PINN
    S_pinn, I_pinn, R_pinn = get_values_from_pinn(pinn, times)
    v_pinn = get_SIR_sum(S_pinn, I_pinn, R_pinn)

    # Compare methods
    plot_compare([S_euler, S_implicit, S_RK, S_pinn], times, ["Euler", "Implicit", "RK4", "PINN"], name="Susceptible individuals", ylabel="Susceptible individuals", save="S")
    plot_compare([I_euler, I_implicit, I_RK, I_pinn], times, ["Euler", "Implicit", "RK4", "PINN"], name="Infectious individuals", ylabel="Infectious individuals", save="I")
    plot_compare([R_euler, R_implicit, R_RK, R_pinn], times, ["Euler", "Implicit", "RK4", "PINN"], name="Removed individuals", ylabel="Removed individuals", save="R")
    plot_difference([v_euler, v_implicit, v_RK, v_pinn], times, torch.full_like(times, 1), ["Euler", "Implicit", "RK4", "PINN"], name="Difference in total population", ylabel="Difference", save="Total")

def test_Kepler(loss, pinn, loss_values, t_domain):
    def get_Kepler_energy(X, Y, dX, dY):
        R = (X ** 2 + Y ** 2) ** (1 / 2)
        return (dX ** 2 + dY ** 2) / 2 - 1 / R

    def get_Kepler_moment(X, Y, dX, dY):
        return X * dY - Y * dX

    # Results of training
    print_loss(loss, pinn)
    plot_loss(loss_values, name="loss_Kepler")

    t = torch.linspace(t_domain[0], t_domain[1], 101).reshape(-1, 1)
    t.requires_grad = True

    plot_1D_in_2D(pinn, t, name="Orbit")
    plot_1D(pinn, t, name="Kepler (sins)", labels=["X", "Y"], ylabel="Value")

    h = 0.001

    # Euler
    X_euler, Y_euler, times = euler_Kepler(t_domain[1], h)
    dX_euler = get_derivatives(X_euler, h)
    dY_euler = get_derivatives(Y_euler, h)
    energy_euler = get_Kepler_energy(X_euler, Y_euler, dX_euler, dY_euler)
    momentum_euler = get_Kepler_moment(X_euler, Y_euler, dX_euler, dY_euler)

    # Semi-implicit Euler
    X_semi, Y_semi, times = semi_Kepler(t_domain[1], h)
    dX_semi = get_derivatives(X_semi, h)
    dY_semi = get_derivatives(Y_semi, h)
    energy_semi = get_Kepler_energy(X_semi, Y_semi, dX_semi, dY_semi)
    momentum_semi = get_Kepler_moment(X_semi, Y_semi, dX_semi, dY_semi)

    # Implicit Euler
    X_implicit, Y_implicit, times = implicit_Kepler(t_domain[1], h)
    dX_implicit = get_derivatives(X_implicit, h)
    dY_implicit = get_derivatives(Y_implicit, h)
    energy_implicit = get_Kepler_energy(X_implicit, Y_implicit, dX_implicit, dY_implicit)
    momentum_implicit = get_Kepler_moment(X_implicit, Y_implicit, dX_implicit, dY_implicit)

    # RK
    X_RK, Y_RK, _ = RK_Kepler(t_domain[1], h)
    dX_RK = get_derivatives(X_RK, h)
    dY_RK = get_derivatives(Y_RK, h)
    energy_RK = get_Kepler_energy(X_RK, Y_RK, dX_RK, dY_RK)
    momentum_RK = get_Kepler_moment(X_RK, Y_RK, dX_RK, dY_RK)

    # Verlet
    X_Verlet, Y_Verlet, _ = Verlet_Kepler(t_domain[1], h)
    dX_Verlet = get_derivatives(X_Verlet, h)
    dY_Verlet = get_derivatives(Y_Verlet, h)
    energy_Verlet = get_Kepler_energy(X_Verlet, Y_Verlet, dX_Verlet, dY_Verlet)
    momentum_Verlet = get_Kepler_moment(X_Verlet, Y_Verlet, dX_Verlet, dY_Verlet)

    # PINN
    X_pinn, Y_pinn = get_values_from_pinn(pinn, times)
    dX_pinn = get_derivatives_from_pinn(pinn, times, dfdt, output_value=0)
    dY_pinn = get_derivatives_from_pinn(pinn, times, dfdt, output_value=1)
    energy_pinn = get_Kepler_energy(X_pinn, Y_pinn, dX_pinn, dY_pinn)
    momentum_pinn = get_Kepler_moment(X_pinn, Y_pinn, dX_pinn, dY_pinn)

    # Compare methods
    plot_compare([X_euler, X_semi, X_implicit, X_RK, X_Verlet, X_pinn], times, ["Euler", "Semi", "Implicit", "RK4", "Verlet", "PINN"], name="X coordinate", ylabel="X")
    plot_compare([Y_euler, Y_semi, Y_implicit, Y_RK, Y_Verlet, Y_pinn], times, ["Euler", "Semi", "Implicit", "RK4", "Verlet", "PINN"], name="Y coordinate", ylabel="Y")
    plot_difference([energy_euler, energy_semi, energy_implicit, energy_RK, energy_Verlet, energy_pinn], times, torch.full_like(times, -0.5), ["Euler", "Semi", "Implicit", "RK4", "Verlet", "PINN"], name="Difference in energy", ylabel="Difference")
    plot_difference([momentum_euler, momentum_semi, momentum_implicit, momentum_RK, momentum_Verlet, momentum_pinn], times, torch.full_like(times, 1), ["Euler", "Semi", "Implicit", "RK4", "Verlet", "PINN"], name="Difference in momentum", ylabel="Difference")

def test_VL(loss, pinn, loss_values, t_domain, h=0.001):
    def get_VL_c(X, Y):
        return 2 * torch.log(X) - X + torch.log(Y) - Y

    # Result of training
    print_loss(loss, pinn)
    plot_loss(loss_values, name="loss_VL", save="loss_VL")
    t = torch.linspace(t_domain[0], t_domain[1], 101).reshape(-1, 1)
    t.requires_grad = True
    plot_1D(pinn, t, name="VL", labels=["X", "Y"], ylabel="Population", save="VL_PINN")

    # Euler
    X_euler, Y_euler, times = euler_VL(t_domain[1], h)
    c_euler = get_VL_c(X_euler, Y_euler)

    # Semi-implicit Euler
    # X_semi, Y_semi, times = semi_VL(t_domain[1], h)
    # c_semi = get_VL_c(X, Y)

    # Implicit Euler
    X_implicit, Y_implicit, times = implicit_VL(t_domain[1], h)
    c_implicit = get_VL_c(X_implicit, Y_implicit)

    # RK
    X_RK, Y_RK, times = RK_VL(t_domain[1], h)
    c_RK = get_VL_c(X_RK, Y_RK)

    # PINN
    X_pinn, Y_pinn = get_values_from_pinn(pinn, times)
    c_pinn = get_VL_c(X_pinn, Y_pinn)

    # Compare methods
    plot_compare([X_euler, X_implicit, X_RK, X_pinn], times, ["Euler", "Implicit", "RK4", "PINN"], name="Prey individuals", ylabel="Prey individuals", save="Prey")
    plot_compare([Y_euler, Y_implicit, Y_RK, Y_pinn], times, ["Euler", "Implicit", "RK4", "PINN"], name="Predators individuals", ylabel="Predators individuals", save="Predators")
    plot_difference([c_euler, c_implicit, c_RK, c_pinn], times, torch.full_like(times, -2), ["Euler", "Implicit", "RK4", "PINN"], name="Constant in VL", ylabel="Difference", save="Constant")


# Databricks notebook source
# MAGIC %md ### Setting up configuration file
# MAGIC
# MAGIC Get data path from configuration.py, including Raw, Bronze, Silver data path.

# COMMAND ----------

# MAGIC %run ./config/configuration

# COMMAND ----------

from pyspark.sql.functions import *
from pyspark.sql.types import *

# COMMAND ----------

# MAGIC %md ### Loading SQL StructType schema from JSON file

# COMMAND ----------

tmp = spark.read.format("json").option("multiline", "True").load(rawPath)
import json
json_schema = StructType.fromJson(json.loads(tmp.schema.json()))

# COMMAND ----------

# MAGIC %md ### Ingest Raw Data by AutoLoader and enrich it by adding Metadata
# MAGIC
# MAGIC Adding Metadata, Datasource, Ingest_Time, Status, Ingest_timestamp.

# COMMAND ----------

def autoload_Ingest_Raw(data_source, source_format):
    df = (spark.readStream
                  .format("cloudFiles")
                  .option("cloudFiles.format", source_format)
                  .option("multiline", "True")
                  .schema(json_schema)
                  .load(data_source)
         )

    return df

# COMMAND ----------

raw_df = autoload_Ingest_Raw(rawPath, "json")

# COMMAND ----------

raw_moive_data_df = (
    raw_df.select(
            explode(col("movie")).alias("value"),
            lit("movie.json").alias("datasource"),
            current_timestamp().alias("ingesttime"),
            lit("new").alias("status"),
            current_timestamp().cast("date").alias("p_ingestdate")
    )
)

# COMMAND ----------

streamQuery = (raw_moive_data_df.writeStream
      .format("delta")
      .option("checkpointLocation", bronzeCheckpoint)
      .option("cloudFiles.partitionColumns", "p_ingestdate")
      .outputMode("append")
      .queryName("Raw_To_Bronze")
      .trigger(once = True)
      .start(bronzePath)
)

# COMMAND ----------

# MAGIC %md ### Create Bronze tabe with Data Tab for visualizing the content

# COMMAND ----------

# spark.sql(
#     """
# DROP TABLE IF EXISTS movie_silver
# """
# )
spark.sql(
    f"""
CREATE TABLE IF NOT EXISTS movie_silver
USING DELTA
LOCATION "{bronzePath}"
"""
)

# COMMAND ----------

# MAGIC %sql
# MAGIC SELECT * FROM movie_bronze

# COMMAND ----------


# 숫자 몇개
n = int(input())

words = []
for i in range(n):
    s = input()
    if s not in words:
        words.append(s)

words.sort()
words.sort(key = len)

for i in words:
    print(i)


import json

from utils import *
from cyphers import text_to_words
import cyphers.permutation as perm

SPACER = '   '

def get_banned_bigrams(text):
    words = text_to_words(text)
    alph = set()
    bigrams = set()
    for word in words:
        for char, char_next in zip(word[:-1], word[1:]):
            alph.add(char)
            alph.add(char_next)
            bigrams.add(char + char_next)
    banned = [a + b for a in alph for b in alph if (a + b) not in bigrams]
    banned.sort()
    alph = ''.join(sorted(alph))
    return alph, banned

def get_table(enc, banned, length):
    blocks = []
    for block_idx in range(0, len(enc), length):
        blocks.append(enc[block_idx:block_idx + length])

    table = [[True] * length for _ in range(length)]
    for col_l in range(length):
        for col_r in range(length):
            if col_l == col_r:
                table[col_l][col_r] = False
                continue
            for b in blocks:
                cl, cr = b[col_l], b[col_r]
                if not cl.isalpha() or not cr.isalpha():
                    continue
                bigram = cl + cr
                if bigram in banned:
                    table[col_l][col_r] = False
                    break
            else:
                table[col_l][col_r] = True
    return table

def _get_tree(table, row, k, depth, used: set):
    if depth == k:
        return {}

    if depth == k - 1:
        res = {}
        for col in range(k):
            if table[row][col] and col not in used:
                res[col + 1] = {}
        return res

    res = {}
    for col in range(k):
        if table[row][col] and col not in used:
            used.add(col)
            sub_node = _get_tree(table, col, k, depth + 1, used)
            used.remove(col)
            if sub_node:
                res[col + 1] = sub_node
    return res

def get_tree(table):
    k = len(table)
    col_trues = [[table[row][col] for row in range(k)].count(True) for col in range(k)]
    cols = [idx for idx in range(k)]
    cols.sort(key=lambda col: col_trues[col])

    tree = {start + 1: _get_tree(table, start, k, 1, {start}) for start in cols}
    tree = {key: value for (key, value) in tree.items() if value}
    tree["length"] = k
    return tree

def _brute(node, k, container):
    for vertex in node:
        container.append(int(vertex) - 1)
        if len(container) == k:
            yield container
        else:
            yield from _brute(node[vertex], k, container)
        container.pop()

def brute(enc, tree):
    k = tree["length"]
    del tree["length"]

    f = get_file_write("bruted.txt")
    for key in _brute(tree, k, []):
        print(perm.str_key(key) + '\r', end='')
        dec = perm.decrypt(enc, key)
        f.write(perm.str_key(key) + '\n')
        f.write(dec + '\n\n')
    f.close()

def main():
    if op == 'bi':
        text = read(argv[2]).lower()
        alph, banned = get_banned_bigrams(text)
        write('alph.txt', alph)
        write('banned.txt', '\n'.join(banned))
    elif op == 'gen':
        perm.exec_gen_mono_key()
    elif op == 'enc':
        perm.exec_encrypt()
    elif op == 'dec':
        perm.exec_decrypt()
    elif op == 'table':
        enc = read(argv[2]).lower()
        banned = read(argv[3]).split('\n')
        length = int(argv[4])
        table = get_table(enc, banned, length)
        write('table.txt', '\n'.join(map(lambda x: ' '.join(map(lambda el: str(int(el)), x)), table)))
    elif op == 'tree':
        table = read(argv[2]).split('\n')
        for idx, row in enumerate(table):
            table[idx] = list(map(lambda x: bool(int(x)), row.split(' ')))
        tree = get_tree(table)
        write('tree.txt', json.dumps(tree, indent=4))
    elif op == 'brute':
        enc = read(argv[2])
        tree = json.loads(read(argv[3]))
        brute(enc, tree)
    else:
        print_wrong_op()

if __name__ == '__main__':
    main()


# coding:utf-8
import requests
import json
import sys

query_string = sys.argv[1]
headers = {"User-Agent":"Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1"}
data = {
    "query": query_string,
    "from": "zh",
    "to": "en",
}
post_url = "http://fanyi.baidu.com/basetrans"

response = requests.post(post_url,data=data,headers=headers)
# print(response.content.decode())
ret_dict = json.loads(response.content.decode())
ret = ret_dict["trans"][0]["dst"]
print("result is:",ret)


TOGET = 1
GOT = 5
            # INEFFECTIVE = 10
            # UNUSE = 15
EXPIRE = 20
USING = 25
USEFAILED = 30
USED = 35

status_str = {
TOGET: '去领取',
GOT: '已领取',
                # INEFFECTIVE: '待生效',  # 前端动态显示
                # UNUSE:  '去使用',
EXPIRE: '已失效',
USING: '使用中',
USEFAILED: '重新使用',  # 等效于未使用
USED: '使用成功',

    # PENDING: '未提交',
    # APPROVING: '审核中',
    # APPROVED: '审核通过',
    # REJECTED: '审核拒绝',
    # CANCELLED: '已取消',
    # SIGNING: '签约中',
    # SIGN_FAILED: '签约失败',
    # FUNDING: '放款中',
    # FUND_ERROR: '放款失败',
    # FUNDED: '待还款',
    # REPAYING: '还款中',
    # REPAID: '已还清'
}


## GNNの実装 # パラメータの平均をとる
import torch
import torch.nn as nn

from torch_geometric.datasets import Planetoid
from torch_geometric.datasets import KarateClub
import torch.nn.functional as F
from torch_geometric.nn import GCNConv
from param_mean_graph_div import GraphParatitionMetis
# from sugar_graph_div import GraphParatitionMetis
# from my_graph_div import GraphParatitionMetis
import numpy as np
import sys
import time
import statistics
import pandas as pd
import matplotlib.pyplot as plt

def check_graph(data):
    '''グラフ情報を表示'''
    print("グラフ構造:", data)
    print("グラフのキー: ", data.keys)
    print("ノード数:", data.num_nodes)
    print("エッジ数:", data.num_edges)
    print("ノードの特徴量数:", data.num_node_features)
    print("孤立したノードの有無:", data.contains_isolated_nodes())
    print("自己ループの有無:", data.contains_self_loops())
    print("====== ノードの特徴量:x ======")
    print(data['x'])
    print("====== ノードのクラス:y ======")
    print(data['y'])
    print("========= エッジ形状 =========")
    print(data['edge_index'])

class GCN(torch.nn.Module):
    def __init__(self):
        super(GCN, self).__init__()
        hidden_size = 15
        self.conv1 = GCNConv(dataset.num_node_features, hidden_size)
        self.conv2 = GCNConv(hidden_size, dataset.num_classes)

    def forward(self, data):
        x, edge_index = data.x, data.edge_index
        x = self.conv1(x, edge_index)
        x = F.relu(x)
        x = F.dropout(x, training=self.training)
        x = self.conv2(x, edge_index)

        return F.log_softmax(x, dim=1)

def test(data_list):
    # グラフの個数
    graph_num = len(data_list)

    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

    # model.train() #モデルを訓練モードにする。
    total_time = 0
    model_list = [GCN() for _ in range(graph_num)]
    optimizer_list = []
    for i in range(graph_num):
        data_list[i] = data_list[i].to(device)
        model_list[i] = model_list[i].to(device)
        model_list[i].train() #モデルを訓練モードにする。
        optimizer_list.append(torch.optim.Adam(model_list[i].parameters(), lr=0.01))

    loss_lists = [[] for _ in range(graph_num)]
    for epoch in range(400):
        if epoch < 400:
            for i in range(1, graph_num):
                model_list[0].conv1.lin.weight.data.add_(model_list[i].conv1.lin.weight.data)
            model_list[0].conv1.lin.weight.data.mul_(float(1.0) / graph_num)
            for i in range(1, graph_num):
                model_list[i].conv1.lin.weight.data = torch.clone(model_list[0].conv1.lin.weight.data)

            for i in range(1, graph_num):
                model_list[0].conv2.lin.weight.data.add_(model_list[i].conv2.lin.weight.data)
            model_list[0].conv2.lin.weight.data.mul_(float(1) / graph_num)
            for i in range(1, graph_num):
                model_list[i].conv2.lin.weight.data = torch.clone(model_list[0].conv2.lin.weight.data)

            for i in range(1, graph_num):
                model_list[0].conv1.bias.data.add_(model_list[i].conv1.bias.data)
            model_list[0].conv1.bias.data.mul_(float(1) / graph_num)
            for i in range(1, graph_num):
                model_list[i].conv1.bias.data = torch.clone(model_list[0].conv1.bias.data)

            for i in range(1, graph_num):
                model_list[0].conv2.bias.data.add_(model_list[i].conv2.bias.data)
            model_list[0].conv2.bias.data.mul_(float(1) / graph_num)
            for i in range(1, graph_num):
                model_list[i].conv2.bias.data = torch.clone(model_list[0].conv2.bias.data)

        for i in range(graph_num):
            for _ in range(100):
                time_sta = time.time()
                optimizer_list[i].zero_grad()
                out = model_list[i](data_list[i])
                yt = data_list[i].y.type(torch.LongTensor).to(device)
                loss = F.nll_loss(out[data_list[i].train_mask], yt[data_list[i].train_mask])
                loss_lists[i].append(loss.tolist())
                loss.backward()
                optimizer_list[i].step()
                time_end = time.time()
                total_time += time_end - time_sta
    # loss値の推移を保存
    # loss値の推移を保存
    # for i in range(graph_num):
    #     with open(f'experiment_data/loss_data/param_mean1/cora/fd_loss_graph_{graph_num}_{i+1}.txt', 'w') as f:
    #         for loss in loss_lists[i]:
    #             f.write(f"{loss}\n")

    acc_list = []
    for i in range(graph_num):
        model_list[i].eval() #モデルを評価モードにする。
        _, pred = model_list[i](data_list[i]).max(dim=1)
        correct = float(pred[data_list[i].test_mask].eq(data_list[i].y[data_list[i].test_mask]).sum().item())
        acc = correct / data_list[i].test_mask.sum().item()
        acc_list.append(acc)

    # correct_num = 0
    # for i in range(len(data_item['y'])):
    #     if pred[i] == data_item['y'][i]: correct_num += 1
    # acc = float(correct_num) / len(data_item['y'])
    print(total_time*1.25)
    return acc_list, total_time

from torch_geometric.datasets import Planetoid
from torch_geometric.datasets import NELL

torch.autograd.set_detect_anomaly(True)

dataset = Planetoid(root='/tmp/Cora', name="Cora")
data = dataset[0]
gpart = GraphParatitionMetis()
pair_distant_list = []
mean_acc_list = []
time_list = []
total_time = 0
for i in range(10):

    print(f"------------------{i+1}回目------------------")
    _, data_list, nodes_parts = gpart.graph_partition(data, 2)
    # pair_table = [[0] * 7 for _ in range(7)]
    # y1 = data_list[0].y.tolist()
    # y2 = data_list[1].y.tolist()
    # if len(y1) != len(y2): continue
    # for j in range(len(y1)):
    #     pair_table[int(y1[j])][int(y2[j])] += 1
    #     if int(y1[j])!=int(y2[j]):
    #         pair_distant += 1
    # print(pair_distant)

    accuracies, time_part = test(data_list)
    total_time += time_part
    l = []
    for acc in accuracies:
        l.append(acc)
    print(accuracies)
    mean_acc = statistics.mean(l)
    # pair_distant_list.append(pair_distant)
    mean_acc_list.append(mean_acc)
    print(mean_acc)
    print()

print(sum(mean_acc_list)/10)
print(total_time/8)
#     exp_data = pd.DataFrame({'nodes_part1': nodes_parts[0],
#                             'y1': data_list[0].y.tolist(),
#                             'nodes_part2': nodes_parts[1],
#                             'y2': data_list[1].y.tolist()})
#     exp_data.to_excel(f"experiment_data/acc_data/acc_{mean_acc}.xlsx")
#     pair_data = pd.DataFrame(pair_table)
#     pair_data.to_csv(f"experiment_data/pair_data/acc_{mean_acc}.csv")
# df = pd.DataFrame({"精度": mean_acc_list}, index=pair_distant_list)
# df.to_csv('test.csv')
# print(df)
# plt.figure()
# df.plot()
# plt.savefig('experiment_data/pair_data/pair_distant.png')
# plt.close('all')
    # data_dic = {}
    # for i in [2]:
    #     for k in range(1, i+1):
    #         # dic_name = "experiment_data/loss_data/param_mean1/citeseer/"
    #         dic_name = "experiment_data/loss_data/param_mean1/cora/"
    #         filename = f"fd_loss_graph_{i}_{k}"
    #         path = dic_name + filename + ".txt"
    #         with open(path, 'r') as f:
    #             data = f.read().splitlines()
    #             data = [float(x) for x in data]
    #         data_dic[filename] = data

    # table = pd.DataFrame(index=range(1, 401), data=data_dic)
    # plt.figure()
    # table.plot()
    # plt.savefig('experiment_data/loss_data/param_mean1/loss_fig_citeseer.png')
    # plt.close('all')


import argparse
import pysam
import re

###### arguments ######
parser = argparse.ArgumentParser()
parser.add_argument('-b','--bam', metavar='File',dest='bam',help='Input file',required=True)
parser.add_argument('-f','--fasta', metavar='File',dest='fasta_file',help='Input file',type=open,required=True)
parser.add_argument('-o','--Output',metavar='File',dest='output',help='Output file',required=True)
args = parser.parse_args()
###### arguments ######

# IF YOU HAVE ANY QUESTIONS ABOUT THE SCRIPTS
# PLEASE FEEL FREE TO CONTACT WITH THE AUTHOR
# E-MAIL: zihua.liu666@gmail.com
# HOPE YOU CAN ENJOY THIS TOY!

def product_list(fasta_file):
    aDict={}
    for line in fasta_file:
        if line[0]=='>':
            key=line.strip().split()[0][1::]
            aDict[key]=[]
        else:
            aDict.setdefault(key,[]).append(line.strip())

    long_string_Dict = {}
    for k in aDict.keys():
        value = ''.join(list(aDict[k]))
        long_string_Dict[k] = value
    print('Compile reference fasta file completed!')
    return long_string_Dict

################################################################################################

def order_inser(cigar):
    order_event = [int(i) for i in re.findall("\d+", cigar)]
    all_M = order_event[0:100:2]
    all_event = order_event[1:100:2]
    # print(order_I, all_M, all_I)
    i = 0
    order_insertion = []
    while i < len(all_event):
        order_insertion.append((sum(all_M[0:i + 1]), all_event[i]))
        i += 1
    return order_insertion
        # print(order_insertion)

def deduction_D_I(cigar):
    # cigar = '2M1D2M1I2M'
    if cigar.find('I') > cigar.find('D'):
        order_I = [int(i) for i in re.findall("\d+", cigar.split('I')[0])]
        order_D = [int(i) for i in re.findall("\d+", cigar.split('D')[1])]
        newI = str(sum(order_I[0:-1])) + 'M' + str(order_I[-1]) + 'I' + cigar.split('I')[1]
        newD = cigar.split('D')[0] + 'D' + str(sum(order_D)) + 'M'
        #print(newD, newI)
        return newI, newD
    else:
        order_D = [int(i) for i in re.findall("\d+", cigar.split('D')[0])]
        order_I = [int(i) for i in re.findall("\d+", cigar.split('I')[1])]
        newD = str(sum(order_D[0:-1])) + 'M' + str(order_D[-1]) + 'D' + cigar.split('D')[1]
        newI = cigar.split('I')[0] + 'I' + str(sum(order_I)) + 'M'
        #print(newD, newI)
        return newI, newD

def add_N(ori_sequence, pos_info):
    new_sequence = ''
    pos_info.insert(0, (0, 0))
    i = 0
    while i < len(pos_info) - 1:
        new_sequence += ori_sequence[pos_info[i][0]:pos_info[i + 1][0]] + pos_info[i + 1][1] * 'N'
        i += 1
    new_sequence += ori_sequence[pos_info[-1][0]::]
    # print(new_sequence)
    return new_sequence

def trans_query_reference_by_cigar(query, reference, cigar):
    # I or D?
    query_I = [i.start() - 1 for i in re.finditer('I', cigar)]
    query_D = [i.start() - 1 for i in re.finditer('D', cigar)]

    order_insertion = order_inser(cigar)

    if query_D == []:
        new_reference = add_N(reference, order_insertion)
        #print(query, new_reference)
        return query, new_reference
        # print(new_sequence)
    elif query_I == []:
        new_query = add_N(query, order_insertion)
        #print(new_query, reference)
        return new_query, reference
    else:
        newIcigar, newDcigar = deduction_D_I(cigar)
        newI_oi = order_inser(newIcigar)
        newD_oi = order_inser(newDcigar)
        new_query = add_N(query, newD_oi)
        new_reference = add_N(reference, newI_oi)
        #print(new_query, new_reference)
        return new_query, new_reference

################################################################################################

def readbam(bam_file, fasta_file, wfile):

    genomeDict = product_list(fasta_file)
    #print(genomeDict['chr10'][3244897:3244897+153])

    bamfile = pysam.AlignmentFile(bam_file,"rb")
    ofile = pysam.AlignmentFile(wfile, "w", template=bamfile)

    for r in bamfile:
        query = r.seq
        reference = genomeDict[r.reference_name][r.pos:r.pos+len(query)+2]
        reference = reference.upper()
        #print(reference)
        #print(r.cigarstring)
        # THIS SCRIPT HAS NO SENSITIVITY FOR DELETION OR INSERTION CONDITIONS
        if 'I' in r.cigarstring or 'D' in r.cigarstring:
            new_query, new_reference = trans_query_reference_by_cigar(query, reference, r.cigarstring)
            #if r.cigarstring == '81M4I65M':
                #print(new_query)
                #print(new_reference)
            #if discard_TH_and_DA(new_query, new_reference) == 1:
            if discard_TH_and_DA(new_query, new_reference) != 1:
                ofile.write(r)
            #continue
        else:
            #if discard_TH_and_DA(query, reference) == 1:
            if discard_TH_and_DA(query, reference) != 1:
                ofile.write(r)
    print('Congratulations! You can move to the next steps now!')

def discard_TH_and_DA(query, reference):
    # H represents A/C/T NOT G
    query_T = [i.start() for i in re.finditer('T', query)]
    reference_C = [j.start() for j in re.finditer('C', reference)]
    # D represents A/G/T NOT C
    query_A = [i.start() for i in re.finditer('A', query)]

    # Position overlapping
    plus_T = set(query_T).intersection(set(reference_C))
    base_behind_plus_T = [query[i+1] for i in plus_T if i+1 < len(query) and len(plus_T) >= 3]
    #print(base_behind_plus_T)
    plus_A = set(query_A).intersection(set(reference_C))
    base_behind_plus_A = [query[i - 1] for i in plus_A if i > 0 and len(plus_A) >= 3]

    judge_T = len(base_behind_plus_T) - base_behind_plus_T.count('G')
    judge_A = len(base_behind_plus_A) - base_behind_plus_A.count('C')

    if judge_T >=3 or judge_A >=3: return 1
    else: return 0

readbam(bam_file = args.bam, fasta_file=args.fasta_file, wfile=args.output)


from voluptuous import Msg, Optional, Required

from lava_common.schemas import boot

def schema():
    base = {
        Required("method"): Msg("bootloader", "'method' should be 'bootloader'"),
        Required("bootloader"): str,
        Required("commands"): [str],
        Optional("use_bootscript"): bool,
        Optional("prompts"): boot.prompts(),
    }
    return {**boot.schema(), **base}


# Python program for implementation of SelectionSort

from plots import plot

def selection_sort(arr, type_plot):

    # Run through all data elements
    for i in range(len(arr)):
        # Find the minimum element
        min_idx = i
        for j in range(i + 1, len(arr)):
            if arr[min_idx] > arr[j]:
                min_idx = j

        # Swap the found minimum element with
        # the first element
        arr[i], arr[min_idx] = arr[min_idx], arr[i]

        # Created typ with selected plot type
        plot(arr=arr, fallow_point=min_idx, type_plot=type_plot, title='Selection Sort')


for tc in range(1, int(input()) + 1):
    N, M = map(int, input().split())
    visit = [0] * 1000001
    Q = [(N, 0)]
    i = 0
    visit[N] = 1
    idx = 0
    while True:
        x = Q[idx]
        idx += 1
        i = x[1] + 1
        if x[0]*2 == M or x[0] + 1 == M or x[0]-10 == M or x[0] - 1 == M:
            break
        if x[0] < M:
            if visit[x[0] * 2] == 0 and x[0] * 2 < 1000001:
                Q.append((x[0] * 2, i))
                visit[x[0] * 2] = 1

            if visit[x[0] + 1] == 0 and x[0] + 1 < 1000001:
                Q.append((x[0] + 1, i))
                visit[x[0] + 1] = 1
        if visit[x[0]-10] == 0 and 0 < x[0]-10:
            Q.append((x[0]-10, i))
            visit[x[0]-10] = 1

        if visit[x[0] - 1] == 0 and 0 < x[0] - 1:
            Q.append((x[0] - 1, i))
            visit[x[0] - 1] = 1
    print('#{} {}'.format(tc, i))

from collections import deque

def bfs():
    queue = deque()
    queue.append(N)

    ans = 0
    while queue:
        size = len(queue)

        for i in range(size):
            curr = queue.popleft()
            if curr == M: return ans
            for j in (curr + 1, curr - 1, curr * 2, curr - 10):
                if 0 < j <= 1000000 and memo[j] == -1:
                    memo[j] = 1
                    queue.append(j)
        ans += 1

for tc in range(1, int(input()) + 1):
    N, M = map(int, input().split())
    memo = [-1] * 1000001
    print("#{} {}".format(tc, bfs()))
########################################

#2번
def calc(num, idx):
    if idx == 0:
        return num + 1
    elif idx == 1:
        return num - 1
    elif idx == 2:
        return num * 2
    else:
        return num - 10

def bfs():
    queue = [0] * 1000000
    front = rear = -1
    rear += 1
    queue[rear] = N
    while front != rear:
        front += 1
        curr_N = queue[front]
        if curr_N == M:
            return
        for i in range(4):
            next_N = calc(curr_N, i)
            if 0 < next_N <= 1000000 and memo[next_N] == -1:
                memo[next_N] = memo[curr_N]+1
                rear += 1
                queue[rear] = next_N

for tc in range(1, int(input()) + 1):
    N, M = map(int, input().split())
    memo = [-1] * 1000001
    memo[N] = 0
    bfs()
    print("#{} {}".format(tc, memo[M]))
#####################################################

###########################################################
#1번
def calc(num, idx):
    if idx == 0:
        return num + 1
    elif idx == 1:
        return num - 1
    elif idx == 2:
        return num * 2
    else:
        return num - 10

def bfs():
    queue = [0] * 1000000
    front = rear = -1
    rear += 1
    queue[rear] = (N, 0)
    while front != rear:
        front += 1
        curr_N, curr_cnt = queue[front]
        if curr_N == M:
            return curr_cnt
        for i in range(4):
            next_N = calc(curr_N, i)
            if 0 < next_N <= 1000000:
                rear += 1
                queue[rear] = (next_N, curr_cnt + 1)

for tc in range(1, int(input()) + 1):
    N, M = map(int, input().split())

    print("#{} {}".format(tc,bfs()))


from brownie import accounts, network, interface, config, Contract
# from brownie import SafeMoon
from brownie import DefectiveContract
from brownie._config import CONFIG
from brownie.network.web3 import web3
from brownie.network.state import Chain
import random

# simulate the attack https://etherscan.io/tx/0xcd7dae143a4c0223349c16237ce4cd7696b1638d116a72755231ede872ab70fc
# without the flashloan part

def main():
    num = 10
    # Environment Setup
    network.disconnect('mainnet-fork')
    # CONFIG.networks['mainnet-fork']['cmd_settings']['fork'] = 'https://mainnet.infura.io/v3/cf64e9aa7e5047a8afd17394a21ac158@12955062'
    CONFIG.networks['mainnet-fork']['cmd_settings']['fork'] = 'https://eth-mainnet.alchemyapi.io/v2/8sIinwGOjt4xg880x4o8T0YyNEctOPkT@12955062'

    CONFIG.networks['mainnet-fork']['explorer'] = 'https://api.etherscan.io/api'
    network.connect('mainnet-fork')
    # print(web3.eth.blockNumber)
    # print(network.show_active())
    # print(CONFIG.networks['mainnet-fork'])

    # UniswapV2Router02 = interface.IUniswapV2Router02('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D')
    # print("test")
    # WETH = interface.IERC20('0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2')
    # print('the balance is: ' + str(WETH.totalSupply()))

    # Deployment
    # safemoon = SafeMoon.deploy({'from': accounts[0]})
    safemoon = DefectiveContract.deploy({'from': accounts[0]})
    # print(safemoon.totalSupply())

    initialSetup(safemoon)
    # test1(safemoon)
    # test2(safemoon)
    # # test3(safemoon)
    # test4(safemoon)

    # functionList = [test1,test2,test4]
    #functionList = [simulateTransfer, simulateBuy, simulateSell]
    # random.choice(functionList)(safemoon)
    #randomChooseMultiFunctions(functionList,safemoon,num)

    # chain = Chain()

def randomChooseMultiFunctions(functionList, deployment, num):
    for _ in range(num):
        random.choice(functionList)(deployment)

def initialSetup(safemoon):
    # Add liquidity
    print('Initializing...')
    uniswapV2Router02 = interface.IUniswapV2Router02('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D')
    safemoon.approve(uniswapV2Router02.address, 1e12, {'from': accounts[0]})
    uniswapV2Router02.addLiquidityETH(safemoon.address, 1e12, 0, 0, accounts[0], 9999999999, {'from': accounts[0], 'amount': 1e18})

    # Set initial balances
    safemoon.transfer(accounts[1], 1e13, {'from': accounts[0]})
    safemoon.transfer(accounts[2], 1e13, {'from': accounts[0]})
    safemoon.transfer(accounts[3], 1e13, {'from': accounts[0]})
    print('Finished initialization.')

# total supply should be less than total supply before
def test1(safemoon):
    print("check total supply should be less than total supply before")
    tokensToSend = 2000
    tokensToReceive = tokensToSend * 90 / 100
    account1 = accounts[1]
    account2 = accounts[2]
    account3 = accounts[3]
    balance1Before = safemoon.balanceOf(account1)
    balance2Before = safemoon.balanceOf(account2)
    balance3Before = safemoon.balanceOf(account3)
    totalSupplyBefore = balance1Before + balance2Before + balance3Before
    safemoon.approve(account2, tokensToSend, {'from': accounts[1]})
    safemoon.transfer(account2, tokensToSend, {'from': accounts[1]})
    balance1After= safemoon.balanceOf(account1)
    balance2After = safemoon.balanceOf(account2)
    balance3After = safemoon.balanceOf(account3)
    totalSupplyAfter = balance1After + balance2After + balance3After
    diff1 = balance1After + tokensToSend - balance1Before
    diff2 = balance2After - tokensToReceive - balance2Before
    # diff3 = balance3After - balance3Before
    # print(balance1After,balance2After,balance3After)
    # ratio1 = balance1After / diff1
    # ratio2 = balance2After / diff2
    # ratio3 = balance3After / diff3
    # print(ratio1,ratio2)
    # assert(ratio3 == ratio2)
    assert(totalSupplyAfter < totalSupplyBefore)

# should transfer tokens correctly while one of accounts is excluded
def test2(safemoon):
    print("check should transfer tokens correctly while one of accounts is excluded")
    tokensToSend = 2000
    tokensToReceive = tokensToSend * 90 / 100
    account1 = accounts[1]
    account2 = accounts[2]
    account3 = accounts[3]
    safemoon.excludeFromReward(account1, {'from': accounts[0]})
    balance1Before = safemoon.balanceOf(account1)
    balance2Before = safemoon.balanceOf(account2)
    balance3Before = safemoon.balanceOf(account3)
    totalSupplyBefore = balance1Before + balance2Before + balance3Before
    safemoon.approve(account2, tokensToSend, {'from': accounts[1]})
    safemoon.transfer(account2, tokensToSend, {'from': accounts[1]})
    balance1After= safemoon.balanceOf(account1)
    balance2After = safemoon.balanceOf(account2)
    balance3After = safemoon.balanceOf(account3)
    totalSupplyAfter = balance1After + balance2After + balance3After
    diff1 = balance1After + tokensToSend - balance1Before
    diff2 = balance2After - tokensToReceive - balance2Before
    # diff3 = balance3After - balance3Before
    # print(balance1After,balance2After,balance3After)
    # ratio1 = balance1After / diff1
    # ratio2 = balance2After / diff2
    # ratio3 = balance3After / diff3
    # print(ratio1,ratio2)
    # assert(ratio3 == ratio2)
    assert(totalSupplyAfter < totalSupplyBefore)

# should stop burning tokens as soon as the total amount reaches 1% of the initial
# Note: only when the safemoon fork has burn() function/interface
def test3(safemoon):
    account1 = accounts[1]
    account2 = accounts[2]
    account3 = accounts[3]
    safemoon.burn(1000000, {'from': accounts[1]})
    safemoon.burn(100000000, {'from': accounts[3]})
    balanceBeforeBurn = safemoon.balanceOf(account2)
    assert(balanceBefore == 2200000)

    safemoon.burn(balanceBeforeBurn-2100000, {'from': accounts[2]})
    balanceAfterBurn = safemoon.balanceOf(account2)
    totalSupplyBeforeSend = safemoon.totalSupply()
    safemoon.transfer(account1, 1000, {'from': account2})
    totalSupplyAfterSend = safemoon.totalSupply()
    assert(totalSupplyAfterSend == totalSupplyBeforeSend)

    balance1 = safemoon.balanceOf(account1)
    balance2 = safemoon.balanceOf(account2)
    assert(balanceAfterBurn == (balance1+balance2+1))

# 'Exclude / Include address'
def test4(safemoon):
    print("check exclude / include address")
    account4 = accounts[4]
    safemoon.excludeFromReward(account4)
    assert(safemoon.isExcludedFromReward(account4) == True), "test1"

    safemoon.includeInReward(account4)
    assert(safemoon.isExcludedFromReward(account4) == False), "test2"

    safemoon.excludeFromFee(account4)
    assert(safemoon.isExcludedFromFee(account4) == True), "test3"

    safemoon.includeInFee(account4)
    assert(safemoon.isExcludedFromFee(account4) == False), "test4"

# Simulate a transfer with random sender, recipient and amount.
def simulateTransfer(safemoon):
    print("Simulate transfer")

    iAccountList = range(4)
    iSender = random.choice(iAccountList)
    iRecipient = random.choice([i for i in iAccountList if i != iSender])
    sender = accounts[iSender]
    recipient = accounts[iRecipient]

    print("account {} balance: {}".format(iSender, sender.balance()))

    balanceOfSender = safemoon.balanceOf(sender)
    if balanceOfSender == 0:
        return
    amount = random.randint(1, balanceOfSender)

    safemoon.transfer(recipient, amount, {'from': sender})
    print("{} sent {} to {}".format(sender, amount, recipient))

# Simulate a buy with random buyer and amount using Uniswap.
def simulateBuy(safemoon):
    print("Simulate buy")
    wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
    uniswapV2Router02 = interface.IUniswapV2Router02('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D')

    buyer = accounts[random.choice(range(1, 4))]
    balanceOfBuyer = buyer.balance()
    if balanceOfBuyer == 0:
        return
    amount = random.randint(1, int(balanceOfBuyer/100))

    print('{} is buying the token with {} wei.'. format(buyer, amount))
    uniswapV2Router02.swapExactETHForTokens(0, [wethAddress, safemoon.address], buyer, 9999999999, {'from': buyer, 'amount': amount})

# Simulate a sell with random seller and amount using Uniswap.
def simulateSell(safemoon):
    print("Simulate sell")
    wethAddress = '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2'
    uniswapV2Router02 = interface.IUniswapV2Router02('0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D')

    seller = accounts[random.choice(range(1, 4))]
    balanceOfSeller = safemoon.balanceOf(seller)
    if balanceOfSeller == 0:
        return
    amount = random.randint(1, min(int(balanceOfSeller/100), safemoon._maxTxAmount()))

    print('{} is selling {} token for WETH.'. format(seller, amount))
    safemoon.approve(uniswapV2Router02.address, amount, {'from': seller})
    uniswapV2Router02.swapExactTokensForETHSupportingFeeOnTransferTokens(amount, 0, [safemoon.address, wethAddress], seller, 9999999999, {'from': seller})


#!/usr/bin/env python3
import socket
import string
import re
from multiprocessing.pool import ThreadPool

charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ '

def attempt(tag, payload, block_number=0):
    s = socket.socket()
    s.connect(('2018shell2.picoctf.com', 30399))

    # Assert length
    '''
    message = """Agent,
Greetings. My situation report is as follows:
{0}
My agent identifying code is: """.format(payload)
    assert (len(message) - (block_number + 1) * 16) <= 1, len(message)
    # print(payload)
    '''

    # retrieve char
    while True:
        data = s.recv(4096).decode().strip()
        if not data:
            continue
        #print("Received >>", data)

        if 'Welcome, Agent 006!' in data:
            pass
        elif 'Please enter your situation report:' in data:
            s.send(payload.encode())
            s.send(b'\n')
        else:
            return (tag, data[block_number * 32 : block_number * 32 + 32])

def main(progress='', block_number=0):
    # My agent identifying code is:
    block = 'A' * 16
    assert len(block) == 16

    for skip in range(16):
        # padding to round to nearest block
        # 96 bytes rounded up from 84 bytes provided
        padding = "x" * (96-53-31)
        prefix = padding + block[skip+1:]

        # Enter 15 characters and retrieve the first 16 encoded
        _, aim = attempt('', prefix, block_number)

        pool = ThreadPool(processes=25)
        async_results = []

        # Then enter 16 characters changing the last one until you get the
        # same result as with 15 characters for the first 16 encoded bytes
        for ch in charset:
            # dummy to duplicate the uncontrolled blocks
            # 96 bytes rounded up from 84 bytes provided
            dummy = '\nMy agent identifying code is: '.replace('\n', 'n') # server can't receive newline
            payload = prefix + dummy + progress + ch

            async_result = pool.apply_async(attempt, (ch, payload, block_number))
            async_results.append(async_result)

        # That 16th character is the first character of your secret.
        # You can then repeat the process by putting 14 characters and then
        # finding the second secret characters with the same thechnique.
        for async_result in async_results:
            ch, result = async_result.get()
            print(f"Result: {ch}, {result} == {aim}")

            if result == aim:
                progress += ch
                if ch == '}':
                    # end of flag! if we continue we
                    # merely get '0's added forever
                    print(f"Success! {progress}")
                    quit()
                break

        print(f"Progress (Block {block_number} of index {skip}): {progress}")

    # continue to next block
    main(progress, block_number + 1)

if __name__ == '__main__':
    # 96 bytes rounded up from 84 bytes provided
    # so we mask out the first 6 blocks
    main(block_number=6)


import pickle
import random
from collections import defaultdict as dd

from keras.layers.core import Dense, Layer, Lambda,Activation
from keras.layers.core import initializations, activations
from keras.layers.embeddings import Embedding
from keras.models import Graph, Sequential
from theano import tensor as T
from keras import backend as K
import logging

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

data = pickle.load(open("../data/person_pub_data.pkl", "rb"))
sorted_names = pickle.load(open("sorted_names.pkl", "rb"))
name_to_idx = pickle.load(open("name_to_idx.pkl", "rb"))

title_df = dd(int)
venue_df = dd(int)
aff_df = dd(int)

class NodeContextProduct(Layer):
    '''
        This layer turns a pair of words (a pivot word + a context word,
        ie. a word from the same context, or a random, out-of-context word),
        indentified by their index in a vocabulary, into two dense reprensentations
        (word representation and context representation).
        Then it returns activation(dot(pivot_embedding, context_embedding)),
        which can be trained to encode the probability
        of finding the context word in the context of the pivot word
        (or reciprocally depending on your training procedure).
        The layer ingests integer tensors of shape:
        (nb_samples, 2)
        and outputs a float tensor of shape
        (nb_samples, 1)
        The 2nd dimension encodes (pivot, context).
        input_dim is the size of the vocabulary.
        For more context, see Mikolov et al.:
            Efficient Estimation of Word reprensentations in Vector Space
            http://arxiv.org/pdf/1301.3781v3.pdf
    '''

    def __init__(self, input_dim, proj_dim=128,
                 init='uniform', activation='sigmoid', weights=None):
        super(NodeContextProduct, self).__init__()
        self.input_dim = input_dim
        self.proj_dim = proj_dim
        self.init = initializations.get(init)
        self.activation = activations.get(activation)

        self.input = T.imatrix()
        # two different embeddings for pivot word and its context
        # because p(w|c) != p(c|w)
        self.W_w = self.init((input_dim, proj_dim))
        self.W_c = self.init((input_dim, proj_dim))

        self.params = [self.W_w, self.W_c]

        if weights is not None:
            self.set_weights(weights)

    def get_output(self, train=False):
        X = self.get_input(train)
        w = self.W_w[X[:, 0]]  # nb_samples, proj_dim
        c = self.W_c[X[:, 1]]  # nb_samples, proj_dim

        dot = T.sum(w * c, axis=1)
        dot = T.reshape(dot, (X.shape[0], 1))
        return self.activation(dot)

    def get_config(self):
        return {
            "name": self.__class__.__name__,
            "input_dim": self.input_dim,
            "proj_dim": self.proj_dim,
            "init": self.init.__name__,
            "activation": self.activation.__name__}

class IntInput(Layer):
    def build(self):
        super(IntInput, self).build()
        self.input = K.placeholder(self._input_shape, dtype='int32')

"""
num_node: number of entity node to be embedded
node_attr_mapping: attributes of each node type
attr_shape: original dimension of each attribute
embedding_dim: dimension of the embedding space
"""
def build_network(num_node, path_type, node_attr_mapping, attr_shape, embedding_dim=100):
    node_type_idx = {}
    attr_type_idx = {}
    num_node_type = 0
    num_attr_type = 0
    for n in node_attr_mapping:
        node_type_idx[n] = num_node_type
        num_node_type += 1
        for a in node_attr_mapping[n]:
            attr_type_idx[a] = num_attr_type
            num_attr_type += 1

    output_loss = []

    model = Graph()

    for i, n in enumerate(path_type):
        for leg in ["left", "right"]:
            model.add_input(name=leg + '_vertex_' + str(i), input_shape=(1,), dtype='int32')
    # shared embedding
    model.add_shared_node(layer=Embedding(input_dim=num_node, output_dim=embedding_dim, input_length=1),
                          name="embedding_pivot",
                          inputs=[(leg + '_vertex_0') for leg in ('left', 'right')],
                          outputs=[(leg + '_embeding_vertex_0') for leg in ('left', 'right')])
    model.add_shared_node(layer=Embedding(input_dim=num_node, output_dim=embedding_dim, input_length=1),
                          name="embedding_context",
                          inputs=[(leg + '_vertex_' + str(i)) for leg in ('left', 'right') for i in range(1, len(path_type))],
                          outputs=[(leg + '_embeding_vertex_' + str(i)) for leg in ('left', 'right') for i in range(1, len(path_type))])

    for i, n in enumerate(path_type):
        attr_layers = []
        for j, a in enumerate(node_attr_mapping[n]):
            for leg in ["left", "right"]:
                model.add_input(name="%s_input_attr_%s_%s" % (leg, i, j), input_shape=(attr_shape[a], ))
            model.add_shared_node(layer=Dense(output_dim=embedding_dim),
                                  name="encoder_attr_%s_%s" % (i, j),
                                  inputs=["%s_input_attr_%s_%s" % (leg, i, j) for leg in ["left", "right"]],
                                  outputs=["%s_encoded_attr_%s_%s" % (leg, i, j) for leg in ["left", "right"]])
            attr_layers.append("_encoded_attr_%s_%s" % (i, j))
            for leg in ["left", "right"]:
                model.add_output("%s_output_vertex_%s_%s" % (leg, i, j),
                                 inputs=["%s_encoded_attr_%s_%s" % (leg, i, j), "%s_embeding_vertex_%s" % (leg, i)],
                                 merge_mode="dot")
                output_loss.append(("%s_output_vertex_%s_%s" % (leg, i, j), "binary_crossentropy"))

        # add vertex attributes loss
    # for i, n in enumerate(path_type):
    #     for leg in ["left", "right"]:
    #         model.add_node(Dense(output_dim=embedding_dim), name="%s_embedding_attr_%s" % (leg, i),
    #                        inputs=[leg+layer_name for layer_name in attr_layers], merge_mode="sum")
    #         model.add_output("%s_output_vertex_%s" % (leg, i),
    #                          inputs=["%s_embedding_attr_%s" % (leg, i), "%s_embeding_vertex_%s" % (leg, i)],
    #                          merge_mode="dot")
    #         output_loss.append(("%s_output_vertex_%s" % (leg, i), "binary_crossentropy"))

    # add local context loss
    for leg in ["left", "right"]:
        for i in range(1, len(path_type)):
            model.add_output("%s_output_edge_%s" % (leg, i),
                             inputs=["%s_embeding_vertex_%s" % (leg, 0), "%s_embeding_vertex_%s" % (leg, i)],
                             merge_mode="dot")
            output_loss.append(("%s_output_edge_%s" % (leg, i), "binary_crossentropy"))

    # add alignment loss
    model.add_output("output_alignment",
                     inputs=["left_embeding_vertex_0", "right_embeding_vertex_0"],
                     merge_mode="dot")
    output_loss.append(("output_alignment", "binary_crossentropy"))

    model.compile('sgd', loss=dict(output_loss))
    return model

vocab = pickle.load(open("vocab.pkl", "rb"))
token_to_idx = pickle.load(open("token_to_idx.pkl", "rb"))
idx_to_token = pickle.load(open("idx_to_token.pkl", "rb"))
fvectors = pickle.load(open("fvectors.pkl", "rb"))

def sample_pair(num_names, num_node, neg_rate):
    current_name = random.randint(0, num_names - 1)
    name = sorted_names[current_name]
    pubs = name_to_idx[name]
    if len(pubs) < 2:
        return []
    true_pair = tuple([data[k[0]]["a"][k[1]]["i"] for k in random.sample(name_to_idx[name], 2)])
    samples = [(true_pair, 1)]
    for i in [(0, 1), (1, 0)]:
        for j in range(neg_rate):
            idx = random.randint(0, num_node - 1)
            false_pair = [-1, -1]
            false_pair[i[0]] = true_pair[i[0]]
            if "a" in data[idx]:
                if len(data[idx]["a"]) == 0:
                    continue
                false_pair[i[1]] = random.sample(data[idx]["a"], 1)[0]["i"]
            else:
                false_pair[i[1]] = idx
            samples.append((tuple(false_pair), 0))
    return samples

def get_path(node, neg_rate, num_vertex):
    pathes = []
    # print(node)
    # print(data[node]["p"])
    pub = data[data[node]["p"]]
    for a in pub["a"]:
        if not a["i"] == data[node]["i"]:
            path = ((node, fvectors['n'][node], fvectors['o'][node]),
                    (pub["i"], fvectors['t'][pub['i']], fvectors['k'][pub['i']], fvectors['v'][pub['i']]),
                    (a['i'], fvectors['n'][a['i']], fvectors['o'][a['i']]), 1, 1)
            # path = ((node, data[node]['n'], data[node]["o"]),
            #         (pub["i"], pub["t"], pub["k"], pub["v"]),
            #         (a["i"], a["n"], a["o"]), 1, 1)
            pathes.append(path)
    for i in range(neg_rate):
        idx = random.randint(0, num_vertex - 1)
        if "a" in data[idx]:
            if len(data[idx]["a"]) == 0:
                continue
            a_idx = random.randint(0, len(data[idx]["a"]) - 1)
            p_id = data[idx]["i"]
            a_id = data[idx]["a"][a_idx]["i"]
            path = ((node, fvectors['n'][node], fvectors["o"][node]),
                    (p_id, fvectors["t"][p_id], fvectors["k"][p_id], fvectors["v"][p_id]),
                    (a_id, fvectors["n"][a_id], fvectors["o"][a_id]),
                    0, 0)
            # path = ((node, data[node]['n'], data[node]["o"]),
            #         (data[idx]["i"], data[idx]["t"], data[idx]["k"], data[idx]["v"]),
            #         (data[idx]["a"][a_idx]["i"], data[idx]["a"][a_idx]["n"], data[idx]["a"][a_idx]["o"]),
            #         0, 0)
            pathes.append(path)
        else:
            p_id = pub["i"]
            a_id = data[idx]["i"]
            path = ((node, fvectors['n'][node], fvectors["o"][node]),
                    (p_id, fvectors["t"][p_id], fvectors["k"][p_id], fvectors["v"][p_id]),
                    (a_id, fvectors["n"][a_id], fvectors["o"][a_id]),
                    1, 0)
            pathes.append(path)
    return pathes

def get_context_pair(pair):
    pathes = []
    for i, leg in enumerate(["left", "right"]):
        pathes.append(get_path(pair[i], 10, 100))
    path_pairs = []
    for p1 in pathes[0]:
        for p2 in pathes[1]:
            path_pairs.append((p1, p2))
    return path_pairs

import numpy as np
from scipy import sparse
def gen_batch():
    num_names = 800000
    num_node = len(data)
    neg_rate = 10
    batch_size = 1
    while True:
        instances = dd(list)
        for _ in range(batch_size):
            samples = sample_pair(num_names, num_node, neg_rate)
            if len(samples) == 0:
                continue
            for s in samples:
                path_pairs = get_context_pair(s[0])
                legs = ["left", "right"]
                for p in path_pairs:
                    instances["output_alignment"].append(s[1])
                    for i, n in enumerate(p):
                        # outputs
                        instances["%s_output_edge_1" % legs[i]].append(n[3])
                        instances["%s_output_edge_2" % legs[i]].append(n[4])

                        # vertex index
                        for k1 in range(3):
                            instances["%s_vertex_%s" % (legs[i], k1)].append(np.array(n[k1][0]))
                        # attribute feature vector
                        for k1 in range(3):
                            for k2 in range(1, len(n[k1])):
                                instances["%s_input_attr_%s_%s" % (legs[i], k1, k2-1)].append(n[k1][k2])
                                instances["%s_output_vertex_%s_%s" % (legs[i], k1, k2-1)].append(1)
        for k in instances:
            instances[k] = sparse.vstack(instances[k]).toarray()
        yield instances

def get_context_graph(idx):
    graph = {}
    graph["vertex_pub"] = [idx]
    graph["vertex_author"] = [a["i"] for a in data[idx]["a"]]
    graph["input_attr_name"] = []
    graph["input_attr_org"] = []
    graph["input_attr_title"] = []
    graph["input_attr_venue"] = []
    return graph

def run():
    num_node = len(data)
    node_attr_mapping = {
        "pub": ["t", "v", "k"],
        "author": ["n", "o"]
    }
    path_type = ["author", "pub", "author"]
    attr_shape = {}
    for t in ["n", "o", "t", "v", "k"]:
        attr_shape[t] = fvectors[t].shape[1]
    model = build_network(num_node, path_type, node_attr_mapping, attr_shape)
    epoch = 0
    for instances in gen_batch():
        print(len(instances["output_alignment"]))
        if len(instances["output_alignment"]) == 0:
            continue
        print(epoch)
        epoch += 1
        loss = model.fit(instances)
        print(loss)


N, M = map(int, input().split())
pan = []
w = dict()
for i in range(N):
    ip = input()
    for j in range(M):
        if ip[j] == "@":
            sx, sy = i, j
        elif ip[j] != '.' and ip[j] != '=' and ip[j] != '#':
            if not w.get(ip[j]):
                w[ip[j]] = [(i, j)]
            else:
                w[ip[j]].append((i, j))
    pan.append(ip)

visited = [[0 for _ in range(M)] for _ in range(N)]
visited[sx][sy] = 1
q = [(sx, sy, 0)]
while q:
    x, y, d = q.pop(0)
    if pan[x][y] == '=':
        print(d)
        quit()
    for dx, dy in [[1, 0], [-1, 0], [0, 1], [0, -1]]:
        nx, ny = x + dx, y + dy
        if N > nx >= 0 and M > ny >= 0 and not visited[nx][ny] and pan[nx][ny] != '#':
            if pan[nx][ny] != '.' and pan[nx][ny] != '=' and pan[nx][ny] != '#':
                for i, j in w.get(pan[nx][ny]):
                    if (nx, ny) != (i, j):
                        nx, ny = i, j
                        break
            else:
                visited[nx][ny] = 1
            q.append((nx, ny, d+1))


import random

class Pokemon:
    def __init__(self,nome,especie,tipo):
        self._nome = nome
        self._especie = especie
        self._tipo = tipo
        self._movimento = "Ataque rapido"
class Aquatico(Pokemon):
    def __init__(self,nome,especie,tipo):
     super().__init__(nome,especie,tipo)
     self._tipo = "Aquatico"
     self._movimento = "Jato de água"

class Fogo(Pokemon):
    def __init__(self,nome,especie,tipo):
     super().__init__(nome,especie,tipo)
     self._tipo = "Fogo"
     self._movimento = "Lança Chamas"

class Elétrico(Pokemon):
    def __init__(self,nome,especie,tipo):
     super().__init__(nome,especie,tipo)
     self._tipo = "Eletrico"
     self._movimento = "Raio do trovão"

class Grama(Pokemon):
    def __init__(self,nome,especie,tipo):
     super().__init__(nome,especie,tipo)
     self._tipo = "Grama"
     self._movimento = "Folhas navalha"

class Treinador:
    def __init__(self,nome,pokemons):
        self._nome = nome
        self._pokemons = pokemons

class Jogador(Treinador):
    def __init__(self,nome,pokemons):
        super().__init__(nome,pokemons)

    def escolherPokemon(self):
        while True:
            print(f"Escolha seu pokemon: ")

            for i in range(len(self._pokemons)):
                print(f"{i+1}. {self._pokemons[i]._especie}")

            pokemonEscolhido = input("Digite o número do pokemon escolhido: ")

            return self._pokemons[int(pokemonEscolhido)-1]

            if (pokemonEscolhido.isnumeric()):
                if (int(pokemonEscolhido) <= len(self._pokemons)):
                    return self._pokemons[pokemonEscolhido]
                else:
                    print("Você escreveu um número maior do que o disponível.")
            else:
                print("Você escreveu um caractere inválido")
    def listarPokemons(self):
        print(f"seus pokemons são")
        for i in range(len(self._pokemons)) :
            print(f"{i+1} - {self._pokemons[i]._especie}")

    def capturarPokemon(self, pokemonCapturado):
        self._pokemons.append(pokemonCapturado)
        print(f"Você capturou o {pokemonCapturado._especie}")

class Inimigo(Treinador):
    def __init__(self,nome,pokemons):
        super().__init__(nome,pokemons)
    def escolherPokemon(self):
        return random.choice(self._pokemons)

def BatalhaPokemon(treinador1, treinador2):

    p1 = treinador1.escolherPokemon()
    p2 = treinador2.escolherPokemon()

    p1tipo = p1._tipo
    p2tipo = p2._tipo

    print(f"{p1._nome} atacou com o {p1._especie} usando a habilidade {p1._movimento}")

    print(f"{p2._nome} atacou com o {p2._especie} usando a habilidade {p2._movimento}")

    if (p1tipo is "Aquatico" and p2tipo is "Fogo"):
        print(f"O vencedor foi {p1._especie} do treinador {p1._nome}")
    elif (p1tipo is "Fogo" and p2tipo is "Aquatico"):
        print(f"O vencedor foi {p2._especie} do treinador {p2._nome}")

    elif (p1tipo is "Aquatico" and p2tipo is "Grama"):
        print(f"O vencedor foi {p2._especie} do treinador {p2._nome}")
    elif (p1tipo is "Grama" and p2tipo is "Aquatico"):
        print(f"O vencedor foi {p1._especie} do treinador {p1._nome}")

    elif (p1tipo is "Fogo" and p2tipo is "Grama"):
        print(f"O vencedor foi {p1._especie} do treinador {p1._nome}")
    elif (p1tipo is "Grama" and p2tipo is "Fogo"):
        print(f"O vencedor foi {p2._especie} do treinador {p2._nome}")

    elif (p1tipo is "Fogo" and p2tipo is "Eletrico"):
        print(f"O vencedor foi {p2._especie} do treinador {p2._nome}")
    elif (p1tipo is "Eletrico" and p2tipo is "Fogo"):
        print(f"O vencedor foi {p1._especie} do treinador {p1._nome}")

    elif (p1tipo is "Eletrico" and p2tipo is "Aquatico"):
        print(f"O vencedor foi {p1._especie} do treinador {p1._nome}")
    elif (p1tipo is "Aquatico" and p2tipo is "Eletrico"):
        print(f"O vencedor foi {p2._especie} do treinador {p2._nome}")

    elif (p1tipo is "Eletrico" and p2tipo is "Grama"):
        print(f"O vencedor foi {p1._especie} do treinador {p1._nome}")
    elif (p1tipo is "Grama" and p2tipo is "Eletrico"):
        print(f"O vencedor foi {p2._especie} do treinador {p2._nome}")
    else:
        print("Os pokemons são de mesmo tipo a batalha deu empate")

PokemonsDisp = [
Fogo("Ash", "Charmander", "Fogo"),
Grama("Jessy", "bulbassauro", "Grama"),
Aquatico("James", "Tentacruel", "Aquatico"),
Elétrico("Wendel", "Electabuzz", "Eletrico")
]

nomeJogador = input("Digite seu nome: ")

print("Escolha seu Pokemon inicial: ")

for i in range(4):
    print(f"{i+1}. {PokemonsDisp[i]._especie}")

pokemonInicial = PokemonsDisp[int(input("Digite o pokemon escolhido: "))-1]

print(f"O pokemon escolhido foi o {pokemonInicial._especie}")

jogador = Jogador(nomeJogador, [pokemonInicial])
inimigo = Inimigo("James", PokemonsDisp)

while True:

    print("""
    Escolha o que você quer fazer:
    1. Ver seus Pokemons
    2. Capturar um novo Pokemon
    3. Batalhar contra um oponente
    0. Sair do jogo
    """)

    menu = input("Digite a opção escolhida:")

    if menu =="0":
        print("Você saiu do jogo.")
        break
    elif menu=="1":
        jogador.listarPokemons()
    elif menu=="2":
        print("Escolha um pokemon para capturar: ")

        for i in range(len(PokemonsDisp)):
            print(f"{i+1}. {PokemonsDisp[i]._especie}")

        capturado = PokemonsDisp[int(input("Digite o pokemon escolhido: "))-1]
        jogador.capturarPokemon(capturado)
    elif menu=="3":
        BatalhaPokemon(jogador,inimigo)
    else:
        print("Você digitou algo inválido, tente novamente.")


from nuitka import Builtins
from nuitka.utils import Utils

from . import CodeTemplates, CppStrings, OperatorCodes
from .AttributeCodes import (
    getAttributeAssignmentClassSlotCode,
    getAttributeAssignmentCode,
    getAttributeAssignmentDictSlotCode,
    getAttributeCheckBoolCode,
    getAttributeDelCode,
    getAttributeLookupCode,
    getSpecialAttributeLookupCode
)
from .CallCodes import (
    getCallCodeKeywordArgs,
    getCallCodeNoArgs,
    getCallCodePosArgs,
    getCallCodePosArgsQuick,
    getCallCodePosKeywordArgs,
    getCallsCode,
    getCallsDecls,
    getMakeBuiltinExceptionCode
)
from .ComparisonCodes import (
    getBranchingCode,
    getBuiltinIsinstanceBoolCode,
    getComparisonExpressionBoolCode,
    getComparisonExpressionCode
)
from .ConstantCodes import getConstantAccess, getConstantCode
from .DictCodes import (
    getBuiltinDict2Code,
    getDictOperationGetCode,
    getDictOperationRemoveCode,
    getDictOperationSetCode
)
from .ErrorCodes import (
    getErrorExitBoolCode,
    getErrorExitCode,
    getReleaseCode,
    getReleaseCodes
)
from .EvalCodes import (
    getCompileCode,
    getEvalCode,
    getExecCode,
    getLocalsDictSyncCode
)
from .ExceptionCodes import (
    getExceptionCaughtTracebackCode,
    getExceptionCaughtTypeCode,
    getExceptionCaughtValueCode,
    getExceptionIdentifier,
    getExceptionRefCode,
    getExceptionUnpublishedReleaseCode,
    getTracebackMakingIdentifier
)
from .FrameCodes import (
    getFrameGuardHeavyCode,
    getFrameGuardLightCode,
    getFrameGuardOnceCode,
    getFrameLocalsUpdateCode,
    getFramePreserveExceptionCode,
    getFrameReraiseExceptionCode,
    getFrameRestoreExceptionCode
)
from .FunctionCodes import (
    getDirectFunctionCallCode,
    getFunctionCode,
    getFunctionCreationCode,
    getFunctionDirectDecl,
    getFunctionMakerCode,
    getFunctionMakerDecl,
    getGeneratorFunctionCode
)
from .GlobalsLocalsCodes import (
    getLoadGlobalsCode,
    getLoadLocalsCode,
    getSetLocalsCode,
    getStoreLocalsCode
)
from .ImportCodes import (
    getBuiltinImportCode,
    getImportFromStarCode,
    getImportModuleHardCode,
    getImportNameCode
)
from .IndexCodes import (
    getIndexCode,
    getIndexValueCode,
    getMaxIndexCode,
    getMinIndexCode
)
from .IteratorCodes import (
    getBuiltinLoopBreakNextCode,
    getBuiltinNext1Code,
    getUnpackCheckCode,
    getUnpackNextCode
)
from .LabelCodes import getGotoCode, getLabelCode
from .ListCodes import getListOperationAppendCode
from .MainCodes import getMainCode
from .ModuleCodes import (
    getModuleAccessCode,
    getModuleCode,
    getModuleMetapathLoaderEntryCode,
    prepareModuleCode
)
from .PrintCodes import getPrintNewlineCode, getPrintValueCode
from .PythonAPICodes import getCAPIIntCode, getCAPIObjectCode
from .RaisingCodes import (
    getRaiseExceptionWithCauseCode,
    getRaiseExceptionWithTracebackCode,
    getRaiseExceptionWithTypeCode,
    getRaiseExceptionWithValueCode,
    getReRaiseExceptionCode
)
from .SetCodes import getSetOperationAddCode
from .SliceCodes import (
    getSliceAssignmentCode,
    getSliceAssignmentIndexesCode,
    getSliceDelCode,
    getSliceDelIndexesCode,
    getSliceLookupCode,
    getSliceLookupIndexesCode,
    getSliceObjectCode
)
from .SubscriptCodes import (
    getIntegerSubscriptAssignmentCode,
    getSubscriptAssignmentCode,
    getSubscriptDelCode,
    getSubscriptLookupCode
)
from .VariableCodes import getVariableAccessCode, getVariableCode
from .YieldCodes import getYieldCode, getYieldFromCode

# pylint: enable=W0611

def getLoopBreakCode(emit, context):
    getExceptionUnpublishedReleaseCode(emit, context)

    break_target = context.getLoopBreakTarget()
    if type(break_target) is tuple:
        emit("%s = true;" % break_target[1])
        break_target = break_target[0]

    getGotoCode(break_target, emit)

def getLoopContinueCode(emit, context):
    getExceptionUnpublishedReleaseCode(emit, context)

    continue_target = context.getLoopContinueTarget()
    if type(continue_target) is tuple:
        emit("%s = true;" % continue_target[1])
        continue_target = continue_target[0]

    getGotoCode(continue_target, emit)

def getConditionCheckTrueCode(to_name, value_name, emit):
    emit(
        "%s = CHECK_IF_TRUE( %s );" % (
            to_name,
            value_name
        )
    )

def getBuiltinRefCode(to_name, builtin_name, emit, context):
    emit(
        "%s = LOOKUP_BUILTIN( %s );" % (
            to_name,
            getConstantCode(
                constant = builtin_name,
                context  = context
            )
        )
    )

    getErrorExitCode(
        check_name = to_name,
        emit       = emit,
        context    = context
    )

    # Gives no reference

def getBuiltinAnonymousRefCode(to_name, builtin_name, emit):
    emit(
        "%s = (PyObject *)%s;" % (
            to_name,
            Builtins.builtin_anon_codes[builtin_name]
        )
    )

def getBuiltinSuperCode(to_name, type_name, object_name, emit, context):
    emit(
        "%s = BUILTIN_SUPER( %s, %s );" % (
            to_name,
            type_name if type_name is not None else "NULL",
            object_name if object_name is not None else "NULL"
        )
    )

    getReleaseCodes(
        release_names = (type_name, object_name),
        emit          = emit,
        context       = context
    )

    getErrorExitCode(
        check_name = to_name,
        emit       = emit,
        context    = context
    )

    context.addCleanupTempName(to_name)

def getBuiltinType3Code(to_name, type_name, bases_name, dict_name, emit,
                        context):
    emit(
        "%s = BUILTIN_TYPE3( %s, %s, %s, %s );" % (
            to_name,
            getConstantCode(
                constant = context.getModuleName(),
                context  = context
            ),
            type_name,
            bases_name,
            dict_name
        ),
    )

    getReleaseCodes(
        release_names = (type_name, bases_name, dict_name),
        emit          = emit,
        context       = context
    )

    getErrorExitCode(
        check_name = to_name,
        emit       = emit,
        context    = context
    )

    context.addCleanupTempName(to_name)

def getBuiltinLong2Code(to_name, base_name, value_name, emit, context):
    emit(
        "%s = TO_LONG2( %s, %s );" % (
            to_name,
            value_name,
            base_name
        )
    )

    getReleaseCodes(
        release_names = (value_name, base_name),
        emit          = emit,
        context       = context
    )

    getErrorExitCode(
        check_name = to_name,
        emit       = emit,
        context    = context
    )

    context.addCleanupTempName(to_name)

def getBuiltinInt2Code(to_name, base_name, value_name, emit, context):
    emit(
        "%s = TO_INT2( %s, %s );" % (
            to_name,
            value_name,
            base_name
        )
    )

    getReleaseCodes(
        release_names = (value_name, base_name),
        emit          = emit,
        context       = context
    )

    getErrorExitCode(
        check_name = to_name,
        emit       = emit,
        context    = context
    )

    context.addCleanupTempName(to_name)

def getExportScopeCode(cross_module):
    if cross_module:
        return "NUITKA_CROSS_MODULE"
    else:
        return "NUITKA_LOCAL_MODULE"

def _getMetaclassVariableCode(context):
    assert Utils.python_version < 300

    return "GET_STRING_DICT_VALUE( moduledict_%s, (Nuitka_StringObject *)%s )" % (
        context.getModuleCodeName(),
        getConstantCode(
            constant = "__metaclass__",
            context  = context
        )
    )

def getSelectMetaclassCode(to_name, metaclass_name, bases_name, emit, context):
    if Utils.python_version < 300:
        assert metaclass_name is None

        args = [
            bases_name,
            _getMetaclassVariableCode(context = context)
        ]
    else:
        args = [
            metaclass_name,
            bases_name
        ]

    emit(
        "%s = SELECT_METACLASS( %s );" % (
            to_name,
            ", ".join(args)
        )
    )

    # Can only fail with Python3.
    if Utils.python_version >= 300:
        getErrorExitCode(
            check_name = to_name,
            emit       = emit,
            context    = context
        )

        getReleaseCodes(
            release_names = args,
            emit          = emit,
            context       = context
        )
    else:
        getReleaseCode(
            release_name = bases_name,
            emit         = emit,
            context      = context
        )

    context.addCleanupTempName(to_name)

def getStatementTrace(source_desc, statement_repr):
    return 'puts( "Execute: " %s );' % (
        CppStrings.encodeString(source_desc + b" " + statement_repr),
    )


class Wohnviertel:
    def __init__(self,Straße,Farbe,Hausnummer,PLZ,Preis,Stockwerke,Quadratmeter):
        self.straße = Straße
        self.Farbe = Farbe
        self.Hausnummer =  Hausnummer
        self.PLZ = PLZ
        self.Preis = Preis
        self.Stockwerke = Stockwerke
        self.Quadrarmeter = Quadratmeter

Haus1 =  Wohnviertel("Wiesbadener Straße" , "Grün" , 22 , 6572 , "3345€" , 3 , 44)

print (Haus1)


from setuptools import setup, find_packages
import os

# The version of the wrapped library is the starting point for the
# version number of the python package.
# In bugfix releases of the python package, add a '-' suffix and an
# incrementing integer.
# For example, a packaging bugfix release version 1.4.4 of the
# js.jquery package would be version 1.4.4-1 .

version = '1.0.0b3.dev0'

def read(*rnames):
    return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

long_description = (
    read('README.rst')
    + '\n' +
    read('js', 'leaflet', 'test_leaflet.txt')
    + '\n' +
    read('CHANGES.rst'))

setup(
    name='js.leaflet',
    version=version,
    description="Fanstatic packaging of Leaflet",
    long_description=long_description,
    classifiers=[],
    keywords='javascript mapping map leaflet js openlayers',
    author='Fanstatic Developers',
    author_email='fanstatic@googlegroups.com',
    url='https://github.com/davidjb/js.leaflet',
    license='BSD',
    packages=find_packages(),
    namespace_packages=['js'],
    include_package_data=True,
    zip_safe=False,
    setup_requires=[
        'setuptools-git',
    ],
    install_requires=[
        'fanstatic>=1.0a',
        'setuptools',
        ],
    entry_points={
        'fanstatic.libraries': [
            'leaflet = js.leaflet:library',
            ],
        },
    )


import os
import os
import csv
from college.models import College
from django.db.models import Count
import json
from django.conf import settings

file_data = {}
db_data = {}

with open(os.path.join(settings.BASE_DIR, 'scripts/students/data_check_code_dir.json'), "r") as file:
    file_data = json.loads(file.read())
    file.close()

with open(os.path.join(settings.BASE_DIR, 'scripts/students/data_check_db_dir.json'), "r") as file:
    db_data = json.loads(file.read())
    file.close()

final_test_data_not_db = 'code,roll_no'
file_college_codes = file_data.keys()
db_college_codes = db_data.keys()

colleges_codes_not_match = []

colleges_codes_not_match += list(set(file_college_codes) - set(db_college_codes))
colleges_codes_not_match += list(set(db_college_codes) - set(file_college_codes))
colleges_codes_not_match = set(colleges_codes_not_match)

students_not_match = 'college_code,student_roll_no,not_match'
students_not_match_data = {}

# print("flag 3")
# Step 1
final_check_data = {}
for college_code in file_college_codes:
    check_data = []
    file_students = file_data[college_code] if college_code in file_data.keys() else []
    db_students = file_data[college_code] if college_code in db_data.keys() else []

    student_codes_not_match = []
    student_codes_not_match += list(set(file_students) - set(db_students))
    student_codes_not_match += list(set(db_students) - set(file_students))
    student_codes_not_match = set(student_codes_not_match)
    final_check_data[college_code] = list(student_codes_not_match)

# print("flag 4")
final_check_data_codes = final_check_data.keys()
for college_code in db_college_codes:
    check_data = []
    # print("floag - 12")
    print(college_code in file_data.keys())
    print(college_code in db_data.keys())
    file_students = file_data[college_code] if college_code in file_data.keys() else []

    # print("floag - 164")
    db_students = db_data[college_code] if college_code in db_data.keys() else []

    # print("floag - 1641")

    student_codes_not_match = []
    if not db_students:
        student_codes_not_match = set(file_students) if file_students else []
    if not file_students:
        student_codes_not_match = set(db_students) if db_students else []
    else:
        student_codes_not_match += list(set(file_students) - set(db_students))
        student_codes_not_match += list(set(db_students) - set(file_students))
        student_codes_not_match = set(student_codes_not_match)

    # print("floag - 1642")

    # print("floag - 143")
    if college_code in final_check_data_codes:
        final_check_data[college_code] += list(student_codes_not_match)
    else:
        final_check_data[college_code] = list(student_codes_not_match)

final_csv_data = 'college_code,student_roll_no'

for college_code, student_data in final_check_data.items():
    student_data = list(set(student_data))
    for roll_no in student_data:
        final_csv_data += f"\n{college_code},{roll_no}"

with open(os.path.join(settings.BASE_DIR, "scripts/students/student_codes_not_match.csv"), "w") as file:
    file.write(final_csv_data)
    file.close()


import os
import pathlib

from lava_common.constants import LAVA_DOWNLOADS
from lava_common.exceptions import JobError
from lava_dispatcher.action import Action, Pipeline
from lava_dispatcher.actions.boot import BootHasMixin
from lava_dispatcher.actions.boot.environment import ExportDeviceEnvironment
from lava_dispatcher.logical import Boot, RetryAction
from lava_dispatcher.shell import ExpectShellSession, ShellCommand, ShellSession
from lava_dispatcher.utils.network import dispatcher_ip

class BootDocker(Boot):
    compatibility = 4

    @classmethod
    def action(cls):
        return BootDockerAction()

    @classmethod
    def accepts(cls, device, parameters):
        if "docker" not in device["actions"]["boot"]["methods"]:
            return False, '"docker" was not in the device configuration boot methods'
        if parameters["method"] != "docker":
            return False, '"method" was not "docker"'
        if "command" not in parameters:
            return False, '"command" was not in boot parameters'
        return True, "accepted"

class BootDockerAction(BootHasMixin, RetryAction):
    name = "boot-docker"
    description = "boot docker image"
    summary = "boot docker image"

    def populate(self, parameters):
        self.pipeline = Pipeline(parent=self, job=self.job, parameters=parameters)
        self.pipeline.add_action(CallDockerAction())
        if self.has_prompts(parameters):
            if self.test_has_shell(parameters):
                self.pipeline.add_action(ExpectShellSession())
                self.pipeline.add_action(ExportDeviceEnvironment())

class CallDockerAction(Action):
    name = "docker-run"
    description = "call docker run on the image"
    summary = "call docker run"

    def __init__(self):
        super().__init__()
        self.cleanup_required = False
        self.remote = ""
        self.extra_options = ""
        self.container = ""

    def validate(self):
        super().validate()
        self.container = "lava-%s-%s" % (self.job.job_id, self.level)

        options = self.job.device["actions"]["boot"]["methods"]["docker"]["options"]

        docker_image = self.get_namespace_data(
            action="deploy-docker", label="image", key="name"
        )
        if docker_image is None:
            raise JobError("Missing deploy action before boot")

        if options["remote"]:
            self.remote = " --host %s" % options["remote"]
        if options["cpus"]:
            self.extra_options += " --cpus %s" % options["cpus"]
        if options["memory"]:
            self.extra_options += " --memory %s" % options["memory"]
        if options["privileged"]:
            self.extra_options += " --privileged"
        for cap in options["capabilities"]:
            self.extra_options += " --cap-add %s" % cap
        for device in options["devices"]:
            self.extra_options += " --device %s" % device
        for network in options["networks"]:
            self.extra_options += " --network %s" % network
        for volume in options["volumes"]:
            self.extra_options += " --volume %s" % volume
        for extra_argument in options["extra_arguments"]:
            self.extra_options += " " + extra_argument

    def run(self, connection, max_end_time):
        location = self.get_namespace_data(
            action="test", label="shared", key="location"
        )
        docker_image = self.get_namespace_data(
            action="deploy-docker", label="image", key="name"
        )

        # Build the command line
        # The docker image is safe to be included in the command line
        cmd = "docker" + self.remote + " run --rm --interactive --tty --hostname lava"
        cmd += " --name %s" % self.container
        if self.test_needs_overlay(self.parameters):
            overlay = self.get_namespace_data(
                action="test", label="results", key="lava_test_results_dir"
            )
            if not self.remote:
                cmd += " --volume %s:%s" % (
                    os.path.join(location, overlay.strip("/")),
                    overlay,
                )
            else:
                cmd += (
                    ' --mount type=volume,volume-driver=local,dst=%s,volume-opt=type=nfs,volume-opt=device=:%s,"volume-opt=o=addr=%s"'
                    % (
                        overlay,
                        os.path.join(location, overlay.strip("/")),
                        dispatcher_ip(self.job.parameters["dispatcher"]),
                    )
                )

        namespace = self.parameters.get(
            "downloads-namespace", self.parameters.get("namespace")
        )
        if namespace:
            downloads_dir = pathlib.Path(self.job.tmp_dir) / "downloads" / namespace
            if downloads_dir.exists():
                self.extra_options += " --volume %s:%s" % (
                    downloads_dir,
                    LAVA_DOWNLOADS,
                )

        cmd += self.extra_options
        cmd += " %s %s" % (docker_image, self.parameters["command"])

        self.logger.debug("Boot command: %s", cmd)
        shell = ShellCommand(cmd, self.timeout, logger=self.logger)
        self.cleanup_required = True

        shell_connection = ShellSession(self.job, shell)
        shell_connection = super().run(shell_connection, max_end_time)

        self.set_namespace_data(
            action="shared", label="shared", key="connection", value=shell_connection
        )
        return shell_connection

    def cleanup(self, connection):
        super().cleanup(connection)
        if self.cleanup_required:
            self.logger.debug("Stopping container %s", self.container)
            self.run_cmd(
                "docker %s stop %s" % (self.remote, self.container), allow_fail=True
            )
            self.cleanup_required = False