# ██████  ██    ██ ███████  ██████  ██ ██      ██████
# ██   ██  ██  ██  ██      ██    ██ ██ ██           ██
# ██████    ████   █████   ██    ██ ██ ██       █████
# ██         ██    ██      ██    ██ ██ ██      ██
# ██         ██    ██       ██████  ██ ███████ ███████

import os, requests, zipfile, io, re, math
from os import path
from bs4 import BeautifulSoup
from heapq import nsmallest, nlargest

class foilscrape:
    def __init__(self, cd):
        self.cd = cd
        self.data_folder = cd + "\pyfoil_data\\"
        self.foil_datfolder = self.data_folder + "dat\\"
        self.foil_txtfolder = self.data_folder + "txt\\"
        self.solidworks_folder = self.data_folder + "solidworks_format\\"
        self.dat_list = []
        self.foil_list = []
        self.good_foil_list = []
        self.bad_foil_list = []
        self.misformated = []

        with open(self.cd + '\\blacklist.pyfoil', 'r') as blacklist:
            self.blacklist = [x for x in blacklist.read().splitlines()]
            self.bad_foil_list = list(set(self.bad_foil_list + self.blacklist))

        if not path.exists(self.data_folder):
            os.makedirs(self.data_folder)

        if not path.exists(self.foil_datfolder):
            os.makedirs(self.foil_datfolder)

        if not path.exists(self.foil_txtfolder):
            os.makedirs(self.foil_txtfolder)

        if not path.exists(self.solidworks_folder):
            os.makedirs(self.solidworks_folder)

        if path.isfile(self.data_folder + 'g.txt'):
            with open(self.data_folder + 'g.txt', 'r') as text:
                self.good_foil_list = [x for x in text.read().splitlines()]
                print('Loaded ' + str(len(self.good_foil_list)) + ' Foils')

        else:
            if not os.listdir(self.foil_datfolder):
                self._download_files()

            self.foil_list = self.get_foil_list()
            self.dat_list = self.get_dat_list()
            self._check_differences()

        if self._check_missing_txt():
            for a in self._check_missing_txt():
                if a not in self.blacklist:
                    print('Creating Text File: ' + a)
                    self._correct_txt(a, self._read_dat(a + '.dat'))
                    self.convert_to_solidworks(a, self._read_dat(a + '.dat'))

        self._write_good()

    def _download_files(self):
        url = "http://m-selig.ae.illinois.edu/ads/archives/coord_seligFmt.zip"
        data = requests.get(url, stream = True)
        unzip = zipfile.ZipFile(io.BytesIO(data.content))
        unzip.extractall(self.data_folder)
        orig_folder = self.data_folder + "coord_seligFmt\\"

        for x in os.listdir(orig_folder):
            os.rename(orig_folder + x, self.foil_datfolder + x)

        os.rmdir(orig_folder)

    def _check_differences(self):
        missing_files = list(set(self.foil_list)-set(self.dat_list))

        for x in missing_files if missing_files != None else None:
            with open(self.foil_datfolder + x + '.dat','w') as text:
                url = 'http://m-selig.ae.illinois.edu/ads/coord_seligFmt/'
                a = requests.get(url + x + '.dat')
                text.write(a.text)

    def _check_missing_txt(self):
        missing_files = list(set(self.foil_list)-set([x.split(
        '.')[0] for x in os.listdir(self.foil_txtfolder)]))

        return missing_files

    def _read_dat(self, filename):
        with open(self.foil_datfolder + filename, 'r', encoding = 'iso8859_15') as text:
            tocopy = []
            content = text.read().splitlines()

            for index, line in enumerate(content):
                if index == 0 and re.search('[a-zA-Z]', line):
                    continue

                if index == 1:
                    try:
                        q = float(line.split()[0])
                        w = float(line.split()[1])

                        if abs(q) > 1.5 and abs(w) > 1.5:
                            continue

                    except:
                        continue

                if line.count('.') > 2:
                    continue

                tocopy.append(line)

            if len(tocopy) > 10:
                return tocopy

            else:
                self.bad_foil_list.append(filename.split('.')[0])
                return False

    def _correct_txt(self, name, text):
        tocopy = []

        for line in text:
            s = line.split()

            self.misformated.append(name) if not text else None

            if len(s) < 2:
                continue

            if s[0][0] == '.' and name not in set(self.misformated):
                self.misformated.append(name)
                s[0] = '0' + s[0]

            elif s[0][0] == '-' and not s[0][1] == '0':
                if name not in set(self.misformated):
                    self.misformated.append(name)
                s[0] = '-0' + s[0][1::]

            if s[1][0] == '.' and name not in set(self.misformated):
                self.misformated.append(name)
                s[1] = '0' + s[1]

            elif s[1][0] == '-' and not s[1][1] == '0':
                if name not in set(self.misformated):
                    self.misformated.append(name)
                s[1] = '-0' + s[1][1::]

            if s[0][0] == '\(' and name not in set(self.misformated):
                self.misformated.append(name)
                s[0] = re.findall('(?<=\().+?(?=\))', s[0])

            if s[1][0] == '\(' and name not in set(self.misformated):
                self.misformated.append(name)
                s[1] = re.findall('(?<=\().+?(?=\))', s[1])

            tocopy.append(s[0] + ' ' + s[1])

        self.convert_to_txt(name, tocopy)

    def convert_to_solidworks(self, name, content):
            with open(self.solidworks_folder + name + '.txt', 'w') as text:
                for line in content:
                    text.write(line + '\t' + '0' + '\n')

    def _write_good(self):
        with open(self.data_folder + 'g.txt', 'w') as text:
            for x in os.listdir(self.foil_txtfolder):
                text.write(x.split('.')[0] + '\n')

    def convert_to_txt(self, name, tocopy):
        with open(self.foil_txtfolder + name + '.txt', 'w') as f:
            for line in tocopy:
                f.write(line.split()[0] + '\t' + line.split()[1] + '\n')
            self.good_foil_list.append(name)

    def get_foil_list(self):
        foil_list = []
        url = 'http://m-selig.ae.illinois.edu/ads/coord_seligFmt/'
        data = requests.get(url)
        soup = BeautifulSoup(data.text, 'lxml')
        tabl = soup.find('table')
        rows = tabl.find_all('tr')

        for row in rows:
            cols = row.find_all('td')
            cols = [ele.text.strip() for ele in cols]
            nam = cols[1].split('.')[0] if len(cols) == 5 else 'index'

            foil_list.append(nam) if nam != 'index' else None

        return foil_list[1::]

    def get_dat_list(self):
        return [x.split('.')[0] for x in os.listdir(self.foil_datfolder)]

    def get_path(self, name):
        return str(self.foil_txtfolder + name + '.txt')

class foil:
    def __init__(self, filepath, alpha, down):
        self.dir = filepath
        self.name = filepath.split('\\')[-1].split('.')[0]

        with open(self.dir, 'r') as text:
            self.lines = text.read().splitlines()
        self.increment_factor = len(self.lines)//2
        self.xy= [[float(x.split()[0]), float(x.split()[1])] for x in self.lines]

        if down == 1:
            alpha = -1 * alpha

        if alpha != 0:
            angle = (math.pi/180) * alpha
            newfoil = []

            for x in self.xy:
                px, py = x
                qx = math.cos(angle) * (px) - math.sin(angle) * (py)
                qy = math.sin(angle) * (px) + math.cos(angle) * (py)
                newfoil.append([qx,qy])

            self.xy = newfoil

        if down == 1:
            self.xy = [[x, -1* y] for [x,y] in self.xy]

        self.x = [x[0] for x in self.xy]
        self.y = [x[1] for x in self.xy]

        for index, x in enumerate(self.xy):
            if x == min(self.xy):
                self.top = self.xy[:index + 1]
                self.bottom = self.xy[index::]

class foilmath(foil):
    def __init__(self, scraper, name, alpha, down):
        self.scraper = scraper
        super().__init__(self.scraper.get_path(name), alpha, down)

    def calc_trailing_edge(self):
        return max(self.xy)

    def calc_leading_edge(self):
        return min(self.xy)

    def calc_le_gradient(self):
        closest = nlargest(4, self.xy, key=lambda g: abs(g[0] - 1))[2::]
        le = self.calc_leading_edge()

        if closest[0][1] > closest[1][1]:
            g1 = (le[1] - closest[0][1])/(le[0] - closest[0][0])
            g2 = (le[1] - closest[1][1])/(le[0] - closest[1][0])

        else:
            g1 = (le[1] - closest[1][1])/(le[0] - closest[1][0])
            g2 = (le[1] - closest[0][1])/(le[0] - closest[0][0])

        return([g1, g2])

    def calc_te_gradient(self):
        closest = nsmallest(4, self.xy, key=lambda g: abs(g[0] - 1))[2::]
        le = self.calc_leading_edge()

        if closest[0][1] > closest[1][1]:
            g1 = (le[1] - closest[0][1])/(le[0] - closest[0][0])
            g2 = (le[1] - closest[1][1])/(le[0] - closest[1][0])

        else:
            g1 = (le[1] - closest[1][1])/(le[0] - closest[1][0])
            g2 = (le[1] - closest[0][1])/(le[0] - closest[0][0])

        return([g1, g2])

    def calc_max_thickness(self):
        differences = []

        for x in range(self.increment_factor):
            incc = (x+1)*(1/self.increment_factor)
            closest = nsmallest(2, self.xy, key=lambda g: abs(g[0]- incc))
            differences.append([abs(closest[1][1] - closest[0][1]), incc])

        return max(differences)

    def calc_max_camber(self):
        camber = []

        for x in range(self.increment_factor):
            incc = (x+1)*(1/self.increment_factor)
            closest = nsmallest(2, self.xy, key=lambda g: abs(g[0]- incc))
            camber.append([0.5*(closest[1][1]+closest[0][1]), incc])

        return max(camber)

    def get_foil(self):
        return self.xy

scraper = foilscrape(path.dirname(path.realpath(__file__)))


from flask import Flask
from strategies.blueprints.two_assets_MA import two_assets_MA

def create_app():
    """
    Crea una aplicacion de flask usando patron de fábrica.

    :return: Flask app
    """

    # configuracion de la aplicacion
    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object('config.settings')
    app.config.from_pyfile('settings.py', silent=True)

    # blueprints
    app.register_blueprint(two_assets_MA)

    return app


# -*- coding: utf-8 -*
'''
修改两个分隔符line 54、line 102
自定义标签line 100
'''

import os
import copy
import json

class InputExample(object):
    """A single training/test example for token classification."""
    def __init__(self, guid, text_a, labels):
        """Constructs a InputExample.
        Args:
            guid: Unique id for the example.
            text_a: list. The words of the sequence.
            labels: (Optional) list. The labels for each word of the sequence. This should be
            specified for train and dev examples, but not for test examples.
        """
        self.guid = guid
        self.text_a = text_a
        self.labels = labels

    def __repr__(self):
        return str(self.to_json_string())

    def to_dict(self):
        """Serializes this instance to a Python dictionary."""
        output = copy.deepcopy(self.__dict__)
        return output

    def to_json_string(self):
        """Serializes this instance to a JSON string."""
        return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"

class DataProcessor:
    """Base class for data converters for sequence classification data sets."""

    def get_train_examples(self, data_dir):
        """Gets a collection of `InputExample`s for the train set."""
        raise NotImplementedError()

    def get_dev_examples(self, data_dir):
        """Gets a collection of `InputExample`s for the dev set."""
        raise NotImplementedError()

    def get_labels(self):
        """Gets the list of labels for this data set."""
        raise NotImplementedError()

    def _read_text(self, input_file, delimiter='\t'):
        # delimiter: word与label之间的分隔符
        lines = []
        with open(input_file, 'r', encoding="utf-8") as f:
            words = []
            labels = []
            for line in f:
                if line.startswith("-DOCSTART-") or line == "" or line == "\n" or line == "end\n":
                    if words:
                        lines.append({"words": words, "labels": labels})
                        words = []
                        labels = []
                else:
                    splits = line.split(delimiter)               # 注意文本分隔符
                    words.append(splits[0].strip().lower())         # 加入小写
                    if len(splits) > 1:
                        labels.append(splits[-1].replace("\n", ""))
                    else:
                        # Examples could have no label for mode = "test"
                        labels.append("O")
            if words:
                lines.append({"words": words, "labels": labels})
        return lines

class NerProcessor(DataProcessor):
    """Processor for the chinese ner data set."""

    def get_train_examples(self, data_dir):
        """See base class."""
        examples = self._read_text(os.path.join(data_dir, "train.txt"))
        return self._create_examples(examples, "train")

    def get_dev_examples(self, data_dir):
        """See base class."""
        examples = self._read_text(os.path.join(data_dir, "dev.txt"))
        return self._create_examples(examples, "dev")

    def get_test_examples(self, data_dir):
        """See base class."""
        examples = self._read_text(os.path.join(data_dir, "test.txt"))
        return self._create_examples(examples, "test")

    def get_labels(self):
        """See base class."""
        return ['O', "B-T", "I-T", "B-ORG", "I-ORG", "B-LOC", "I-LOC", "B-PER", "I-PER"]

    def _create_examples(self, lines, set_type, delimiter='-'):
        """
        Creates examples for the training and dev sets.
        delimiter : bio和tag之间的分隔符，- or _，例如“B-PER”,"B_PER"
        """
        examples = []
        for (i, line) in enumerate(lines):
            if i == 0:
                continue
            guid = "%s-%s" % (set_type, i)
            text_a = line['words']
            # 转 BIO
            labels = []
            for x in line['labels']:
                if 'M'+delimiter in x:
                    labels.append(x.replace('M'+delimiter, 'I'+delimiter))
                elif 'E'+delimiter in x:
                    labels.append(x.replace('E'+delimiter, 'I'+delimiter))
                else:
                    labels.append(x)
            examples.append(InputExample(guid=guid, text_a=text_a, labels=labels))
        return examples


menu = {
    "Baja Taco": 4.00,
    "Burrito": 7.50,
    "Bowl": 8.50,
    "Nachos": 11.00,
    "Quesadilla": 8.50,
    "Super Burrito": 8.50,
    "Super Quesadilla": 9.50,
    "Taco": 3.00,
    "Tortilla Salad": 8.00,
}

print("Enter all items:")

total = 0

while True:
    try:
        item = input().title()

        cost = menu[item]
        total = total + cost
    except KeyError:
        print("Previous item not on the menu")
    except EOFError:
        print("\n")
        break

print(f"Your total is ${total:.2f}")


import pdfkit
import sys
import re

def renameSpaces(entrada):
    entrada = entrada.encode('utf-8', errors='surrogateescape').decode('utf-8')
    entrada = re.sub("_", " ", entrada)
    return entrada

def ajusteDatas(data):
    valor = data
    saida = valor[2:4]

    saida = str(saida)
    mes = ""

    if saida == "01":
        mes = "janeiro"
    elif saida == "02":
        mes = "fevereiro"
    elif saida == "03":
        mes = "maio"
    elif saida == "04":
        mes = "abril"
    elif saida == "05":
        mes = "marco"
    elif saida == "06":
        mes= "junho"
    elif saida == "07":
        mes = "julho"
    elif saida == "08":
        mes = "agosto"
    elif saida == "09":
        mes = "setembro"
    elif saida == "10":
        mes = "outubro"
    elif saida == "11":
        mes = "novembro"
    elif saida == "12":
        mes = "dezembro"
    else:
        pass

    return "{} de {} de {}".format(valor[0:2], mes, valor[4:8])

treinamento = sys.argv[1]
data_emissao = sys.argv[2]
data_inicial = sys.argv[3]
data_final = sys.argv[4]
horas = sys.argv[5]
responsaveis = sys.argv[6].split(',')
funcionarios = sys.argv[7].split(',')
cursos = sys.argv[8].split(',')

#Parte certificado
#-----------------------------------------------
arquivo = open("certificado.html", "w", encoding="utf-8")

arquivo.write("<!DOCTYPE html><meta name='pdfkit-page-size' content='A4'/><meta name='pdfkit-orientation' content='Landscape'/><link rel='stylesheet' type='text/css' href='./css/css_meio.css'>")
for c in range(len(funcionarios)-1, -1, -2):
    for i in range(c, c-2, -1):
        if i != int(-1):
            arquivo.write("

CERTIFICADO

")
            arquivo.write(renameSpaces(funcionarios[i]).title())
            arquivo.write("

É com satisfação que confiro-lhe o certificado, por sua participação no ")
            arquivo.write(renameSpaces(treinamento))
            arquivo.write(" realizado ")

            if int(data_final) == 0:
                arquivo.write(" em  ")
                arquivo.write(ajusteDatas(data_inicial))
            else:
                arquivo.write(" entre os dias ")
                arquivo.write(ajusteDatas(data_inicial))
                arquivo.write(" há ")
                arquivo.write(ajusteDatas(data_final))

            arquivo.write(" com carga horária de ")
            arquivo.write(horas)
            arquivo.write(" horas totais.

")
            arquivo.write("
Cordeirópolis, ")
            arquivo.write(ajusteDatas(data_emissao))
            arquivo.write("

")

            if len(responsaveis) == 6:
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[0]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[1]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[2]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[3]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[4]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[5]).title())
                arquivo.write("

")
            elif len(responsaveis) == 4:
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[0]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[1]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[2]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[3]).title())
                arquivo.write("

")
            elif len(responsaveis) == 2:
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[0]).title())
                arquivo.write("

")
                arquivo.write(renameSpaces(responsaveis[1]).title())
                arquivo.write("

")
            else:
                pass
        else:
            arquivo.write("

")

    for i in range(c, c-2, -1):
        if i != int(-1):
            arquivo.write("

Conteúdo programático

")
            for k in range(0, len(cursos)):
                arquivo.write("
")
                arquivo.write(renameSpaces(cursos[k]).capitalize())
                arquivo.write("
")
            arquivo.write("

")

arquivo.write("")

arquivo.close()
#-----------------------------------------------

#Saida
#-----------------------------------------------
array_arquivos = ['certificado.html']

options = {
    'page-size': 'A4',
    'margin-top': '0.75in',
    'margin-right': '0.75in',
    'margin-bottom': '0.75in',
    'margin-left': '0.75in',
    'encoding': 'UTF-8'
}
pdfkit.from_file(array_arquivos, "pdf_tmp_9842389429.pdf", options=options)
#-----------------------------------------------


def neighborhood(centerIndex, radius, dimensions):
  """
  Get the points in the neighborhood of a point.

  A point's neighborhood is the n-dimensional hypercube with sides ranging
  [center - radius, center + radius], inclusive. For example, if there are two
  dimensions and the radius is 3, the neighborhood is 6x6. Neighborhoods are
  truncated when they are near an edge.

  This is designed to be fast. In C++ it's fastest to iterate through neighbors
  one by one, calculating them on-demand rather than creating a list of them.
  But in Python it's faster to build up the whole list in batch via a few calls
  to C code rather than calculating them on-demand with lots of calls to Python
  code.

  :param centerIndex: (int) The index of the point. The coordinates are
         expressed as a single index by using the dimensions as a mixed radix
         definition. For example, in dimensions 42x10, the point [1, 4] is index
         1*420 + 4*10 = 460.

  :param radius: (int) The radius of this neighborhood about the
         ``centerIndex``.

  :param dimensions: (indexable sequence) The dimensions of the world outside
         this neighborhood.

  :returns: (numpy array) The points in the neighborhood, including
            ``centerIndex``.
  """
  centerPosition = coordinatesFromIndex(centerIndex, dimensions)

  intervals = []
  for i, dimension in enumerate(dimensions):
    left = max(0, centerPosition[i] - radius)
    right = min(dimension - 1, centerPosition[i] + radius)
    intervals.append(xrange(left, right + 1))

  coords = numpy.array(list(itertools.product(*intervals)))
  return numpy.ravel_multi_index(coords.T, dimensions)


from logging import debug
from flask import Flask, render_template, request
from werkzeug.utils import redirect
from flask_mysqldb import MySQL
import MySQLdb.cursors

app=Flask(__name__)

app.config['MYSQL_HOST']="localhost"
app.config['MYSQL_USER']="root"
app.config['MYSQL_PASSWORD']=""
app.config['MYSQL_DB']="mycrud"
mysql=MySQL(app)

@app.route('/')
def fetch():
    cursor=mysql.connection.cursor(MySQLdb.cursors.DictCursor)
    cursor.execute("select * from details")
    data=cursor.fetchall()
    # print(data)
    return render_template("my.html",data=data)

@app.route('/',methods=['GET', 'POST'])
def insert():
    # check methods
    if(request.method=="POST"):
        # getting details from html
        details=request.form
        name=details['name']
        hobby=details['hobby']
        cur=mysql.connection.cursor()
        cur.execute("INSERT INTO details(name, hobby) VALUES (%s, %s)", (name, hobby))
        mysql.connection.commit()
        cur.close()
        return "Success!"

    return render_template('my.html')

@app.route('/delete/<int:id>')
def delete(id):
    cur=mysql.connection.cursor()
    cur.execute("DELETE FROM details WHERE id='%s'"%id)

    print(id)
    mysql.connection.commit()
    cur.close()
    return redirect('/')

@app.route('/update/<int:id>',methods=['GET', 'POST'])
def update(id):
    cur=mysql.connection.cursor()

    if(request.method=="POST"):

        # getting details from html
        detailss=request.form
        hobby=detailss['hobby']
        print(hobby)
        cur=mysql.connection.cursor()
        cur.execute("UPDATE `details` SET `hobby`=%s WHERE `id`=%s",(hobby, id))
        mysql.connection.commit()
        cur.close()
        return redirect('/')
    return render_template("new.html",id=id)

if __name__=='__main__':
    app.run(debug=True)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import math

from tensorflow.contrib.framework.python.framework import tensor_util as contrib_tensor_util  # pylint: disable=line-too-long
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import tensor_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import constant_op
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops

# TODO(ebrevdo): Use asserts contrib module when ready
def _assert_all_positive(x):
  return logging_ops.Assert(
      math_ops.reduce_all(x > 0),
      ["Tensor %s should contain only positive values: " % x.name, x])

class Gaussian(object):
  """The scalar Gaussian distribution with mean and stddev parameters mu, sigma.

  #### Mathematical details

  The PDF of this distribution is:

  ```f(x) = sqrt(1/(2*pi*sigma^2)) exp(-(x-mu)^2/(2*sigma^2))```

  #### Examples

  Examples of initialization of one or a batch of distributions.

  ```python
  # Define a single scalar Gaussian distribution.
  dist = tf.contrib.distributions.Gaussian(mu=0, sigma=3)

  # Evaluate the cdf at 1, returning a scalar.
  dist.cdf(1)

  # Define a batch of two scalar valued Gaussians.
  # The first has mean 1 and standard deviation 11, the second 2 and 22.
  dist = tf.contrib.distributions.Gaussian(mu=[1, 2.], sigma=[11, 22.])

  # Evaluate the pdf of the first distribution on 0, and the second on 1.5,
  # returning a length two tensor.
  dist.pdf([0, 1.5])

  # Get 3 samples, returning a 3 x 2 tensor.
  dist.sample(3)
  ```

  Arguments are broadcast when possible.

  ```python
  # Define a batch of two scalar valued Gaussians.
  # Both have mean 1, but different standard deviations.
  dist = tf.contrib.distributions.Gaussian(mu=1, sigma=[11, 22.])

  # Evaluate the pdf of both distributions on the same point, 3.0,
  # returning a length 2 tensor.
  dist.pdf(3.0)
  ```

  """

  def __init__(self, mu, sigma, name=None):
    """Construct Gaussian distributions with mean and stddev `mu` and `sigma`.

    The parameters `mu` and `sigma` must be shaped in a way that supports
    broadcasting (e.g. `mu + sigma` is a valid operation).

    Args:
      mu: `float` or `double` tensor, the means of the distribution(s).
      sigma: `float` or `double` tensor, the stddevs of the distribution(s).
        sigma must contain only positive values.
      name: The name to give Ops created by the initializer.

    Raises:
      TypeError: if mu and sigma are different dtypes.
    """
    with ops.op_scope([mu, sigma], name, "Gaussian"):
      mu = ops.convert_to_tensor(mu)
      sigma = ops.convert_to_tensor(sigma)
      with ops.control_dependencies([_assert_all_positive(sigma)]):
        self._mu = array_ops.identity(mu, name="mu")
        self._sigma = array_ops.identity(sigma, name="sigma")

    contrib_tensor_util.assert_same_float_dtype((mu, sigma))

  @property
  def dtype(self):
    return self._mu.dtype

  @property
  def mu(self):
    return self._mu

  @property
  def sigma(self):
    return self._sigma

  @property
  def mean(self):
    return self._mu * array_ops.ones_like(self._sigma)

  def log_pdf(self, x, name=None):
    """Log pdf of observations in `x` under these Gaussian distribution(s).

    Args:
      x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
      name: The name to give this op.

    Returns:
      log_pdf: tensor of dtype `dtype`, the log-PDFs of `x`.
    """
    with ops.op_scope([self._mu, self._sigma, x], name, "GaussianLogPdf"):
      x = ops.convert_to_tensor(x)
      if x.dtype != self.dtype:
        raise TypeError("Input x dtype does not match dtype: %s vs. %s"
                        % (x.dtype, self.dtype))
      log_2_pi = constant_op.constant(math.log(2 * math.pi), dtype=self.dtype)
      return (-0.5*log_2_pi - math_ops.log(self._sigma)
              -0.5*math_ops.square((x - self._mu) / self._sigma))

  def cdf(self, x, name=None):
    """CDF of observations in `x` under these Gaussian distribution(s).

    Args:
      x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
      name: The name to give this op.

    Returns:
      cdf: tensor of dtype `dtype`, the CDFs of `x`.
    """
    with ops.op_scope([self._mu, self._sigma, x], name, "GaussianCdf"):
      x = ops.convert_to_tensor(x)
      if x.dtype != self.dtype:
        raise TypeError("Input x dtype does not match dtype: %s vs. %s"
                        % (x.dtype, self.dtype))
      return (0.5 + 0.5*math_ops.erf(
          1.0/(math.sqrt(2.0) * self._sigma)*(x - self._mu)))

  def log_cdf(self, x, name=None):
    """Log CDF of observations `x` under these Gaussian distribution(s).

    Args:
      x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
      name: The name to give this op.

    Returns:
      log_cdf: tensor of dtype `dtype`, the log-CDFs of `x`.
    """
    with ops.op_scope([self._mu, self._sigma, x], name, "GaussianLogCdf"):
      return math_ops.log(self.cdf(x))

  def pdf(self, x, name=None):
    """The PDF of observations in `x` under these Gaussian distribution(s).

    Args:
      x: tensor of dtype `dtype`, must be broadcastable with `mu` and `sigma`.
      name: The name to give this op.

    Returns:
      pdf: tensor of dtype `dtype`, the pdf values of `x`.
    """
    with ops.op_scope([self._mu, self._sigma, x], name, "GaussianPdf"):
      return math_ops.exp(self.log_pdf(x))

  def entropy(self, name=None):
    """The entropy of Gaussian distribution(s).

    Args:
      name: The name to give this op.

    Returns:
      entropy: tensor of dtype `dtype`, the entropy.
    """
    with ops.op_scope([self._mu, self._sigma], name, "GaussianEntropy"):
      two_pi_e1 = constant_op.constant(
          2 * math.pi * math.exp(1), dtype=self.dtype)
      # Use broadcasting rules to calculate the full broadcast sigma.
      sigma = self._sigma * array_ops.ones_like(self._mu)
      return 0.5 * math_ops.log(two_pi_e1 * math_ops.square(sigma))

  def sample(self, n, seed=None, name=None):
    """Sample `n` observations from the Gaussian Distributions.

    Args:
      n: `Scalar`, type int32, the number of observations to sample.
      seed: Python integer, the random seed.
      name: The name to give this op.

    Returns:
      samples: `[n, ...]`, a `Tensor` of `n` samples for each
        of the distributions determined by broadcasting the hyperparameters.
    """
    with ops.op_scope([self._mu, self._sigma, n], name, "GaussianSample"):
      broadcast_shape = (self._mu + self._sigma).get_shape()
      n = ops.convert_to_tensor(n)
      shape = array_ops.concat(
          0, [array_ops.pack([n]), array_ops.shape(self.mean)])
      sampled = random_ops.random_normal(
          shape=shape, mean=0, stddev=1, dtype=self._mu.dtype, seed=seed)

      # Provide some hints to shape inference
      n_val = tensor_util.constant_value(n)
      final_shape = tensor_shape.vector(n_val).concatenate(broadcast_shape)
      sampled.set_shape(final_shape)

      return sampled * self._sigma + self._mu


import logging
import time
from queue import Queue
from threading import Thread

import boto3

logger = logging.getLogger(__name__)

class GetTagWorker(Thread):

    def __init__(self, queue, result, sqs):
        super().__init__()
        self.queue = queue
        self.result = result
        self.sqs = sqs

    def run(self):
        while True:
            url = self.queue.get()
            try:
                tags = self.sqs.list_queue_tags(QueueUrl=url)
                self.result[url.split('/')[4]] = tags
            finally:
                self.queue.task_done()

def check_no_tags(d):
    no_tags = []
    for a, i in d.items():
        if i is None:
            no_tags.append(a)

    print('no tags {}'.format(len(no_tags)))

def timming(f):
    def some_function(*args, **kwargs):
        t1 = time.time()
        aux = f(*args, **kwargs)
        print(f"{f.__name__} se demoro {time.time() - t1}")
        return aux

    return some_function

@timming
def get_queue_list(sqs):
    return sqs.list_queues()

@timming
def get_tags(queues, sqs):
    for url in queues:
        tags = sqs.list_queue_tags(QueueUrl=url)
        yield url, tags

def get_queue_by_filter(tags, filter):
    return {key: value for (key, value) in tags if filter(key, value)}

@timming
def main():
    sqs = boto3.client('sqs')

    # List SQS queues

    thread_queue = Queue()
    queues = get_queue_list(sqs)

    for url in queues.get('QueueUrls'):
        thread_queue.put(url)

    result = {}

    dev_queues = {}
    cl_queues = {}
    mx_queues = {}
    col_queues = {}
    arg_queues = {}
    ec_queues = {}
    es_queues = {}
    br_queues = {}
    pa_queues = {}
    pe_queues = {}

    no_tag_queues = {}
    others_queues = {}

    for i in range(10):
        thread = GetTagWorker(thread_queue, result, sqs)
        thread.daemon = True
        thread.start()

    thread_queue.join()

    dev_queues = get_queue_by_filter(result.items(), lambda key, value: key.find('dev-') == 0)
    cl_queues = get_queue_by_filter(result.items(),
                                    lambda key, value: key.find('-cl-') != -1 and not (key.find('dev') == 0))

    mx_queues = get_queue_by_filter(result.items(),
                                    lambda key, value: key.find('-mx-') != -1 and not (key.find('dev') == 0))

    col_queues = get_queue_by_filter(result.items(),
                                     lambda key, value: key.find('-co-') != -1 and not (key.find('dev') == 0))

    for key, value in result.items():
        if key.find('-ar-') != -1 and not (key.find('dev') == 0):
            arg_queues[key] = value

    for key, value in result.items():
        if key.find('-ec-') != -1 and not (key.find('dev') == 0):
            ec_queues[key] = value

    for key, value in result.items():
        if key.find('-es-') != -1 and not (key.find('dev') == 0):
            es_queues[key] = value

    for key, value in result.items():
        if key.find('-br-') != -1 and not (key.find('dev') == 0):
            br_queues[key] = value

    for key, value in result.items():
        if key.find('-pa-') != -1 and not (key.find('dev') == 0):
            pa_queues[key] = value

    for key, value in result.items():
        if key.find('-pe-') != -1 and not (key.find('dev') == 0):
            pe_queues[key] = value

    for key, value in result.items():
        if value is None:
            no_tag_queues[key] = value

    for key, value in result.items():
        if key.find('-pe-') == -1 \
                and not (key.find('dev-') == 0) \
                and key.find('-ec-') == -1 \
                and key.find('-cl-') == -1 \
                and key.find('-ar-') == -1 \
                and key.find('-br-') == -1 \
                and key.find('-pa-') == -1 \
                and key.find('-es-') == -1 \
                and key.find('-co-') == -1 \
                and key.find('-mx-') == -1:
            others_queues[key] = value

    print("Total {}".format(len(result)))

    print("devs {}".format(len(dev_queues)))
    check_no_tags(dev_queues)

    print("CL {}".format(len(cl_queues)))
    check_no_tags(cl_queues)

    print("AR {}".format(len(arg_queues)))
    check_no_tags(arg_queues)

    print("COL {}".format(len(col_queues)))
    check_no_tags(col_queues)

    print("EC {}".format(len(ec_queues)))
    check_no_tags(ec_queues)

    print("EEUU {}".format(len(es_queues)))
    check_no_tags(es_queues)
    print("BR {}".format(len(br_queues)))
    check_no_tags(br_queues)

    print("MX {}".format(len(mx_queues)))
    check_no_tags(mx_queues)

    print("PE {}".format(len(pe_queues)))
    check_no_tags(pe_queues)

    print("PA {}".format(len(pa_queues)))
    check_no_tags(pa_queues)

    print("others {}".format(len(others_queues)))
    check_no_tags(others_queues)

    print("Without tags {}".format(len(no_tag_queues)))

    print("all = {} ".format(
        (len(dev_queues) + len(cl_queues)) + len(arg_queues) + len(col_queues) + len(ec_queues) + len(es_queues) + len(
            br_queues) + len(mx_queues) + len(pe_queues) + len(pa_queues) + len(others_queues)))

if "__main__" == __name__:
    main()


import asyncio
import pytest
from asynctest import MagicMock, CoroutineMock
from kutana import Context

def test_reply_non_str():
    ctx = Context(backend=MagicMock(execute_send=CoroutineMock()))
    ctx.default_target_id = 1
    asyncio.get_event_loop().run_until_complete(ctx.reply(123))
    ctx.backend.execute_send.assert_called_with(1, "123", (), {})

def test_reply_no_default_target():
    ctx = Context(backend=MagicMock(execute_send=CoroutineMock()))
    ctx.default_target_id = None

    with pytest.raises(RuntimeError):
        asyncio.get_event_loop().run_until_complete(ctx.reply("hey"))

    ctx.backend.execute_send.assert_not_called()

def test_context():
    called = []

    class Backend:
        async def execute_send(self, target_id, message, attachments, kwargs):
            called.append(("ps", message))

        async def execute_request(self, method, kwargs):
            called.append(("pac", method, kwargs))

    ctx = Context(backend=Backend())
    ctx.default_target_id = 1

    asyncio.get_event_loop().run_until_complete(ctx.reply("hey1"))
    asyncio.get_event_loop().run_until_complete(ctx.send_message(1, "hey2"))
    asyncio.get_event_loop().run_until_complete(ctx.request("a", v="hey3"))

    assert called == [
        ("ps", "hey1"),
        ("ps", "hey2"),
        ("pac", "a", {"v": "hey3"}),
    ]

    called.clear()

    message = "a" * 4096 + "b" * 4096 + "c" * 4096

    asyncio.get_event_loop().run_until_complete(ctx.reply(message))

    assert called == [
        ("ps", message[:4096]),
        ("ps", message[4096: 4096 * 2]),
        ("ps", message[4096 * 2:]),
    ]

def test_lont_message_for_kwargs():
    ctx = Context(backend=CoroutineMock(execute_send=CoroutineMock()))
    ctx.default_target_id = 1

    asyncio.get_event_loop().run_until_complete(ctx.reply("a" * (4096 * 2 - 1)))

    ctx.backend.execute_send.assert_any_await(1, "a" * 4096, (), {})
    ctx.backend.execute_send.assert_any_await(1, "a" * 4095, (), {})

def test_dynamic_attributes():
    ctx = Context()

    ctx.var1 = "val1"
    ctx.var2 = "val2"

    assert ctx.var1 == "val1"
    assert ctx.var2 == "val2"
    assert ctx.get("var3") is None
    assert ctx.get("var3", "default_value_1") == "default_value_1"

def test_replace_method():
    calls = []

    async def replacement(self, message, attachments=(), **kwargs):
        calls.append((message, attachments, kwargs))

    ctx = Context()
    ctx.replace_method("reply", replacement)
    asyncio.get_event_loop().run_until_complete(ctx.reply("hey"))

    assert calls == [("hey", (), {})]

    with pytest.raises(ValueError):
        ctx.replace_method("a" * 64, lambda: 0)


import requests
from bs4 import BeautifulSoup
import subprocess

# This is the file that takes care of playing podcasts on my pi.
# As of now I only have it for The Daily, but an be used for any RSS audio feed.
# I use a get request to grab the audio from the feed then save it to an mp3 file,
# create a subprocess and have that thread play the podcast.

running = False
daily = ""

def start_daily():
    feeduUrl = "https://rss.art19.com/the-daily"
    feed = requests.get(feeduUrl).content
    parser = BeautifulSoup(feed,'xml')
    episodes = parser.findAll("item")
    recentPodcast = episodes[0]
    url = str(recentPodcast.enclosure['url'])
    response = requests.get(url)
    data = response.content
    mp3Name = "daily.mp3"
    song = open(mp3Name, "wb")
    song.write(data)
    song.close()
    global daily
    daily = subprocess.Popen(["mpg321", "-R", 'anyword'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    daily.stdin.write("L daily.mp3\n")
    global running
    running = True

def play():
    if running is False:
        if daily is not "":
            daily.stdin.write("P\n")
            global running
            running = True

def pause():
    if running is True:
        if daily is not "":
            daily.stdin.write("P\n")
            global running
            running = False

def quit():
    global daily
    if daily is not "":
        global daily
        daily.stdin.write("Q\n")
        global running
        running = False
        global daily
        daily = ""

def interpret(r):
    if "daily" in r:
        start_daily()
    elif daily != "":
        if "play" in r:
            play()
        elif "pause" in r or "stop" in r:
            pause()
        elif "quit" in r:
            quit()
        else:
            return "Sorry, I could not understand your request."
    else:
        return "Sorry, I could not understand your request. You do not have a podcast running."

def playing():
    global running
    return running


import sys
import math

def groupby(arr, s=8):
    while len(arr) > 0:
        yield [str(x) for x in arr[:8]]
        arr = arr[8:]

def binary_to_ip(binary_ip):
    ip = []
    for g in groupby(binary_ip):
        decimal = int("".join(g), 2)
        ip.append( str(decimal) )
    return ".".join(ip)

def ip_to_binary(ip):
    chunk = [int(x) for x in ip.split(".")]
    binary_ip = ["{0:08b}".format(x) for x in chunk]
    binary_array = [int(y) for x in binary_ip for y in x]
    return binary_array

def mask_to_binary(mask):
    mask = int(mask)
    binary_mask = [1] * mask + [0] * (32 - mask)
    return binary_mask

ip, mask = input().split("/")

binary_ip = ip_to_binary(ip)
binary_mask = mask_to_binary(mask)

print(binary_ip, file=sys.stderr)
print(binary_mask, file=sys.stderr)

# "network address"
network_binary = [value * mask for value, mask in zip(binary_ip, binary_mask)]
broadcast_binary = [value if mask == 1 else 1 for value, mask in zip(binary_ip, binary_mask)]

print(network_binary, file=sys.stderr)
print(broadcast_binary, file=sys.stderr)

network_address = binary_to_ip(network_binary)
broadcast_address = binary_to_ip(broadcast_binary)

print(network_address)
print(broadcast_address)


class Matrix:
  def __init__(self, matrix: list[list]) -> None:
    is_matrix = self.__validate_matrix(matrix)

    if not is_matrix:
      raise Exception('Invalid matrix')

    self.matrix = matrix
    self.matrix_len = len(matrix)

  def __validate_matrix(self, matrix: list[list]) -> bool:
    for row in matrix:
      if len(row) != len(matrix[0]):
        return False

    return True

  def __is_submatrix(self, submatrix: list[list], i: int, j: int) -> bool:
    for row in range(len(submatrix)):
      for col in range(len(submatrix)):
        if self.matrix[i + row][j + col] != submatrix[row][col]:
          return False

    return True

  def count_submatrix(self, submatrix: list[list]) -> int:
    if not self.__validate_matrix(submatrix):
      raise Exception('Invalid submatrix')

    submatrix_len = len(submatrix)
    count = 0

    for i in range(self.matrix_len - submatrix_len + 1):
      for j in range(self.matrix_len - submatrix_len + 1):
        if self.__is_submatrix(submatrix, i, j):
          count += 1

    return count


def moar(a,b,n):
	sum1 = 0
	sum2 = 0
	for i in a:
		if i%n==0:
			sum1 += 1
	for i in b:
		if i%n==0:
			sum2 += 1
	if sum1>sum2:
		return True
	else:
		return False


import tensorflow as tf
import numpy as np
import math

def conv_module(input_, n_filters, training, name, pool=True, activation=tf.nn.relu,
                padding='same', batch_norm=True):
    """{Conv -> BN -> RELU} x 2 -> {Pool, optional}
        reference : https://github.com/kkweon/UNet-in-Tensorflow
    Args:
        input_ (4-D Tensor): (batch_size, H, W, C)
        n_filters (int): depth of output tensor
        training (bool): If True, run in training mode
        name (str): name postfix
        pool (bool): If True, MaxPool2D after last conv layer
        activation: Activaion functions
        padding (str): 'same' or 'valid'
        batch_norm (bool) : If True, use batch-norm
    Returns:
        u_net: output of the Convolution operations
        pool (optional): output of the max pooling operations
    """
    kernel_sizes = [3,3]
    net = input_
    with tf.variable_scope("conv_module_{}".format(name)):
        for i, k_size in enumerate(kernel_sizes):
            net = tf.layers.conv2d(net, n_filters, (k_size, k_size), activation=None, padding=padding,
                                   name="conv_{}".format(i + 1))

            if batch_norm:
                net = tf.layers.batch_normalization(net, training=training, renorm=True,
                                                    name="bn_{}".format(i + 1))
            net = activation(net, name="relu_{}".format(i + 1))

        if pool is False:
            return net

        pool = tf.layers.max_pooling2d(net, (2, 2), strides=(2, 2), name="pool")

        return net, pool

def upsample(input_, name, upscale_factor=(2,2)):
    H, W, _ = input_.get_shape().as_list()[1:]

    target_H = H * upscale_factor[0]
    target_W = W * upscale_factor[1]

    return tf.image.resize_nearest_neighbor(input_, (target_H, target_W), name="upsample_{}".format(name))


#!/usr/bin/python
# coding: UTF-8
# mylist = [1, 4, -5, 10, -7, 2, 3, -1]
# print [n for n in mylist if n > 0]
# print [n for n in mylist if n < 0]
# pos = (n for n in mylist if n > 0)
# print pos
# print list(pos)
# for x in pos:
#     print x

values = ['1', '2', '-3', '-', '4', 'N/A', '5']

def is_int(val):
    try:
        x = int(val)
        return True
    except ValueError:
        return False

values = list(filter(is_int, values))
print(values)


"""
给定一组不含重复元素的整数数组 nums，返回该数组所有可能的子集（幂集）。
"""

def subsets(nums):
    if not nums:
        return [[]]
    if len(nums) == 1:
        return [nums, []]
    res = [[]]
    for i in range(len(nums)):
        tmp = subsets(nums[i+1:])
        for j in tmp:
            j.insert(0, nums[i])
            res.append(j)

    return res

if __name__ == '__main__':
    print(subsets([1, 2, 3]))


def solution(routes):
    answer = 0
    visited = [0]*len(routes)

    routes.sort()   # 시작 지점으로 정렬

    # 첫번재 구간 방문
    visited[0] = 1
    answer += 1
    start, end = routes[0][0], routes[0][1]

    while sum(visited) != len(routes):
        for idx in range(1, len(routes)):
            if start <= routes[idx][0] <= end:    # 겹치는 구간이 있다면
                visited[idx] = 1
                # 새로운 겹치는 구간 설정
                if routes[idx][0] > start:
                    start = routes[idx][0]
                if routes[idx][1] < end:
                    end = routes[idx][1]
            else:   # 더 이상 겹치는 구간이 안나오면 새로운 구간으로 탐색
                start, end = routes[idx][0], routes[idx][1]
                visited[idx] = 1
                answer += 1

    return answer

def solution2(routes):
    routes = sorted(routes, key=lambda x: x[1]) # 종료지점으로 정렬
    last_camera = -30000    # 도로의 최소 값
    answer = 0

    for route in routes:
        # 시작 지점이 마지막 카메라가 있는 지점보다 크다면
        # 카메라가 해당 구간을 지나가는 차를 못봄
        if last_camera < route[0]:
            answer += 1     # 카메라 추가
            last_camera = route[1]  # 카메라 위치는 해당 구간의 마지막 위치

    return answer

print(solution2([[-20,15], [-14,-5], [-18,-13], [-5,-3]]))   # 2


import pyupbit
import numpy as np

def get_ror(k=0.3):
    df = pyupbit.get_ohlcv("KRW-BTT", count=28)
    df['range'] = (df['high'] - df['low']) * k
    df['target'] = df['open'] + df['range'].shift(1)

    fee = 0.0005
    df['ror'] = np.where(df['high'] > df['target'],
                         df['close'] / df['target'] - fee,
                         1)

    ror = df['ror'].cumprod()[-2]
    return ror

for k in np.arange(0.1, 1.0, 0.1):
    ror = get_ror(k)
    print("%.1f %f" % (k, ror))

    # 04월 26일 기준 / fee 없이
    # 14일 - k값 0.3 일 때 하락장 시작 / 04월 13일 ~ 04월 26일 - 하락장이였음
    # 21일 - k값 0.5 일 때 하락장 시작 / 04월 06일 ~ 04월 26일 - 하락장이였음
    # 28일 - k값 0.4 일 때 이 때는 상승장 / 03월 30일 ~ 04월 26일
    # 하락장일 땐 k 값은 0.3

  # 04월 26일 기준 / fee
    # 14일 - k값 0.3 일 때 하락장 시작 / 04월 13일 ~ 04월 26일 - 하락장이였음
    # 21일 - k값 0.5 일 때 하락장 시작 / 04월 06일 ~ 04월 26일 - 하락장이였음
    # 28일 - k값 0.4 일 때 이 때는 상승장 / 03월 30일 ~ 04월 26일
    # 하락장일 땐 k 값은 0.3


import operators

print("select")
print("1.add")
print("2.substract")
print("3.multiply")
print("4.divide")
print("5.power")

choice=input("enter choice 1/2/3/4/5 :")

x=(int(input("enter 1st")))

y=(int(input("enter 2nd value")))

if choice == "1":
    operators.add(x,y)

elif choice == "2":
    operators.subtract(x,y)

elif choice== "3":
    operators.multiply(x,y)

elif choice== "4":
    operators.divide(x,y)

elif choice== "5":
    operators.power(x,y)

else:
    print("invalid")


import numpy as np
from svm import SMO
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix

if __name__ == "__main__":
    dataurl = 'https://archive.ics.uci.edu/ml/machine-learning-databases/letter-recognition/letter-recognition.data'
    X = np.genfromtxt(dataurl, delimiter=',', usecols=range(1, 17))
    y = np.genfromtxt(dataurl, delimiter=',', usecols=[0], dtype=np.str_)
    y = np.where(y == 'C', 1, -1)
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)

    acc_list = []
    p_list = []
    C_list = np.logspace(-1, 2, 4)
    gamma_list = np.logspace(-1, 2, 4)
    for C in C_list:
        for gamma in gamma_list:
            clf = SMO(C=C, tol=0.01, kernel='', gamma=gamma)
            clf.train(X_train, y_train)
            y_pred = clf.predict(X_test)
            accuracy = accuracy_score(y_test, y_pred)
            acc_list.append(accuracy)
            p_list.append((C, gamma))
    idx = np.argmax(acc_list)
    print(p_list[idx])
    print(f'best accuracy:{acc_list[idx]}')


"""
Module of Credit mining function testing.

Author(s): Mihai Capota, Ardhi Putra
"""

from binascii import unhexlify, hexlify
from twisted.internet import reactor

from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import deferLater

from Tribler.Core.CreditMining.CreditMiningSource import ChannelSource
from Tribler.Core.simpledefs import NTFY_CHANNELCAST, NTFY_DISCOVERED, NTFY_TORRENT
from Tribler.community.allchannel.community import AllChannelCommunity
from Tribler.community.channel.community import ChannelCommunity
from Tribler.Test.test_as_server import TestAsServer

class TestCreditMiningSources(TestAsServer):
    """
    Class to test the credit mining sources
    """

    def __init__(self, *argv, **kwargs):
        super(TestCreditMiningSources, self).__init__(*argv, **kwargs)
        # Fake channel id for testing
        self.cid = '0' * 40

    def setUpPreSession(self):
        super(TestCreditMiningSources, self).setUpPreSession()
        self.config.set_megacache_enabled(True)
        self.config.set_dispersy_enabled(True)
        self.config.set_channel_search_enabled(True)

    def test_channel_lookup(self):
        source = ChannelSource(self.session, self.cid, lambda: None)
        source.start()
        self.assertIsInstance(source.community, ChannelCommunity, 'ChannelSource failed to create ChannelCommunity')
        source.stop()

    def test_existing_channel_lookup(self):
        # Find AllChannel
        for community in self.session.lm.dispersy.get_communities():
            if isinstance(community, AllChannelCommunity):
                allchannelcommunity = community

        # Load the channel
        community = ChannelCommunity.init_community(self.session.lm.dispersy,
                                                    self.session.lm.dispersy.get_member(mid=unhexlify(self.cid)),
                                                    allchannelcommunity.my_member,
                                                    self.session)

        # Check if we find the channel
        source = ChannelSource(self.session, self.cid, lambda: None)
        source.start()
        self.assertEqual(source.community, community, 'ChannelSource failed to find existing ChannelCommunity')
        source.stop()

    @inlineCallbacks
    def test_torrent_from_db(self):
        # Torrent is a tuple: (channel_id, dispersy_id, peer_id, infohash, timestamp, name, files, trackers)
        torrent = (0, self.cid, 42, '\00' * 20, 0, u'torrent', [], [])
        channel_db_handler = self.session.open_dbhandler(NTFY_CHANNELCAST)
        channel_db_handler.on_torrents_from_dispersy([torrent])

        torrent_inserteds = []
        torrent_insert_callback = lambda source, infohash, name: torrent_inserteds.append((source, infohash, name))
        source = ChannelSource(self.session, self.cid, torrent_insert_callback)
        source.start()

        yield deferLater(reactor, 1, lambda: None)
        self.assertIn((self.cid, hexlify(torrent[3]), torrent[5]), torrent_inserteds,
                      'ChannelSource failed to insert torrent')

        source.stop()

    def test_torrent_discovered(self):
        torrent_inserteds = []
        torrent_insert_callback = lambda source, infohash, name: torrent_inserteds.append((source, infohash, name))
        source = ChannelSource(self.session, self.cid, torrent_insert_callback)
        source.start()

        source.on_torrent_discovered(NTFY_TORRENT, NTFY_DISCOVERED, self.cid, {'dispersy_cid': self.cid,
                                                                               'infohash': '\00' * 20,
                                                                               'name': 'torrent'})
        self.assertIn((self.cid, '\00' * 20, 'torrent'), torrent_inserteds, 'ChannelSource failed to insert torrent')

        source.on_torrent_discovered(NTFY_TORRENT, NTFY_DISCOVERED, self.cid, {'dispersy_cid': '1' * 40,
                                                                               'infohash': '\01' * 20,
                                                                               'name': 'torrent'})
        self.assertTrue(len(torrent_inserteds) == 1, 'ChannelSource inserted torrent with wrong dispersy_cid')

        source.stop()


import tqdm
import pandas as pd
import numpy as np
from pandas.api.types import is_bool_dtype, is_numeric_dtype
# from essential import *
from fastpreprocess.essential import *

class NumericDetail(BaseModel):
    data: TypeVar('pandas.core.series.Series')
    vname: str
    vmissing: Union[List, None]
    vtype: str
    vsummary: Tuple[List, List]
    vstat: TypeVar('pandas.core.frame.DataFrame')
    voutlier_track: Union[List, None]
    vhtmlid: Tuple[int, int]

    def boxplot_json(self):
        stat = (self.vstat.iloc[[3, 4, 5, 6,7]].values).flatten().astype(int).tolist()
        # if self.voutlier_track is None:
        json = [{'name': self.vname, 'type': 'boxPlot', 'data': [{'x': self.vname, 'y': stat}]}]
        return json
        # json = [{'name': self.vname, 'type': 'boxPlot', 'data': [{'x': self.vname, 'y': stat}]}, self.outlier_json()]
        # return json

    def outlier_json(self):
        json = {'name': 'outliers',
                'type': 'scatter',
                'data': [{'x': self.vname, 'y': list(set(self.voutlier_track))}]}
        return json

    def distribution_json(self):
        hist = np.histogram(self.data.dropna().values)
        counter = hist[0].astype(int).tolist()
        categ = np.round(hist[1], 2).astype(str).tolist()
        return {'data': counter, 'categories': categ}

    def get_stat(self):
        stat = {'Facts': {'VType': self.vtype, 'TotalMissing': self.vmissing,
                         'Outlier Count': len(self.voutlier_track)},

                'Summary': {'Number_of_observations': self.vsummary[1][0],
                            'Mean': self.vsummary[1][1],
                            'Standard_Deviation': self.vsummary[1][2],
                            'Minimum': self.vsummary[1][3],
                            'Quartile_1': self.vsummary[1][4],
                            'Median': self.vsummary[1][5],
                            'Quartile 2': self.vsummary[1][6],
                            'Maximum': self.vsummary[1][7],
                            'Skewness': self.vsummary[1][8],
                            'Kurtosis': self.vsummary[1][9]
                        },
                'Distribution': self.distribution_json(),
                'Boxplot': self.boxplot_json()
                }
        return stat

class CategoricalDetail(BaseModel):
    vname: str
    vmissing: Union[List, None]
    vtype: Any
    vsummary: Tuple[List, List]
    vstat: TypeVar('pandas.core.frame.DataFrame')
    vhtmlid: Tuple[int, int]
    vnunique: int
    vnuniquevalues: Set[Any]
    vmostcommon: Tuple[List, List, List]

    def barplot_json(self):
        return  {'categories': self.vmostcommon[0], 'data': self.vmostcommon[2]}

    def get_stat(self):
        stat = {'MostCommon': {'categories': self.vmostcommon[0][:2], 'data': self.vmostcommon[2][:2]},
               'Summary': {
                            'Number_of_observations': str(self.vsummary[1][0]),
                            'Number_of_u0nique_values': str(self.vsummary[1][1]),
                            'Highest_occuring_values': str(self.vsummary[1][2]),
                            'Total_Missing': self.vmissing},
                'BarPlot': self.barplot_json()
            }
        return stat

class IndividualVariables(BaseModel):
    TotalNumeric: int = 0
    TotalCategorical: int = 0
    Length: int = 0
    Missing: int = 0
    Shape: Tuple[int, int] = (0, 0)
    Variables: List[Union[NumericDetail, CategoricalDetail]] = []
    VariableName: List[str] = []

class IndividualVariable():

    def __init__(self, data: TypeVar('pandas.core.frame.DataFrame')):
        self.data = data
        self.IV = IndividualVariables(Missing = self.data.isna().sum().values.sum()
                            , Shape = self.data.shape)

    def outlier(self, v, i):
        df = self.data
        q1q2 = v.statistics.iloc[[4,6]].values.flatten()
        IQR = q1q2[1] - q1q2[0]
        outlier = df[i][(df[i] < (q1q2[0] - 1.5 * IQR)) |(df[i] > (q1q2[1] + 1.5 * IQR))].values
        return (outlier.astype(int)).tolist()

    def start(self):
        for i in tqdm.tqdm(self.data.columns, desc="Analysing"):
            v = Bivariate(self.data[i])
            if v.var_type == 'numeric':
                self.IV.TotalNumeric += 1
                var = NumericDetail(
                            data = self.data[i], vname=i, vmissing=v.missing, vtype=v.var_type,
                            vsummary=(v.statistics.index.to_list(), v.statistics.values.flatten().tolist()),
                            vstat=v.statistics, voutlier_track=self.outlier(v, i),
                            vhtmlid=(self.IV.Length, self.IV.Length)
                    )

            if v.var_type == 'categorical':
                self.IV.TotalCategorical += 1
                var = CategoricalDetail(
                            vname=i, vmissing=v.missing, vtype=v.var_type,
                            vsummary=(v.statistics.index.to_list(),  v.statistics.values.flatten().tolist()),
                            vstat=v.statistics, vhtmlid=(self.IV.Length, self.IV.Length), vnunique = v.num_unique,
                            vnuniquevalues = v.unique, vmostcommon = v.most_common_items
                    )

            self.IV.Variables.append(var)
            self.IV.Length += 1
            self.IV.VariableName.append(i)

        assert self.IV.Length == len(self.data.columns), "Length counter value and total number of columns is different"

class Bivariate:

    def __init__(self, data):
        self.data = data
        self.var_type = self.variable_type()
        self.statistics = self.summary()
        self.num_unique = self.data.nunique()
        self.unique = set(self.data.unique())
        self.missing = self.missing_value()

    def variable_type(self):
        if is_numeric_dtype(self.data) and not is_bool_dtype(self.data):
            # Only int and float types
            return 'numeric'
        else:
            # Handle bool, string, datetime, etc as categorical
            self.data = self.data.astype('category')
            return 'categorical'

    def summary(self):

        if self.var_type == 'numeric':
            return self.numerical_summary()
        elif self.var_type == 'categorical':
            return self.categorical_summary()

    def numerical_summary(self):

        summary = self.data.describe()
        summary.index = [
            'Number of observations', 'Average', 'Standard Deviation',
            'Minimum', 'Lower Quartile', 'Median', 'Upper Quartile', 'Maximum'
        ]
        summary['Skewness'] = self.data.skew()
        summary['Kurtosis'] = self.data.kurt()
        return summary.round(3).to_frame()

    def categorical_summary(self):

        summary = self.data.describe()[['count', 'unique', 'top']]
        summary.index = ['Number of observations', 'Unique values',
                         'Mode (Highest occurring value)']

        most_common_items = self.data.value_counts().head()
        n = len(self.data)
        var = most_common_items.index.to_list()
        count = most_common_items.values.tolist()
        percentage = most_common_items.apply(lambda x: f'{x / n:.2%}').values.tolist()
        self.most_common_items = \
            var, percentage, count

        return summary.to_frame()

    def missing_value(self):

        missing_values = self.data.isna().sum()
        if missing_values == 0:
            return None
        else:
            percent = str(round((missing_values / len(self.data)) * 100, 3))
            return [str(missing_values), percent]


"""
自定义分页组件
"""

import math
from django.utils.safestring import mark_safe

class Pagination(object):
    def __init__(self, request, query_set, page_param="page", page_size=10, plus=4):
        from django.http.request import QueryDict
        import copy
        query_dict = copy.deepcopy(request.GET)
        query_dict._mutable = True
        self.query_dict = query_dict
        self.page_param = page_param

        self.page = request.GET.get(page_param, '1')
        if self.page.isdecimal():
            self.page = int(self.page)
        else:
            self.page = 1

        max_value = len(query_set)
        self.page_count = math.ceil(max_value / page_size)  # 总页数

        # 防止页数越界
        if self.page > self.page_count:
            self.page = self.page_count
        elif self.page < 1:
            self.page = 1

        self.min_page = max(1, self.page - plus)
        self.max_page = min(self.page + plus, self.page_count)

        if self.page < plus + 1:
            self.max_page = min(self.page_count, 2 * plus + 1)
        if self.page > self.max_page - plus:
            self.min_page = max(1, self.page_count - 2 * plus)

        if max_value == 0:
            self.query_set = []
        else:
            self.query_set = query_set[(self.page - 1) * page_size: min(self.page * page_size, max_value)]

        self.pre_page = max(1, self.page - 1)
        self.post_page = min(self.page_count, self.page + 1)

    def html(self):
        self.query_dict.setlist(self.page_param, [1])
        first = '
首页
'.format(
            self.query_dict.urlencode())
        self.query_dict.setlist(self.page_param, [self.pre_page])
        pre = '
«
'.format(
            self.query_dict.urlencode())
        page_list = []
        page_list.append(first)
        page_list.append(pre)
        for i in range(self.min_page, self.max_page + 1):
            if i == self.page:
                self.query_dict.setlist(self.page_param, [i])
                eme = '
{}
'.format(self.query_dict.urlencode(), i)
            else:
                self.query_dict.setlist(self.page_param, [i])
                eme = '
{}
'.format(self.query_dict.urlencode(), i)
            page_list.append(eme)

        self.query_dict.setlist(self.page_param, [self.post_page])
        post = '
»
'.format(
            self.query_dict.urlencode())
        self.query_dict.setlist(self.page_param, [self.page_count])
        end = '
尾页
'.format(
            self.query_dict.urlencode())
        page_list.append(post)
        page_list.append(end)

        search = '''

<form method="get">
<input type="text" class="form-control" placeholder="页码" name="page">
        <button class="btn btn-default" type="submit">跳转</button>

</form>

         '''
        page_list.append(search)
        page_string = ''.join(page_list)
        page_string = mark_safe(page_string)

        return page_string


#yakıt tüketimi(benzin, dizel) hesaplama

benzinFiyat = 6.69
dizelFiyat = 5.86

ortalamaYakitTuketimi_L = float(input("100 km deki ortalama yakıt tüketiminiz: "))
gidilecekYol_Km = float(input("gidilecek yok kaç km: "))
yakitTipi = input("yakıt tipiniz nedir(dizel/benzin): ")

toplamYakitTuketimi = gidilecekYol_Km * (ortalamaYakitTuketimi_L / 100)

toplamBenzin = benzinFiyat * toplamYakitTuketimi
toplamDizel = dizelFiyat * toplamYakitTuketimi

if (yakitTipi == "benzin"):
    print(f"Toplam {gidilecekYol_Km} KM yol giderseniz {toplamBenzin} TL yakıt yakarsınız.")
elif (yakitTipi == "dizel"):
    print(f"Toplam {gidilecekYol_Km} KM yol giderseniz {toplamDizel} TL yakıt yakarsınız.")


import random
# random_number = random.randint(0,5)
# # print(random_number)
# ran=random.random() *100
# print(ran)

# lst=["Akki","Raj","Aklesh Kumar","Ashish"]
# print(random.choice(lst))

lst = ["cloth","Fruit","Grocery","Vagitable"]
choice = random.gauss(lst)
print(choice)


import os

# Configuration file for the Sphinx documentation builder.

project = "PyDotBot"
copyright = "2023, Alexandre Abadie"
author = "Alexandre Abadie"

# -- General configuration ---------------------------------------------------

extensions = [
    "myst_parser",
    "sphinx.ext.autodoc",
    "sphinx.ext.autosummary",
    "sphinx.ext.doctest",
    "sphinx.ext.githubpages",
    "sphinx.ext.graphviz",
    "sphinx.ext.inheritance_diagram",
    "sphinx.ext.todo",
    "sphinx.ext.viewcode",
]

tls_verify = False
templates_path = ["_templates"]
exclude_patterns = ["_build"]
nitpick_ignore_regex = [
    ("py:class", r"abc.*"),
    ("py:class", r"enum.*"),
    ("py:class", r"numpy.*"),
    ("py:class", r"pydantic.*"),
    ("py:class", r"pynput.*"),
    ("py:class", r"threading.*"),
    ("py:class", r"starlette.*"),
    ("py:class", r"ConfigDict"),
    ("py:class", r"FieldInfo"),
    ("py:class", r"<MagicMock.*>"),
]

# -- Options for HTML output -------------------------------------------------

html_theme = "pydata_sphinx_theme"
html_sourcelink_suffix = ""
html_static_path = ["_static"]

myst_enable_extensions = ["html_image"]

# Define the json_url for our version switcher.
json_url = "https://pydotbot.readthedocs.io/en/latest/_static/switcher.json"
rtd_version = os.environ.get("READTHEDOCS_VERSION")
rtd_version_type = os.environ.get("READTHEDOCS_VERSION_TYPE")
rtd_git_identifier = os.environ.get("READTHEDOCS_GIT_IDENTIFIER")
# If READTHEDOCS_VERSION doesn't exist, we're not on RTD
# If it is an integer, we're in a PR build and the version isn't correct.
# If it's "latest" → change to "dev" (that's what we want the switcher to call it)
if not rtd_version or rtd_version.isdigit() or rtd_version == "latest":
    rtd_version = "dev"
    json_url = "_static/switcher.json"
elif rtd_version == "stable":
    rtd_version = f"{rtd_git_identifier}"
release = rtd_version

html_theme_options = {
    "external_links": [
        {
            "url": "https://github.com/DotBots/DotBot-firmware",
            "name": "DotBot firmware",
            "attributes": {
                "target": "_blank",
                "rel": "noopener me",
            },
        },
        {
            "url": "https://github.com/DotBots/DotBot-hardware",
            "name": "DotBot hardware",
            "attributes": {
                "target": "_blank",
                "rel": "noopener me",
            },
        },
    ],
    "icon_links": [
        {
            "name": "GitHub",
            "url": "https://github.com/DotBots/PyDotBot",
            "icon": "fa-brands fa-github",
        },
    ],
    "header_links_before_dropdown": 4,
    "logo": {
        "text": "PyDotBot",
    },
    "navbar_align": "left",
    "navbar_center": ["version-switcher", "navbar-nav"],
    "switcher": {
        "json_url": json_url,
        "version_match": rtd_version,
    },
    "footer_start": ["copyright"],
    "footer_center": ["sphinx-version"],
}

# -- Options for linkcheck ---------------------------------------------

linkcheck_ignore = [r"http://localhost:\d+/"]

# -- Options for autosummary/autodoc output -----------------------------------
autosummary_generate = True
autodoc_typehints = "description"
autodoc_member_order = "groupwise"


def get_num(number, n):
    tmp = "0123456789ABCDEF"
    q, r = divmod(number, n)
    if q == 0:
        return tmp[r]
    else:
        return get_num(q, n)+tmp[r]

def solution(n, t, m, p):
    answer = ''
    num = 0
    result = ""
    while num <= t*m:
        result += str(get_num(num, n))
        num+=1

    while len(answer) < t:
        answer+=result[p-1]
        p+=m

    return answer


import sys
import random
import requests
import datetime

if __name__ == '__main__':
    res = requests.post('http://127.0.0.1:5000/accounts', json={
        'user': sys.argv[1],
        'starting_balance': '%.2f' % random.uniform(0, 1000),
        'name': 'stocks-%d' % int(datetime.datetime.utcnow().timestamp()),
        'type': 'Investment'
    })
    if '--silent' in sys.argv:
        try:
            print(res.json()['_id'])
        except Exception:
            if '--debug' in sys.argv:
                import ipdb
                ipdb.set_trace()
            else:
                pass
    else:
        import json
        print(json.dumps(res.json(), indent=4))


"""
Website: Leetcode
URL: https://leetcode.com/problems/buddy-strings/

Problem statement:
Given two strings A and B of lowercase letters,
return true if and only if we can swap two letters in A so that the result equals B.

Example 1:

Input: A = "ab", B = "ba"
Output: true
Example 2:

Input: A = "ab", B = "ab"
Output: false
Example 3:

Input: A = "aa", B = "aa"
Output: true
Example 4:

Input: A = "aaaaaaabc", B = "aaaaaaacb"
Output: true
Example 5:

Input: A = "", B = "aa"
Output: false

Note:

0 <= A.length <= 20000
0 <= B.length <= 20000
A and B consist only of lowercase letters.
"""

class Solution:
    def __init__(self):
        pass

    def buddy_string(self, A: str, B: str) -> bool:
        if len(A) > 20000 or len(B) > 20000:
            return False

        if len(A) != len(B):
            return False
        seen = []
        if A == B:
            for i, j in zip(A, B):
                if i in seen:
                    return True
                else:
                    seen.append(i)
        else:
            pairs = []
            for i, j in zip(A, B):
                if i != j:
                    pairs.append((i, j))

            return len(pairs) == 2 and (pairs[0][0] == pairs[1][1] and  pairs[0][1] == pairs[1][0])

if __name__ == "__main__":
    a = "abc" # aabc aacb
    b = "acb"
    s = Solution()
    r = s.buddy_string(a, b)
    print(r)


import os
import torchvision.transforms as transforms
import albumentations as A
import torch
import torch.nn as nn
from albumentations.pytorch.transforms import ToTensorV2

class_num = 2

# train_batch_size
source_batch_size = 1
# test_batch_size
target_batch_size = 1

learning_rate = 1e-5

#the begin path of using crossvalidation(run random5Foldstrain.py)
manyTimesTrainFirstPath = r"/MouthCancerDataSet/LabDataSet/makedTifSet/2"
#the train path for a single data to training(run train_base.py)
train_path = r'/MouthCancerDataSet/LabDataSet/makedTifSet/5/train'
#the test path for a single data to training(run train_base.py)
test_path = r'/MouthCancerDataSet/LabDataSet/makedTifSet/5/test'

#model_path = r"/home/joe/JoeFilesCollections/cap-pytorch/Contrast_model/mmdState/PureMineacc0.6666666269302368_epoch29normal_acc0.6338028311729431ossc_acc0.7115384340286255.pth"

epoches = 60

train_transform = transforms.Compose([
    transforms.Resize((224, 224)),

    transforms.RandomHorizontalFlip(),
    #transforms.RandomVerticalFlip(),

    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
    #transforms.Grayscale(),
])

test_transform = transforms.Compose([
    transforms.Resize((224, 224)),

    transforms.ToTensor(),
    transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
    #transforms.Grayscale(),
])

A_train_transform = A.Compose([A.HorizontalFlip(p=0.5),
                                            A.HorizontalFlip(p=0.5),
                                            A.VerticalFlip(p=0.5),
                                            #A.RandomBrightness(limit=0.2, p=0.5),
                                            #A.RandomContrast(limit=0.2, p=0.5),
                                            # A.OneOf([
                                            #     A.MotionBlur(blur_limit=3),
                                            #     A.MedianBlur(blur_limit=3),
                                            #     A.GaussianBlur(blur_limit=3),
                                            #     A.GaussNoise(var_limit=(3.0, 30.0)),
                                            # ], p=0.5),
                                            # A.OneOf([
                                            #     A.OpticalDistortion(distort_limit=1.0),
                                            #     A.GridDistortion(num_steps=5, distort_limit=1.),
                                            #     A.ElasticTransform(alpha=3),
                                            # ], p=0.7),

                                            A.Resize(224, 224),
                                            # A.Cutout(max_h_size=int(224 * 0.375), max_w_size=int(224 * 0.375),
                                            #          num_holes=1, p=0.7),
                                            A.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
                                            ToTensorV2()])
A_test_transform = A.Compose([
    A.Resize(224, 224),
    # A.Cutout(max_h_size=int(224 * 0.375), max_w_size=int(224 * 0.375),
    #          num_holes=1, p=0.7),
    A.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),
    ToTensorV2()
])


import random
import math
import re

from sqlalchemy import null

# Create an board object to represent the minesweeper game
class Board:
    def __init__(self, dimmSize, numBombs):
        # Keep track of these parameters (board size and number of bombs)
        self.dimSize = dimmSize
        self.numBombs = numBombs

        # Creation of the board
        # makeNewBoard() is an helper function which will create the board and plant the bombs into the board
        self.board = self.makeNewBoard()
        # assignValueToBoard() is an helper function which will assign the number to determine how many bombs are around the area
        self.assignValueToBoard()

        # Initalize a set to keep track of which locations we've uncovered
        # Something like (row, col) tuples into this set
        # So if we dig at 0,0 then self.dug = {(0,0)}
        self.dug = set()

    def makeNewBoard(self):
        # Construct a new board based on the dimension size and number of bombs that the player has set or with the default value

        # Generate a new board
        board = [[None for _ in range(self.dimSize)] for _ in range(self.dimSize)]
        # In a nutshell create an array that look like this:
        # [[None, None, ..., None],
        #  [None, None, ..., None],
        #  [..., ..., ..., ...],
        #  [None, None, ..., None],
        # A board filled with board with none

        # Plant the bomb onto the board
        bombPlanted = 0
        while bombPlanted < self.numBombs:
            loc = random.randint(0, self.dimSize**2 -1)
            # We want the number of times dimSize goes into loc to tell us the row index
            row = loc // self.dimSize
            # We want the remainder to tell us what index in that row to look for the column index
            col = loc % self.dimSize

            # We will use * to represent the bomb while None as a "normal space"
            if board[row][col] == '*':
                # This means we've actually planted a bomb there already so keep going
                continue

            # Bomb planted onto the board
            board[row][col] = '*'
            bombPlanted += 1
        return board

    def assignValueToBoard(self):
        # With the bombs planted onto the board, we can assign a number 0-8 for all the empty spaces to represent how many neighboring bombs there are.
        for r in range(self.dimSize):
            for c in range(self.dimSize):
                if self.board[r][c] == '*':
                    # If the square is already an bomb, we dont want to calculate anything
                    continue
                self.board[r][c] = self.getNumNeighboringBombs(r, c)

    def getNumNeighboringBombs(self, row, col):
        # Iterate through each of the neighboring positions and sum number of bombs
        # Top left: (row-1, col-1)
        # Top mid: (row-1, col)
        # Top right: (row-1, col+1)
        # Left: (row, col-1)
        # Right: (row, col+1)
        # Bottom left: (row+1, col-1)
        # Bottom  mid: (row+1, col)
        # Bottom  right: (row+1, col+1)

        # Making sure we dont go out of bound
        numNeighboringBombs = 0

        # For each row, we are checking above and below
        # For the lower bound (max(0, row-1), we are setting it with the highest value so if we were at 0,0 it would not set the index to -1 since it would be out of bound
        # For the upper bound min(self.dimSize-1, row+1)+1), that is the biggest index we can go
        for r in range(max(0, row-1), min(self.dimSize-1, row+1)+1):
            # For each column we are checking the left and the right side
            for c in range(max(0,col-1), min(self.dimSize-1, col+1)+1):
                if r == row and c == col:
                    # Original location, dont check
                    continue
                if self.board[r][c] == '*':
                    numNeighboringBombs += 1
        return numNeighboringBombs

    def dig(self, row, col):
        # Dig at the location given
        # Return true if its an successful dig, false if a bomb were dug

        # Scenarios for the dig function:
        # S1: Hit a bomb -> game over and return false
        # S2: Dig at location with neighboring bombs -> finish dig and return true
        # S3: Dig at location with no neighboring bombs -> recursively dig neighbors

        # Keep track of where we dug
        self.dug.add((row, col))

        if self.board[row][col] == '*':
            return False
        elif self.board[row][col] > 0:
            return True

        # Where self.board[row][col] == 0 -> S3
        for r in range(max(0, row-1), min(self.dimSize-1, row+1)+1):
            for c in range(max(0,col-1), min(self.dimSize-1, col+1)+1):
                # If this place has already been dug, then continue
                if(r, c) in self.dug:
                    continue
                self.dig(r, c)
        # If our initial dig didnt't hit a bomb, we shouldn't hit a bomb here
        return True

    def __str__(self):
        # This is a magic function where if you call print on this object
        # it'll print out what this function returns!
        # Return a string that shows the board to the player

        # Create a new array that represents what the user would see
        visibleBoard = [[None for _ in range(self.dimSize)] for _ in range(self.dimSize)]
        for row in range(self.dimSize):
            for col in range(self.dimSize):
                if (row, col) in self.dug:
                    visibleBoard[row][col] = str(self.board[row][col])
                else:
                    visibleBoard[row][col] = ' '

        # put this together in a string
        string_rep = ''

        # Get max column widths for printing
        widths = []
        for idx in range(self.dimSize):
            columns = map(lambda x: x[idx], visibleBoard)
            widths.append(
                len(
                    max(columns, key = len)
                )
            )

        # Print the csv strings
        indices = [i for i in range(self.dimSize)]
        indices_row = '   '
        cells = []
        for idx, col in enumerate(indices):
            format = '%-' + str(widths[idx]) + "s"
            cells.append(format % (col))
        indices_row += '  '.join(cells)
        indices_row += '  \n'

        for i in range(len(visibleBoard)):
            row = visibleBoard[i]
            string_rep += f'{i} |'
            cells = []
            for idx, col in enumerate(row):
                format = '%-' + str(widths[idx]) + "s"
                cells.append(format % (col))
            string_rep += ' |'.join(cells)
            string_rep += ' |\n'

        str_len = int(len(string_rep) / self.dimSize)
        string_rep = indices_row + '-'*str_len + '\n' + string_rep + '-'*str_len

        return string_rep

# Function to play the game, default board size is 10 by 10 with 10 bombs
def play(dimSize = 10, numBombs = 10):
    # Step 1: Create the board and plant the bombs
    board = Board(dimSize, numBombs)

    # Step 2: Show the user the board and ask for where they want to dig

    # Step 3a: If location is a bomb, show game over message
    # Step 3b: If location is not a bomb, dig recursively until each square is at least next to a bomb
    # Step 4: Repeat step 2 and 3a/b until there are no more places to dig which results in an victory
    safe = True
    while len(board.dug) < board.dimSize ** 2 - numBombs:
        print(board)
        # Regex basically split the string with , and matches it with either 0,0 or 0, 0 or 0, .... 0
        userInput = re.split(',(\\s)*', input('Where would you like to dig? Input as row, col: '))
        row, col = int(userInput[0]), int(userInput[-1])
        if row < 0 or row >= board.dimSize or col < 0 or col >= dimSize:
            print("Invalid location. Try again.")
            continue

        # If its an valid spot, we dig
        safe = board.dig(row, col)
        if not safe:
            # Dug a bomb so game over
            print("Sorry Game over: ")
            # Reveal the whole board
            board.dug = [(r,c) for r in range(board.dimSize) for c in range(board.dimSize)]
            print(board)
            break

    if safe:
        print("Congratulations! You have won!")

if __name__ == '__main__':
    # Data sanitization (Limit user inputting numbers only)
    while True:
        try:
            # Create a board size that the user has specified. Maximum a 10 by 10
            boardsize = input("Enter a boardsize: ")
            # Create mines. The quantity of mines are <= boardsize^2
            bombQuantity = input("Enter the number of bombs: ")

            # User has not specified the board size or the bomb quantity therefore default values were used
            if(len(boardsize) == 0 and len(bombQuantity) == 0):
                play()
            # User has only specified the quantity of mines
            elif(len(boardsize) == 0 and len(bombQuantity) != 0):
                # If specified quantity of mines exceed the board size default values are used
                if(int(bombQuantity) > int(boardsize)):
                    play(10, 10)
                play(10, int(bombQuantity))
            # User has only specified the board size
            elif(len(boardsize) != 0 and len(bombQuantity) == 0):
                # If specified board size is greater than 10 by 10 then default values are used
                if(int(boardsize) > 10):
                    play(10, 10)
                play(int(boardsize), 10)
            # User has only both the board size and quanity of mines
            else:
                # If specified quantity of mines exceed the board size, half the board is filled with mines (custom board if user has entered in two valid input)
                if(int(bombQuantity) > int(boardsize)):
                    play(int(boardsize), math.floor(int(pow(int(boardsize), 2)/2)))
                play(int(boardsize), int(bombQuantity))
            break
        except:
            print("Please enter a valid integer for either the board size or quantity of mines!")


#!/usr/bin/env python
"""
Validates that a string of parentheses and curly/square braces/brackets
is a valid set of matches.
"""
class Validator:
    """Because OOP?"""

    def __init__(self):
        self.openChars = ['(', '[', '{']
        self.closeChars = [')', ']', '}']

    def validateString(self, string):
        """Validates a string consisting of only the set of characters in
            self.openChars + self.closeChars
           Handling of any other characters (except leading/trailing whitespace)
           is not defined.

        Args:
           - string (String): The string of parens (e.g., "(())")

        Returns:
           - True if `string` is a valid set of open/close chars, else False
        """
        stack = []
        string = string.strip()

        if len(string) % 2 is not 0:
            return False

        for ch in string:
            if ch in self.openChars:
                stack.append(ch)
            elif len(stack) is 0:
                return False
            elif ch in self.closeChars:
                idx = self.closeChars.index(ch)
                if self.openChars[idx] != stack.pop():
                    return False
        return True

tests = [
    (True, ""),
    (True, "()"),
    (True, "()()"),
    (True, "{}[]"),
    (True, "({}[])"),
    (True, "([]){}"),
    (True, "((({{{[[[]]]}}})))"),
    (True, "{()}"),

    (False, "{"),
    (False, "}"),
    (False, ")("),
    (False, "{{}"),
    (False, "{}}"),
    (False, "}{()"),
    (False, "[])"),
    (False, "({)}"),
    (False, "([{]})")
    ]
if __name__ == '__main__':
    val = Validator()
    for (i, (answer, inpt)) in enumerate(tests):
        print(" \033[33;01m Test #%d (\"%s\")\033[0m" % (i, inpt))
        out = val.validateString(inpt)
        if out == answer:
            print(" \033[32m PASS \033[0m")
        else:
            print(" \033[31m FAIL \033[0m")
            print("\033[92mExpected:")
            print("+%s\033[0m" % (str(answer)))
            print("\033[91mReceived:")
            print("-%s\033[0m" % (str(out)))


def subtract(*args, **kwds):
        '''Like dict.update() but subtracts counts instead of replacing them.
        Counts can be reduced below zero.  Both the inputs and outputs are
        allowed to contain zero and negative counts.

        Source can be an iterable, a dictionary, or another Counter instance.

        >>> c = Counter('which')
        >>> c.subtract('witch')             # subtract elements from another iterable
        >>> c.subtract(Counter('watch'))    # subtract elements from another counter
        >>> c['h']                          # 2 in which, minus 1 in witch, minus 1 in watch
        0
        >>> c['w']                          # 1 in which, minus 1 in witch, minus 1 in watch
        -1

        '''
        if not args:
            raise TypeError("descriptor 'subtract' of 'Counter' object "
                            "needs an argument")
        self = args[0]
        args = args[1:]
        if len(args) > 1:
            raise TypeError('expected at most 1 arguments, got %d' % len(args))
        iterable = args[0] if args else None
        if iterable is not None:
            self_get = self.get
            if isinstance(iterable, Mapping):
                for elem, count in iterable.items():
                    self[elem] = self_get(elem, 0) - count
            else:
                for elem in iterable:
                    self[elem] = self_get(elem, 0) - 1
        if kwds:
            self.subtract(kwds)


import threading
from lib.reports import *

class Result(object):
    def __init__(self, path, status, response):
        self.path = path
        self.status = status
        self.response = response

    def get_content_length(self):
        try:
            content_length = int(self.response.headers["content-length"])
        except (KeyError, ValueError):
            content_length = len(self.response.body)
        return content_length

class Report(object):
    def __init__(self, host, port, protocol, base_path):
        self.host = host
        self.port = port
        self.protocol = protocol
        self.base_path = base_path
        self.results = []
        self.completed = False

        if self.base_path.endswith("/"):
            self.base_path = self.base_path[:-1]

        if self.base_path.startswith("/"):
            self.base_path = self.base_path[1:]

    def add_result(self, path, status, response):
        result = Result(path, status, response)
        self.results.append(result)

class ReportManager(object):
    def __init__(self, save_format, output_file):
        self.format = save_format
        self.reports = []
        self.report_obj = None
        self.output = output_file
        self.lock = threading.Lock()

    def update_report(self, report):
        if report not in self.reports:
            self.reports.append(report)
        self.write_report()

    def write_report(self):
        if self.report_obj is None:
            if self.format == "simple":
                report = SimpleReport(self.output, self.reports)
            elif self.format == "json":
                report = JSONReport(self.output, self.reports)
            elif self.format == "xml":
                report = XMLReport(self.output, self.reports)
            elif self.format == "md":
                report = MarkdownReport(self.output, self.reports)
            elif self.format == "csv":
                report = CSVReport(self.output, self.reports)
            elif self.format == "html":
                report = HTMLReport(self.output, self.reports)
            else:
                report = PlainTextReport(self.output, self.reports)

            self.report_obj = report

        with self.lock:
            self.report_obj.save()

    def save(self):
        with self.lock:
            self.output.save()

    def close(self):
        self.output.close()


# coding: utf-8

"""
Exemplo de uma classe com descritor

A classe ItemPedido deve ser instanciada com os dados essenciais que sao:
descricao do item, preco unitario e quantidade.

    >>> bolas = ItemPedido('bola de golf', 2, 10)
    >>> bolas.descr
    'bola de golf'
    >>> bolas.qtd
    10

O atributo qtd de um ItemPedido nunca pode ser < 1:

    >>> duendes = ItemPedido('duende verde', 2.99, 0)
    Traceback (most recent call last):
      ...
    TypeError: quantidade deve ser > 0
    >>> duendes = ItemPedido('duende verde', 2.99, 13)
    >>> duendes.qtd
    13
    >>> duendes.qtd = -1
    Traceback (most recent call last):
      ...
    TypeError: quantidade deve ser > 0
    >>> duendes.qtd = 20
    >>> duendes.qtd
    20

Se o argumento qtd for None, eh usado um valor default, definido
na classe:

    >>> unicornio = ItemPedido('unicornio', 199000)
    >>> unicornio.qtd
    1

"""

class Quantidade(object):
    def __init__(self, nome_atr):
        self.nome_atr = nome_atr
    def __set__(self, instance, valor):
        if valor < 1:
            raise TypeError('quantidade deve ser > 0')
        else:
            setattr(instance, '__'+self.nome_atr, valor)
    def __get__(self, instance, owner):
        nome_atr_real = '__'+self.nome_atr
        if hasattr(instance, nome_atr_real):
            return getattr(instance, nome_atr_real)
        else:
            return getattr(owner, self.nome_atr+'_default')

class ItemPedido(object):
    """um item de um pedido"""

    qtd = Quantidade('qtd')
    qtd_default = 1

    def __init__(self, descr, pr_unitario, qtd=None):
        self.descr = descr
        if qtd is not None:
            self.qtd = qtd
        self.pr_unitario = pr_unitario


import torch
import torch.nn as nn
from transformers import BertModel

class TextClassifier(nn.Module):
    def __init__(self, input_size: int = 768, num_classes: int = 13) -> None:
        super().__init__()
        self.bert = BertModel.from_pretrained('bert-base-uncased', output_hidden_states=True)
        self.main = nn.Sequential(nn.Dropout1d(0.1),
                                  nn.Conv1d(input_size, 256, kernel_size=3, stride=1, padding=1),
                                  nn.ReLU(),
                                  nn.MaxPool1d(kernel_size=2, stride=2),

                                  nn.Conv1d(256, 128, kernel_size=3, stride=1, padding=1),
                                  nn.ReLU(),
                                  nn.MaxPool1d(kernel_size=2, stride=2),

                                  nn.Conv1d(128, 64, kernel_size=3, stride=1, padding=1),
                                  nn.ReLU(),
                                  nn.MaxPool1d(kernel_size=2, stride=2),

                                  nn.Conv1d(64, 32, kernel_size=3, stride=1, padding=1),
                                  nn.ReLU(),
                                  nn.MaxPool1d(kernel_size=2, stride=2),
                                  nn.Dropout1d(0.1),

                                  nn.Flatten(),
                                  nn.Dropout1d(0.3),
                                  nn.Linear(384 , 13))

    def forward(self, input):
        embeddings = []
        self.bert.eval()
        for stack in input:
            split = torch.unbind(stack)
            encoded = {}
            encoded['input_ids'] = split[0]
            encoded['token_type_ids'] = split[1]
            encoded['attention_mask'] = split[2]

            with torch.no_grad():
                embedding = self.bert(**encoded).last_hidden_state.swapaxes(1,2)
            embedding = embedding.squeeze(0) # removes the leading dimension of '1' in .size
            embeddings.append(embedding)

        desc_stack = torch.stack(embeddings)
        result = self.main(desc_stack)
        return result


from datetime import date

from dagster import execute_solid

from definitions.exchangerates.solids import extract

def is_key_in_dict(dict, key):
    for element in dict:
        if key in element:
            return True

def test_extract_solid():
    date_from = date(year=2010, month=1, day=1).isoformat()
    date_to = date(year=2010, month=12, day=31).isoformat()
    run_config = {"solids": {"extract": {"config": {"date_from": date_from, "date_to": date_to}}}}
    result = execute_solid(extract, run_config=run_config)
    output = result.output_values['result']

    assert 'rates' in output
    assert len(output['rates']) > 250
    assert is_key_in_dict(output['rates'], '2010-01-04')
    assert is_key_in_dict(output['rates']['2010-01-04'], 'USD')


from unittest import TestCase

import numpy as np
import torch

from backend.ml.misconception import MisconceptionDataset
from backend.ml.sentence_bert import cosine_similarity
from backend.ml.sentence_bert import SentenceBertBase

#SMALL_MODEL_IDENTIFIER = "julien-c/bert-xsmall-dummy"
SMALL_MODEL_IDENTIFIER = "roberta-base"

class CosineSimilarityTest(TestCase):
    def test_output_is_corect(self):
        # Tests that score of a batch of orthogonal tensors against itself is the identity matrix.
        x = torch.FloatTensor([
            [1,  1],
            [1, -1],
        ])
        score = cosine_similarity(x, x)
        expected_score = torch.FloatTensor([
            [1,  0],
            [0,  1]
        ])
        assert torch.allclose(score, expected_score)

class SentenceBertBaseTest(TestCase):
    def setUp(self):
        self.detector = SentenceBertBase(SMALL_MODEL_IDENTIFIER)

    def test_scores_not_affected_by_padding(self):
        with open('tests/fixtures/misconceptions.jsonl', 'r') as f:
            misconceptions = MisconceptionDataset.from_jsonl(f)
        sentences = ['Lorem ipsum', 'dolor sit amet']
        score_a = self.detector.score(sentences[0], misconceptions)
        score_b = self.detector.score(sentences, misconceptions)[0]
        assert np.allclose(score_a, score_b)


from b26_toolkit.b26_toolkit.instruments.microwave_generator import MicrowaveGenerator
import timeit
import matplotlib.pyplot as plt
import numpy as np

def switch_frequency(mw_generator):
    mw_generator.update({'frequency': 2.7e9})
    mw_generator.update({'frequency': 2.7e9})

times = []
mw_generator = MicrowaveGenerator()
for i in range(0,10):
    print(i)
    times.append(timeit.timeit(lambda: switch_frequency(mw_generator), number = 500))
plt.plot(times, '.')

print(times)

print((np.std(np.array(times))))

plt.title('Average: {0:.2f}, Stddev: {1:.2f}'.format(np.mean(np.array(times)), np.std(np.array(times))))
plt.xlabel('Trial Number')
plt.ylabel('Execution time (s)')

plt.show()