import cv2
import numpy as np
from PySide6.QtGui import QImage, QPainter, QPen, Qt, QPixmap
from PySide6.QtCore import QObject, QPoint
from PySide6.QtCore import Slot, Signal
from PySide6.QtWidgets import QMessageBox

from Logic.utils.utils import QImageToCvMat
from Model.Scribble import SCRIBBLE_TYPE
import Model
from Logic.utils.utils import QImageToGrayCvMat

class ImageLabelModel(QObject):
    resetImage = Signal(QImage)
    __m_parent = None
    # 图片左上角相对与Qlabel左上角的偏移
    __originX: int
    __originY: int
    # Qlabel内显示的图片的长度和宽度，用于计算左上角的坐标
    __imgW: int
    __imgH: int
    rawImage: QImage

    cur_scribble_type: SCRIBBLE_TYPE
    scribbles: list

    __initialseg_end: bool

    # 用户给的点击点对应的位置
    __extrem_pos: list

    # 扩展后转化成和图片尺寸一样的编码图
    __initial_extreme_seed: np.ndarray
    __contours: tuple
    iniSegProb: np.ndarray
    __segmentResult: np.ndarray

    def __init__(self, parent=None) -> None:
        super().__init__(parent)
        self.scribbles = []
        self.cur_scribble_type = SCRIBBLE_TYPE.SEED
        self.__extrem_pos = []
        self.__contours = ()
        self.__initialseg_end = False

    def imgShape(self):
        return (self.__imgH, self.__imgW)

    @property
    def iniExtremSeed(self):
        return self.__initial_extreme_seed

    @iniExtremSeed.setter
    def iniExtremSeed(self, x):
        self.__initial_extreme_seed = x

    @property
    def extremPos(self):
        return self.__extrem_pos

    def start(self, x, y, color):
        '''
        鼠标按下时调用的方法,x,y为相对于窗口左上角的坐标
        :param x:
        :param y:
        :param color:
        :return:
        '''
        xr, yr = self.mapToRelative(x, y)
        xr, yr = self.validate(xr, yr)

        if self.__initialseg_end:
            Model.Scribble.ScribeFactory.getScribbleByEnum(self.cur_scribble_type, self).start(xr, yr, color)
            Model.Scribble.ScribeFactory.getScribbleByEnum(self.cur_scribble_type, self).update(xr, yr)
        else:
            self.__extrem_pos.append((xr, yr))

    def validate(self, x, y):
        '''
        如果滑到了图片框之外，让他回到图片上
        :param x:
        :param y:
        :return:
        '''
        if x < 0:
            x = 0
        if y < 0:
            y = 0
        if x >= self.__imgW:
            x = self.__imgW
        if y >= self.__imgH:
            y = self.__imgH
        return x, y

    def update(self, x, y):
        xr, yr = self.mapToRelative(x, y)
        xr, yr = self.validate(xr, yr)
        if self.__initialseg_end:
            Model.Scribble.ScribeFactory.getScribbleByEnum(self.cur_scribble_type, self).update(xr, yr)
        else:
            self.__extrem_pos.append((xr, yr))

    def draw(self, painter: QPainter):
        '''
        用指定SCRIBBLE_TYPE枚举类中的self.cur_scribble_type工具绘制,这里采用的工厂模式,扩展时需要在SCRIBBLE_TYPE添加对应的枚举项、
        并修改ScribeFactory，注意工具类必须继承自Scribblebase，并实现对应的方法，绘制时统一调用其draw方法
        :param painter:
        :return:
        '''
        Model.Scribble.ScribeFactory.getScribbleByEnum(self.cur_scribble_type, self).draw(painter)
        painter.setPen(QPen(Qt.darkCyan, 4))
        for p in self.__extrem_pos:
            xr, yr = self.recoverToAbs(p[0], p[1])
            painter.drawPoint(QPoint(xr, yr))
        # if self.__initialseg_end:
        #     ScribeFactory.getScribbleByEnum(self.cur_scribble_type, self).draw(painter)
        # else:
        #     painter.setPen(QPen(Qt.darkCyan, 4))
        #     for p in self.__extrem_pos:
        #         xr, yr = self.recoverToAbs(p[0], p[1])
        #         painter.drawPoint(QPoint(xr, yr))

    def end(self, x, y):
        '''
        这里是鼠标放下时调用的方法，鼠标放下代表此次绘制结束，x,y为相对于窗口左上角的坐标
        :param x:
        :param y:
        :return:
        '''
        xr, yr = self.mapToRelative(x, y)
        xr, yr = self.validate(xr, yr)
        if self.__initialseg_end:
            Model.Scribble.ScribeFactory.getScribbleByEnum(self.cur_scribble_type, self).end(xr, yr)
        else:
            self.__extrem_pos.append((xr, yr))

    def setImage(self, img: QImage):
        self.rawImage = img
        self.clear()
        self.__imgH = img.height()
        self.__imgW = img.width()
        self.grayImage = QImageToGrayCvMat(img)

    def moveToRefine(self):
        self.__initialseg_end = True

    def computeOrigin(self, framW, framH):
        '''
        label的长宽会根据窗口调整，每次调整后重新计算图片左上角的坐标
        :param framW:label框的宽度
        :param framH: label框的长度
        :return:
        '''
        self.__originX = (framW - self.__imgW) / 2
        self.__originY = (framH - self.__imgH) / 2

    @Slot()
    def clear(self):
        Model.Scribble.ScribeFactory.release()
        self.__initialseg_end = False
        self.__contours = ()
        self.__extrem_pos.clear()
        self.segmentResult = None
        self.resetImage.emit(self.rawImage)

    def stage1End(self):
        return self.__initialseg_end

    def showContours(self, contours) -> tuple:
        self.__contours = contours
        img = QImageToCvMat(self.rawImage)
        img = cv2.drawContours(
            img, self.__contours, -1, (0, 255, 0), 2)
        q_img = QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * 4, QImage.Format_RGB32)
        self.resetImage.emit(q_img)

    def saveMask(self, filepath):
        if self.__segmentResult is None:
            QMessageBox.warning(None, "warn",
                                "segmentation result not found.")
            return

        cv2.imwrite(filepath, self.__segmentResult)

        # if not self.__initialseg_end or len(self.__contours) == 0:
        #     QMessageBox.warning(None, "warn",
        #                         "segmentation result not found.")
        #
        #     return

        # img = QImageToCvMat(self.__segmentResult)
        # # img = QImageToCvMat(self.rawImage)
        # # img = cv2.drawContours(
        # #     img, self.__contours, -1, (0, 255, 0), 2)
        # q_img = QImage(img.data, img.shape[1], img.shape[0], img.shape[1] * 4, QImage.Format_RGB32)
        # q_img.save(filepath)

    def mapToRelative(self, x, y):
        '''
        相对于父widget(label)左上角坐标转换成相对于图片左上角的坐标
        :param x:
        :param y:
        :return:
        '''
        return x - self.__originX, y - self.__originY

    def recoverToAbs(self, x, y):
        '''
        绘制点的时候，draw接口需要转化会相对与窗口父widget的坐标
        :param x:
        :param y:
        :return:
        '''
        return x + self.__originX, y + self.__originY

    def setSegmentationResult(self, result: np.ndarray):
        self.__segmentResult = result * 255


import time

import module_pyportplexed as th

threads = th.start(55555, 8, 12345)

print('threads:', threads)

connections = th.connect(threads, '1024**100000')

print('connections:', connections)

t0 = time.perf_counter()
results = th.results(12345, 8)
print('time taken:', time.perf_counter() - t0)
print('Items in results:', len(results))

# my pyportplexed (python -OO program_x.py):
# (8 operations: 1024**100000) 2.6084568000005675 seconds

# single thread (python -OO time_equivalent_eval(1024^10000).py):
# (8 operations: 1024**100000) 16.447089799999958 seconds


import numpy as np
import scipy.misc
import itertools

def isposint(n):
    """
    Determines whether number n is a positive integer.
    :param n: number
    :return: bool
    """
    return isinstance(n, int) and n > 0

def isdistribution(p):
    """
    :param p: a vector representing a discrete probability distribution
    :return: True if p is a valid probability distribution
    """
    return np.all(p >= 0.0) and np.isclose(np.sum(p), 1.0)

def logistic(x):
    """
    Elementwise logistic sigmoid.
    :param x: numpy array
    :return: numpy array
    """
    return 1.0 / (1.0 + np.exp(-x))

def logit(x):
    """
    Elementwise logit (inverse logistic sigmoid).
    :param x: numpy array
    :return: numpy array
    """
    return np.log(x / (1.0 - x))

def logsoftmax(x):
    """
    Calculates the log softmax of x, or of the rows of x.
    :param x: vector or matrix
    :return: log softmax
    """

    x = np.asarray(x)

    if x.ndim == 1:
        return x - scipy.misc.logsumexp(x)

    elif x.ndim == 2:
        return x - scipy.misc.logsumexp(x, axis=1)[:, np.newaxis]

    else:
        raise ValueError('input must be either vector or matrix')

def softmax(x):
    """
    Calculates the softmax of x, or of the rows of x.
    :param x: vector or matrix
    :return: softmax
    """

    return np.exp(logsoftmax(x))

def discrete_sample(p, n_samples=None, rng=np.random):
    """
    Samples from a discrete distribution.
    :param p: a distribution with N elements
    :param n_samples: number of samples, only 1 if None
    :return: vector of samples
    """

    # check distribution
    # assert isdistribution(p), 'Probabilities must be non-negative and sum to one.'

    one_sample = n_samples is None

    # cumulative distribution
    c = np.cumsum(p[:-1])[np.newaxis, :]

    # get the samples
    r = rng.rand(1 if one_sample else n_samples, 1)
    samples = np.sum((r > c).astype(int), axis=1)

    return samples[0] if one_sample else samples

def importance_sample(target, proposal, n_samples, rng=np.random):
    """
    Importance sampling.
    :param target: target distribution
    :param proposal: proposal distribution
    :param n_samples: number of samples
    :param rng: random generator to use
    :return: samples, normalized log weights
    """

    xs = proposal.gen(n_samples, rng=rng)
    log_ws = target.eval(xs, log=True) - proposal.eval(xs, log=True)
    log_ws -= scipy.misc.logsumexp(log_ws)

    return xs, log_ws

def ess_importance(ws):
    """
    Calculates the effective sample size of a set of weighted independent samples (e.g. as given by importance
    sampling or sequential monte carlo). Takes as input the normalized sample weights.
    """

    ess = 1.0 / np.sum(ws ** 2)
    return ess

def ess_mcmc(xs):
    """
    Calculates the effective sample size of a correlated sequence of samples, e.g. as given by markov chain monte
    carlo.
    """

    n_samples, n_dims = xs.shape

    mean = np.mean(xs, axis=0)
    xms = xs - mean

    acors = np.zeros_like(xms)
    for i in xrange(n_dims):
        for lag in xrange(n_samples):
            acor = np.sum(xms[:n_samples-lag, i] * xms[lag:, i]) / (n_samples - lag)
            if acor <= 0.0: break
            acors[lag, i] = acor

    act = 1.0 + 2.0 * np.sum(acors[1:], axis=0) / acors[0]
    ess = n_samples / act

    return np.min(ess)

def calc_whitening_transform(xs):
    """
    Calculates the parameters that whiten a dataset.
    """

    assert xs.ndim == 2, 'Data must be a matrix'
    N = xs.shape[0]

    means = np.mean(xs, axis=0)
    ys = xs - means

    cov = np.dot(ys.T, ys) / N
    vars, U = np.linalg.eig(cov)
    istds = np.sqrt(1.0 / vars)

    return means, U, istds

def whiten(xs, params):
    """
    Whitens a given dataset using the whitening transform provided.
    """

    means, U, istds = params

    ys = xs.copy()
    ys -= means
    ys = np.dot(ys, U)
    ys *= istds

    return ys

def de_whiten(xs, params):
    """
    De-whitens a given dataset using the whitening transform provided.
    """

    means, U, istds = params

    ys = xs.copy()
    ys /= istds
    ys = np.dot(ys, U.T)
    ys += means

    return ys

def median_distance(xs):
    """
    Calculate the median distance of a set of points.
    :param xs: matrix with points as rows
    :return: median distance
    """

    xs = np.asarray(xs)
    diffs = np.array([x1 - x2 for x1, x2 in itertools.combinations(xs, 2)])
    dists = np.sqrt(np.sum(diffs ** 2, axis=1))

    return np.median(dists)


#!/usr/bin/env python

import tensorflow as tf
import numpy as np

b = tf.Variable(tf.zeros((100,)))
w = tf.Variable(tf.random_uniform((784, 100), -1, 1))
x = tf.placeholder(tf.float32, (100, 784))

h = tf.nn.relu(tf.matmul(x, w) + b)

sess = tf.Session()
sess.run(tf.initialize_all_variables())
sess.run(h, {x : np.random.random(100, 784)})

# ------------  Till Initializing a session ---------------- #


from rl.callbacks import Callback

class EpsilonDecay(Callback):
    def __init__(self, decay, minimum=0.01, offset=0, skip=1):
        super().__init__()
        self.decay = decay
        self.min = minimum
        self.offset = offset
        self.skip = skip

    def on_episode_end(self, episode, logs={}):
        super().on_episode_end(episode, logs=logs)
        episode += 1
        if episode >= self.offset and episode % self.skip == 0:
            self.model.policy.eps = max(self.min, self.model.policy.eps*self.decay)

        print("epsilon:", self.model.policy.eps)


def check_connection(network, first, second):
    graph = build_graph(network)

    def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return True

        if not start in graph.keys():
            return False

        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return False

    return find_path(graph, first, second)

def build_graph(network):
    graph = {}
    for pair in network:
        node1, node2 = pair.split('-')
        if node1 not in graph:
            graph[node1] = list(set([node2]))
        else:
            graph[node1].append(node2)

        if node2 not in graph:
            graph[node2] = list(set([node1]))
        else:
            graph[node2].append(node1)

    return graph

if __name__ == '__main__':
    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert check_connection(
        ("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
         "scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
        "scout2", "scout3") == True, "Scout Brotherhood"
    assert check_connection(
        ("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
         "scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
        "super", "scout2") == True, "Super Scout"
    assert check_connection(
        ("dr101-mr99", "mr99-out00", "dr101-out00", "scout1-scout2",
         "scout3-scout1", "scout1-scout4", "scout4-sscout", "sscout-super"),
        "dr101", "sscout") == False, "I don't know any scouts."


#step 1. First, we need to import the GUI library:
from PyQt5.QtGui import *

#step 2: Next, we initialize the warning dialog:
msg=QMessageBox()

#step 3: Then, we set the warning message:
msg.setText("This is an error")

#step 4:Now, add a warning icon to the dialog that has an enumeration index of 2:
msg.setIcon(QMessageBox.Critical)

#step 5: Finally, we call the execution method to display the dialog:
msg.show()


def solution(sequence):
    answer = 0
    length = len(sequence)
    dp = [0] * length
    dp[0] = sequence[0]
    if length == 1:
        return max(dp[0], dp[0]*-1)
    for i in range(1, length, 2):
        sequence[i] *= -1
    for i in range(1, length):
        dp[i] = max(dp[i-1]+sequence[i], sequence[i])
    answer = max(dp)
    for i in range(length):
        sequence[i] *= -1
    dp[0] = sequence[0]
    for i in range(1, length):
        dp[i] = max(dp[i-1]+sequence[i], sequence[i])
    answer = max(answer, max(dp))
    return answer

프로그래머스/unrated/161988. 연속 펄스 부분 수열의 합/연속 펄스 부분 수열의 합.py

연속 펄스 부분 수열의 합.py


import pygame
from scripts.config import _

def draw_text(screen, text, font, color, x, y):
    textobj = font.render(text, 1, color)
    rect_txt = textobj.get_rect()
    rect_txt.topleft = (x, y)
    rect_txt.centerx = int(_.SCREEN_WIDTH / 2)
    screen.blit(textobj, rect_txt)
    return rect_txt

def draw_button(screen, x, y, w , h, bg_c, text_, clr_, x_, y_):
    rect_btn = pygame.Rect(x, y, w, h)
    rect_btn.centerx = int(_.SCREEN_WIDTH / 2)
    pygame.draw.rect(screen, bg_c, rect_btn)
    rect_txt = draw_text(screen, text_, _.font, clr_, x_, y_)
    #rect_txt.centery = rect_btn.centery
    return rect_btn

def drawImage(screen, path, x, y):
    img_ = pygame.image.load(path).convert_alpha()
    rect_img = img_.get_rect()
    if(rect_img.w > _.SCREEN_WIDTH):
        img_ = pygame.transform.scale(img_,(_.SCREEN_WIDTH, y))
        rect_img = img_.get_rect()
    rect_img.centerx = int(_.SCREEN_WIDTH / 2)
    screen.blit(img_, (rect_img.x, y))
    return rect_img


import shutil
import pandas as pd
import glob
import os

TARGET_TRAIN_DIR = '../data/raw/train/'
TARGET_TEST_DIR = '../data/raw/test/'

### NB: move all files from subdirectories to parent (current) dir: find . -mindepth 2 -type f -print -exec mv {} . \;

def copy_images(path, imgs, train=True):
    cnt = 0
    cnt_skipped = 0
    for i, img in enumerate(imgs):
        file_path = glob.glob(path + img + '.jpg', recursive=True)
        target_path = os.path.join(TARGET_TRAIN_DIR, img + '.jpg')
        if os.path.exists(target_path):
            print("Skipping ", target_path, cnt_skipped)
            cnt_skipped += 1
            continue
        if not file_path:
            print("Image not found: ", img)
            continue
        print("Copying file ", img, cnt)
        if train:
            shutil.copy(file_path[0], TARGET_TRAIN_DIR + img + '.jpg')
        else:
            shutil.copy(file_path[0], TARGET_TEST_DIR + img + '.jpg')
        cnt += 1

print("--- Extract training images ---")
f = pd.read_csv('../data/raw/inaturalist-user-120k/federated_train_user_120k.csv')
imgs = f['image_id'].tolist()
copy_images('../data/raw/train_val_images/**/', imgs)

print("--- Extract test images ---")
f = pd.read_csv('../data/raw/inaturalist-user-120k/test.csv')
imgs = f['image_id'].tolist()
copy_images('../data/raw/train_val_images/**/', imgs, train=False)


from random import choice

answers = ['Sim', 'Não', 'Sim!', 'Não!', 'Acho que sim...', 'Acho que não...', 'Óbvio que sim', 'Óbvio que não', 'Claro que sim', 'Claro que não', 'Talvez...', 'Melhor não...', 'Com certeza!', 'Não sei...', 'Sei lá', 'Não posso responder isso', 'Você que sabe', 'Se você quer...', 'A decisão é sua!']

while True:

    question = input('Digite sua pergunta: ')

    if question.isalpha() != True and not '?' in question:
        print('Ei, faça uma pergunta!')
        continue

    else:
        print(choice(answers))


import pickle
import numpy as np
from scipy.io import loadmat
import os
import sys

i = int(sys.argv[1]) if len(sys.argv)>1 else 0

step=1
lion_extended_power_options = np.arange(1, 200+step, step)
lion_extended_power_options = sorted(list(lion_extended_power_options) + [13.8, 16.5, 21.1, 26.6])
#Those are found by cross-validation below. Just want to estimate accuracy at those spots

lion_extended_percentile_options = [90,95,99,100]

ptsne_train_mat = loadmat('mnist_train.mat')
ptsne_test_mat = loadmat('mnist_test.mat')

accuracy_nn = 10

ptsne_mapped = loadmat('mnist_mapped.mat') # We need Y to take as ground truth
ptsne_Y_train = ptsne_mapped['mapped_train_X']
ptsne_Y_test = ptsne_mapped['mapped_test_X']

ptsne_X_train = ptsne_train_mat['train_X']
ptsne_labels_train = ptsne_train_mat['train_labels'].reshape(-1)-1
ptsne_X_test = ptsne_test_mat['test_X']
ptsne_labels_test = ptsne_test_mat['test_labels'].reshape(-1)-1

lion_extended_accuracy_plot_data_file = './lion-processed-samples/lion_extended_accuracy_plot_data_'+str(i)+'.p'

with open('cell_centers.p', 'rb') as f:
    cell_centers = pickle.load(f)

# This cell calculates test set accuracy for each combination of power and radius_x percentile

np.random.seed(111222)

# Leaving it extensible to get smth like "KL vs power" etc. if we need to.
regenerate_extended_lion_accuracy = False

lion_extended_accuracy_plot_data = dict()
lion_extended_precision_30_plot_data = dict()
lion_extended_precision_50_plot_data = dict()
already_tested_keys = dict()

with open('extended_nn_dist.p', "rb") as f:
    nn_x_extended_distance, nn_y_extended_distance = pickle.load(f)

radius_y = np.percentile(nn_y_extended_distance, 100)
radius_y_close = np.percentile(nn_y_extended_distance, 10)
radius_y += radius_y_close

radius_extended_x = dict()
for p in lion_extended_percentile_options:
    radius_extended_x[p] = np.percentile(nn_x_extended_distance, p)

# One at a time, so no such things as outliers overlap, etc.

sample_accuracy = dict()
sample_precision_30 = dict()
sample_precision_50 = dict()

def ptsne_get_nearest_neighbors_in_y(y, ptsne_Y_train, n,i=-1):
    y_distances = np.sum((ptsne_Y_train - y)**2, axis=1)
    if i>=0:
        y_distances[i] = np.inf
    return np.argsort(y_distances)[:n]

print("Processing:", i)

with open('./ExtendedDistanceVectors/test_' + str(i) + '.p', 'rb') as f:
    x_distances_to_all_training_samples = pickle.load(f)

y_result = dict()  # Embeddings in all cases

# If we got exact match, power and percentile does not matter, response is the same
exact_match = np.where(x_distances_to_all_training_samples == 0)[0]
if len(exact_match) > 0:
    print("Exact match!")
    # If we got exact match, power and percentile does not matter, response is the same
    for perc in lion_extended_percentile_options:
        for p in lion_extended_power_options:
            key = str(perc) + ";" + "%.3f" % (p)
            if key not in already_tested_keys:
                y_result[key] = ptsne_Y_train[exact_match[0], :]
else:
    # Not an exact match. Need to go further.
    for perc in lion_extended_percentile_options:
        # print(perc)
        # This part depends only on radius_x
        cur_neighbor_indices = np.where(x_distances_to_all_training_samples <= radius_extended_x[perc])[0]
        local_interpolation_distances = x_distances_to_all_training_samples[cur_neighbor_indices]
        # print(cur_neighbor_indices)
        # print(local_interpolation_distances)
        if len(local_interpolation_distances) == 0:  # Outlier handling does not depend on power.
            # print(perc, 0)
            for p in lion_extended_power_options:
                key = str(perc) + ";" + "%.3f" % (p)
                # No need to pop. Each sample is independent anyway
                if key not in already_tested_keys:
                    y_result[key] = cell_centers[np.random.randint(0, len(cell_centers)), :]
        elif len(local_interpolation_distances) == 1:  # Single-neighbor handling does not depend on power
            # print(perc, 1)
            # Now a single neighbor
            single_neighbor_index = cur_neighbor_indices[0]
            single_neighbor_nn_dist = nn_x_extended_distance[single_neighbor_index]
            if single_neighbor_nn_dist <= radius_extended_x[perc]:
                # Treat as outliers
                for p in lion_extended_power_options:
                    key = str(perc) + ";" + "%.3f" % (p)
                    # No need to pop. Each sample is independent anyway
                    if key not in already_tested_keys:
                        y_result[key] = cell_centers[np.random.randint(0, len(cell_centers)), :]
            else:
                for p in lion_extended_power_options:
                    key = str(perc) + ";" + "%.3f" % (p)
                    if key not in already_tested_keys:
                        random_dist = np.random.uniform(low=0, high=radius_y_close)
                        random_angle = np.random.uniform(low=0, high=2 * np.pi)
                        y_result[key] = ptsne_Y_train[single_neighbor_index, :].copy()
                        y_result[key][0] += random_dist * np.cos(
                            random_angle)  # Considering 0 is X. DOes not matter, really
                        y_result[key][1] += random_dist * np.sin(random_angle)
        else:
            # print(perc, 2)
            for p in lion_extended_power_options:
                key = str(perc) + ";" + "%.3f" % (p)
                # weights = 1 / np.array([decimal.Decimal(i) for i in local_interpolation_distances]) ** p
                if key not in already_tested_keys:
                    weights = 1 / local_interpolation_distances ** p
                    weights = weights / np.sum(weights)
                    y_result[key] = weights.dot(ptsne_Y_train[cur_neighbor_indices, :])

print("Got results")

# TODO Got results for all cases
for perc in lion_extended_percentile_options:
    for p in lion_extended_power_options:
        key = str(perc) + ";" + "%.3f" % (p)
        print(perc, p, key)

        expected_label = ptsne_labels_test[i]
        result = y_result[key]
        nn_indices = ptsne_get_nearest_neighbors_in_y(result, ptsne_Y_train, n=accuracy_nn)
        obtained_labels = ptsne_labels_train[nn_indices]
        sample_accuracy[key] = sum(obtained_labels == expected_label) / len(obtained_labels)

        nn_x_indices = ptsne_get_nearest_neighbors_in_y(ptsne_X_test[i,:], ptsne_X_train, n=30)
        nn_y_indices = ptsne_get_nearest_neighbors_in_y(result, ptsne_Y_train, n=30)
        matching_indices = len([k for k in nn_x_indices if k in nn_y_indices])
        sample_precision_30[key] = (matching_indices / 30)

        nn_x_indices = ptsne_get_nearest_neighbors_in_y(ptsne_X_test[i,:], ptsne_X_train, n=50)
        nn_y_indices = ptsne_get_nearest_neighbors_in_y(result, ptsne_Y_train, n=50)
        matching_indices = len([k for k in nn_x_indices if k in nn_y_indices])
        sample_precision_50[key] = (matching_indices / 50)

        print("\t", sample_accuracy[key], sample_precision_30[key], sample_precision_50[key])

with open(lion_extended_accuracy_plot_data_file, 'wb') as f:
    pickle.dump((y_result, sample_accuracy, sample_precision_30,
                 sample_precision_50), f)


#!/usr/bin/env python3
import argparse
import torch

def main(args):
    res = []

    combos = torch.combinations(torch.arange(0, args.n_modules), args.n_active).numpy().tolist()
    for i, subset in enumerate(combos):
        if args.head_id in subset:
            res.append(str(i))

    print("{}".format(" ".join(res)))

def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument(
        "--head-id", type=int, required=True)
    parser.add_argument(
        "--n-modules", type=int, required=True)
    parser.add_argument(
        "--n-active", type=int, required=True)
    return parser.parse_args()

if __name__ == "__main__":
    main(parse_args())


#capture.py

import cv2

#顔検出器を初期化
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
#映像を読み込むオブジェクト
cap= cv2.VideoCapture(0) #0はデフォルトのカメラデバイス

ret,frame = cap.read()
#グレイスケール化
faces = face_cascade.detectMultiScale(cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY))

if len(faces) > 0:
    (x,y,w,h) = faces[0] #顔検出器によって返される位置情報を変数に取る
    track_window = (x,y,w,h) #トラッキングウィンドウの位置とサイズ
    roi = frame[y:y+h, x:x+w] #region of interest. 顔がある部分の領域
    hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV) #BGR色空間からHSV色空間に変換
    mask = cv2.inRange(hsv_roi,(0,60,32),(180,255,255)) #指定範囲内の色は白に、それ以外は黒に変換
    roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180]) #指定された色相のヒストグラムを計算
    cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX) #ヒストグラムの正規化とスケーリング
    term_crit = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1) #トラッキング処理（後述）の停止基準。10回繰り返したら終了

while True:
    #カメラからフレームを取得
    ret, frame = cap.read()

    #フレームの取得に成功したら
    if ret:
        hsv=cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
        dst=cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1) #ヒストグラムの逆投影を行う
        ret, track_window=cv2.meanShift(dst,track_window,term_crit) #トラッキングを行う
        x,y,w,h=track_window
        cv2.rectangle(frame, (x,y),(x+w,y+h),(0,255,0),2)

        #フレームをウィンドウで表示
        cv2.imshow('Camera',frame)
    #qを押したらループ解除
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
#終了動作
cap.release()
cv2.destroyAllWindows()


import boto3
from botocore.exceptions import ClientError
from botocore.client import Config
import env
import json

aws_access_key_id = env.AWS_ACCESS_KEY_ID
aws_secret_access_key = env.AWS_SECRET_ACCESS_KEY

session = boto3.Session(
    aws_access_key_id=aws_access_key_id,
    aws_secret_access_key=aws_secret_access_key,
    region_name = env.AWS_REGION
)

s3 = session.resource('s3')
expected = 'well-s3-bucket'

for bucket in s3.buckets.all():
    if 'well-s3-bucket' in bucket.name:
        assert bucket.name == expected
        print(bucket.name + ' was created')
        print(f"S3 Bucket was created on {bucket.creation_date}")


from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException, WebDriverException
import firebase_admin
from firebase_admin import credentials
from firebase_admin import db

cred_obj = firebase_admin.credentials.Certificate('firebase-sdk.json')
firebase_admin.initialize_app(cred_obj, {
	'databaseURL': 'https://wise-monitor-price-default-rtdb.asia-southeast1.firebasedatabase.app/'
	})

chrome_path = r"C:\Users\gundu\PycharmProjects\pythonProject\drivers\chromedriver.exe"
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--incognito")
browser = webdriver.Chrome(chrome_path, options=chrome_options)
ref = db.reference('/')
ref.child('Pacific').delete()

# method for finding product name and price
def findItem():
    product = browser.find_elements_by_xpath(
        './/*[@class="product_grid-item grid__item product_img-crop ratio_1-1 small--one-half medium--one-half large--one-quarter"]')
    product2 = browser.find_elements_by_xpath(
        './/*[@class="product_grid-item grid__item product_img-crop ratio_1-1 small--one-half medium--one-half large--one-quarter on-sale"]')

    for post in product:
        name = post.find_element_by_xpath('.//*[@class="grid-link__title"]').text
        price = post.find_element_by_xpath('.//*[@data-currency="MYR"]').text

        ref = db.reference('Pacific')
        emp_ref = ref.push({
                        'name': name,
                        'price': price
            })

    for post2 in product2:
        name2 = post2.find_element_by_xpath('.//*[@class="grid-link__title"]').text
        price2 = post2.find_element_by_xpath('.//*[@data-currency="MYR"]').text
        ref = db.reference('Pacific')
        emp_ref = ref.push({
            'name': name2,
            'price': price2
            })

    print("new data created")

# delete the # in the list below to retrieve the products' name and price from the link
url = {#'https://www.pacific-online.com.my/collections/groceries',
#'https://www.pacific-online.com.my/collections/toiletries',
#'https://www.pacific-online.com.my/collections/wet-tissues-diapers-napkin',
#'https://www.pacific-online.com.my/collections/beauty',
#'https://www.pacific-online.com.my/collections/toiletries-health-beauty',
#'https://www.pacific-online.com.my/collections/household-1',
#'https://www.pacific-online.com.my/collections/pets-care',
'https://www.pacific-online.com.my/collections/beverages/coffee'}
for link in url:
    browser.get(link)
    print(link)
    findItem()              # scrap first page

                        # move to next page
    while True:
        try:
            browser.execute_script("return arguments[0].scrollIntoView(true);",WebDriverWait(browser, 10).until(
             EC.presence_of_element_located((By.XPATH, "//a[@title = 'Next']"))
                 ))
            browser.find_element_by_xpath("//a[@title = 'Next']").click()

            print("------------------Next Page-----------------")
            # scraping the following pages
            findItem()
        except (TimeoutException, WebDriverException) as e:
            print("Last page reached")
            break


from __future__ import absolute_import, print_function, division, unicode_literals

import os
import io
import sys
import hashlib
import datetime
import logging
import json

from ..app import db

file_types = {
    "jpg": ("images", "image/jpeg"),
    "mp3": ("sounds", "audio/mp3"),
    "mp4": ("videos", "video/mp4"),
    "stl": ("models", "model/mesh")
}

type_dc_type = {
    "images": "StillImage",
    "sounds": "Sound",
    "videos": "MovingImage",
    "models": "InteractiveResource"
}

def check_update(m, p, current_user, guid_type=None):
    h = calcFileHash(p)
    if m.image_hash == h:
        return m
    m.status = "file_changed"
    m.status_date = datetime.datetime.now()
    m.status_detail = m.image_hash
    m.image_hash = h
    m.appuser = current_user
    props = json.loads(m.props)
    config = json.loads(current_user.config)
    props["dc:rights"] = config.get("license", "CC0")
    m.props = json.dumps(props)
    if guid_type == "hash":
        m.file_reference = h
    return m

def calcFileHash(f, op=True, return_size=False, read_size=2048):
    def do_hash(fd):
        md5 = hashlib.md5()
        size = 0

        buf = fd.read(read_size)
        while len(buf) > 0:
            size += len(buf)
            md5.update(buf)
            buf = fd.read(read_size)

        return md5, size

    if op:
        with io.open(f, "rb") as fd:
            md5, size = do_hash(fd)
    else:
        md5, size = do_hash(f)

    if return_size:
        return (md5.hexdigest(), size)
    else:
        return md5.hexdigest()

def process_media(m, update_db=True, api=None):
    try:
        if os.path.exists(m.path):
            h, size = calcFileHash(m.path, return_size=True)
            m.image_hash = h

            for k in file_types:
                if m.path.lower().endswith(k):
                    m.media_type, m.mime = file_types[k]
                    break
            else:
                raise TypeError("Invalid File Type {}".format())

        else:
            raise FileNotFoundError

        # Upload Media File
        if api is None:
            m.status = "uploaded"
            m.status_date = datetime.datetime.now()
            m.status_detail = ""
        else:
            logging.debug("Start post for %r", m.path)
            res = api.upload(m.file_reference, m.path)
            logging.debug("Finished post for %r got back %r", m.path, res)
            if res is None:
                m.status = "failed"
                m.status_date = datetime.datetime.now()
                m.status_detail = ""
            else:
                m.status = "uploaded"
                m.status_date = datetime.datetime.now()
                m.status_detail = ""

        if update_db:
            db.session.add(m)
            db.session.commit()

    except FileNotFoundError:
        e = sys.exc_info()[1]
        m.status = "missing"
        m.status_date = datetime.datetime.now()
        m.status_detail = repr(e)

    return m


import pandas as pd
from pathlib import Path
import subprocess
from bianca import __version__

def get_subject_sessions(bids_dir, flair_acq):
    def _get_suse_from_path(p):
        session = p.parents[1].name.replace("ses-", "")
        subject = p.parents[2].name.replace("sub-", "")
        return subject, session

    flair_files = list(Path(bids_dir).glob(f"sub-*/ses-*/anat/*_acq-{flair_acq}_*_FLAIR.nii.gz"))
    t1w_files = list(Path(bids_dir).glob(f"sub-*/ses-*/anat/*_T1w.nii.gz"))
    flair_suse = set([_get_suse_from_path(p) for p in flair_files])
    t1w_suse = set([_get_suse_from_path(p) for p in t1w_files])
    subject_sessions = list(flair_suse & t1w_suse)
    subject_sessions.sort()
    return subject_sessions

def export_version(out_dir):
    out_dir.mkdir(parents=True, exist_ok=True)
    try:
        version_label = subprocess.check_output(["git", "describe", "--tags"]).strip()
        (out_dir / "pipeline_version.txt").write_text(f"git: {version_label.decode()}")
    except:
        (out_dir / "pipeline_version.txt").write_text(__version__)

def create_masterfile(prep_dir, training_data_dir, bianca_dir, flair_tmpl, t1w_tmpl, manual_mask_tmpl,
                      mat_tmpl):
    bianca_dir.mkdir(exist_ok=True, parents=True)

    # get flair files
    flair_globs = list(prep_dir.glob(flair_tmpl.format(subject="*", session="*")))
    print(f"{len(flair_globs)} flair files found")

    # get remaining files
    df = pd.DataFrame({"flair": [str(f) for f in flair_globs]})
    df["subject"] = df.flair.str.split("sub-").str[1].str.split("/").str[0]
    df["session"] = df.flair.str.split("ses-").str[1].str.split("/").str[0]

    complete_files = {"t1w": str(prep_dir / t1w_tmpl),
                      "manual_mask": str(training_data_dir / manual_mask_tmpl),
                      "mat": str(prep_dir / mat_tmpl)
                      }
    for var in complete_files.keys():
        df[var] = None
    for i in range(len(df)):
        for var in complete_files.keys():
            df[var].iloc[i] = complete_files[var].format(**df.iloc[i])

    df = df[['flair', 't1w', 'manual_mask', 'mat', 'subject', 'session']]

    # only include masks from training subjects
    training_subject_index = df.manual_mask.apply(lambda s: Path(s).is_file())
    df.loc[~training_subject_index, "manual_mask"] = "XXX"
    training_subjects = df[training_subject_index]

    # check if files exist
    files = df[['flair', 't1w', 'manual_mask', 'mat']].melt()["value"].to_list()
    for f in files:
        if f != "XXX":
            assert Path(f).is_file(), f"{f} is missing"

    # save
    df.to_csv(bianca_dir / "masterfile.txt", index=False, header=False, sep=" ")
    df.to_csv(bianca_dir / "masterfile_wHeader.txt", index=False, sep=" ")
    training_subjects.to_csv(bianca_dir / "masterfile_training_subjects.txt", index=False, sep=" ")


#!/usr/bin/env python3

import re

RE_DEFAULT = re.compile(r"\[D=([TF])\] ")
RE_TRANSITION = re.compile(r"([a-zA-Z0-9 \[\]=#_-]+) *->(.*)")
RE_ASSERTION = re.compile(
    r"\[A S=([a-zA-Z01_]+) SS=([a-zA-Z01_]+) ES=([a-zA-Z01_]+) P=([a-zA-Z_]+) ESP=([a-zA-Z_]+)\]"
)
RE_ASSERTION_SHORTHAND = re.compile(r"\[A#([0-9T]+)\]")

# ======================================================================
# ======================================================================

testnum = 1

def start_test(line):
    global testnum
    output.write(
        """
    def test_{0}(self):
        # {1}...\n""".format(
            testnum, line[0:80]
        )
    )
    testnum += 1

def set_default(d):
    output.write(
        """
        if self.default_is is not {0}:
            return\n""".format(
            "True" if d == "T" else "False"
        )
    )

def enroll(e):
    if e.endswith("-C"):
        e = e[:-2]
        output.write("\n        # Re-set enrollment pref, like Normandy would do\n")
    output.write(
        "        self.set_enrollment_status(ExperimentStatus.ENROLLED_{0})\n".format(
            e.upper()
        )
    )

def set_pref(enabled):
    output.write(
        "\n        self.marionette.set_pref(Prefs.WIN32K, {0})\n".format(str(enabled))
    )

def set_e10s(enable):
    if enable:
        output.write(
            """
        app_version = self.execute_script("return Services.appinfo.version")
        self.restart(env={ENV_DISABLE_E10S: app_version})
        self.set_env(ENV_DISABLE_E10S, "null")\n"""
        )
    else:
        raise Exception("Not implemented")

def set_header(enable):
    if enable:
        output.write(
            """
        self.restart(env={ENV_DISABLE_WIN32K: "1"})\n"""
        )
    else:
        output.write(
            """
        self.set_env(ENV_DISABLE_WIN32K, "")\n"""
        )

def set_bad_requirements(enabled):
    output.write(
        """
        self.marionette.set_pref(Prefs.WEBGL, {0})\n""".format(
            "False" if enabled else "True"
        )
    )

def restart():
    output.write("\n        self.restart()\n")

def print_assertion(assertion):
    if not assertion:
        return
    output.write(
        """
        self.check_win32k_status(
            status=ContentWin32kLockdownState.{0},
            sessionStatus=ContentWin32kLockdownState.{1},
            experimentStatus=ExperimentStatus.{2},
            pref={3},
            enrollmentStatusPref=ExperimentStatus.{4},
        )\n""".format(
            *assertion
        )
    )

# ======================================================================
# ======================================================================

TESTS = open("win32k_tests.txt", "r").readlines()

output = open("test_win32k_enrollment.py", "w", newline="\n")
header = open("test_win32k_enrollment.template.py", "r")
for l in header:
    output.write(l)

mappings = {}
for line in TESTS:
    line = line.strip()
    if not line:
        continue

    if line.startswith("#"):
        continue
    elif line.startswith("> "):
        line = line[2:]
        key, value = line.split(":")
        mappings[key.strip()] = value.strip()
        continue
    elif line.startswith("-"):
        line = line[1:].strip()
    elif line.startswith("+"):
        line = line[1:].strip()
        import pdb

        pdb.set_trace()
    else:
        raise Exception("unknown line type: " + line)

    # We can't handle Safe Mode right now
    if "Safe Mode" in line:
        continue

    # If we have no assertions defined, skip the test entirely
    if "[A" not in line:
        continue

    if not RE_DEFAULT.match(line):
        raise Exception("'{0}' does not match the default regex".format(line))
    default = RE_DEFAULT.search(line).groups(1)[0]

    start_test(line)

    set_default(default)

    line = line[6:]

    while line:
        # this is a horrible hack for the line ending to avoid making the
        # regex more complicated and having to fix it
        if not line.endswith(" ->"):
            line += " ->"

        groups = RE_TRANSITION.search(line).groups()
        start = groups[0].strip()
        end = groups[1].strip()

        if RE_ASSERTION.search(start):
            assertion = RE_ASSERTION.search(start).groups()
            start = start[0 : start.index("[")].strip()
        elif RE_ASSERTION_SHORTHAND.search(start):
            key = RE_ASSERTION_SHORTHAND.search(start).groups()[0]
            assertion = RE_ASSERTION.search(mappings[key]).groups()
            start = start[0 : start.index("[")].strip()
        else:
            assertion = ""

        if start == "Nothing":
            pass
        elif start.startswith("Enrolled "):
            enroll(start[9:])
        elif start == "E10S":
            set_e10s(True)
        elif start == "Header-On":
            set_header(True)
        elif start == "Header-Off":
            set_header(False)
        elif start == "Bad Requirements":
            set_bad_requirements(True)
        elif start == "Restart":
            restart()
        elif start == "On":
            set_pref(True)
        elif start == "Off":
            set_pref(False)
        else:
            raise Exception("Unknown Action: " + start)

        print_assertion(assertion)

        line = end.strip()

    if RE_ASSERTION.match(line):
        print_assertion(RE_ASSERTION.search(line).groups())
    elif RE_ASSERTION_SHORTHAND.search(line):
        key = RE_ASSERTION_SHORTHAND.search(line).groups()[0]
        print_assertion(RE_ASSERTION.search(mappings[key]).groups())


import numpy as np

def instructions_from_file(filepath: str):
    """
    Reads input from a given file and returns the seat layout as a
    numpy 2D array (ndarray).
    """
    with open(filepath, "r") as file:
        instructions = [(line[0], int(line[1:]))  for line in file.readlines()]
    return instructions

def go_direction(coords: tuple, direction: str, amount: int):
    x, y = coords
    if direction == "N":
        y += amount
    elif direction == "S":
        y -= amount
    elif direction == "E":
        x += amount
    elif direction == "W":
        x -= amount
    return x, y

def run_ship(instructions: list):
    x, y = 0, 0
    dirs = ["N", "E", "S", "W"]
    facing = "E"
    for instruction in instructions:
        direction, amount = instruction
        x, y = go_direction((x,y), direction, amount)    # Move N, E, S, W
        if direction == "F":
            x,y = go_direction((x,y), facing, amount)
        if direction == "L":
            # L rotation is inverted R rotation
            amount = -amount
            direction = "R"
        if direction == "R":
            facing = dirs[(dirs.index(facing)+(amount//90))%4]

    print("Part 1:", abs(x)+abs(y))

def run_with_waypoint(instructions: list):
    ship_x, ship_y = 0, 0
    way_x, way_y = 10, 1
    for rule in instructions:
        direction, amount = rule
        way_x,way_y = go_direction((way_x,way_y), direction, amount)
        if direction == "F":
            ship_x += way_x * amount
            ship_y += way_y * amount
        if amount == 180 and (direction == "R" or direction == "L"):
            way_x, way_y = -way_x, -way_y
        elif direction == "L":
            way_x, way_y = -way_x, -way_y
            direction = "R"

        if direction == "R":
            if amount == 90:
                way_x, way_y = way_y, -way_x
            if amount == 270:
                way_x, way_y = -way_y, way_x

    print("Part 2:", abs(ship_x) + abs(ship_y))

def main(file: str):
    """
    Main function. Contains top-level logic.
    """
    instructions = instructions_from_file(file)
    # Part 1
    run_ship(instructions)
    # Part 2 - with Waypoint
    run_with_waypoint(instructions)

if __name__ == "__main__":
    print("-- TEST --")
    main("test.txt")
    print("-- REAL --")
    main("input.txt")


from configparser import ConfigParser
import os.path
import sys
from dotenv import load_dotenv

config_object = ConfigParser()

load_dotenv()

api_key = os.getenv('api_key')
api_secret = os.getenv('api_secret')

if not api_key or not api_secret:
    if not os.path.isfile("config.ini"):
        print("Check config file config.ini for api key parameters")

        config_object.add_section('API_CONFIG')
        config_object.set('API_CONFIG', 'api_key', 'xxxx')
        config_object.set('API_CONFIG', 'api_secret', 'xxxx')

        with open(r"config.ini", 'w') as configfile:
            config_object.write(configfile)

        sys.exit()

    config_object.read("config.ini")

    api_key = config_object['API_CONFIG']['api_key']
    api_secret = config_object['API_CONFIG']['api_secret']


import discord
import json
import os
from discord.ext import commands

client = commands.Bot(command_prefix= '!w2g')

os.chdir("path completo")

@client.event
async def on_ready():
    print('Bot is ready.')

@client.event
async def on_member_join(meber):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, member)

    with open('users.json', 'w') as f:
        json.dump(users, f)

@client.event
async def on_message(message):
    with open('users.json', 'r') as f:
        users = json.load(f)

    await update_data(users, message.author)
    await add_experience(users, message.author, 5)
    await level_up(users, message.author, message.channel)

    with open('users.json', 'w') as f:
        json.dump(users, f)

async def update_data(users, users):
    if not user.id in users:
        users[user.id] = {}
        users[user.id]['experience'] = 0
        users[user.id]['level'] = 1

async def add_experience(users, user, exp):
    users[user.id]['experience'] += exp

async def level_up(users, user, chennel):
    experience = users[user.id]['experience']
    lvl_start = users[user.id]['level']
    lvl_end = int(experience ** (1/4))

    if lvl_start < lvl_end:
        await client.send_message(channel, '{} upou de levels'.format(user.mention, lvl_end))
        users[user.id]['level'] = lvl_end
client.run('NzcyNTAxMzYyNjgzNTQzNTYz.X57l9Q.tiBFZwKM02qDv7emjtLBkNVxvFk')


import time,random,sqlite3

conn = sqlite3.connect('scores.db')
c = conn.cursor()

# Create the table if it doesn't exist
c.execute('CREATE TABLE IF NOT EXISTS scores (username TEXT, score INTEGER)')

difficulty,players,hints,category,username=[0,0,0,0,0]

# all the words that will pop up for hangman
words = {
    'Animals': {
        'Easy': ['zebra', 'tiger', 'snake', 'shark', 'whale', 'otter', 'panda', 'koala', 'chimp', 'puppy', 'eagle', 'hippo', 'raven', 'stork', 'hyena', 'skunk', 'rhino', 'goose'],
        'Medium': ['panther', 'gazelle', 'penguin', 'buffalo', 'giraffe', 'elephant', 'octopus', 'chicken', 'jaguar', 'hamster', 'seagull', 'sparrow', 'badgers', 'kangaro',  'platypu', 'lobster', 'wallaby'],
        'Hard': ['crocodile', 'porcupine', 'rhinoceros', 'alligator', 'kangaroos', 'jellyfish', 'chameleons', 'hummingbird', 'butterfly', 'orangutans', 'dolphinews', 'porpoises', 'hippopotam', 'woodpecker', 'platypuses', 'cheetahs', 'anteaters', 'squirrels', 'flamingoes', 'chinchilla']
    },
    'Countries': {
        'Easy': ['japan', 'china', 'india', 'spain', 'italy', 'chile', 'kenya', 'egypt', 'nepal','sudan', 'nepal', 'yemen',  'libya', 'malta'],
        'Medium': ['belgium', 'morocco', 'ireland', 'germany', 'colombi', 'bahrain', 'pakistan', 'romania', 'mongolia', 'nigeria', 'denmark', 'haiti', 'oman', 'brazil', 'namibia', 'jamaica', 'thailand', 'india', 'kazakhs', 'mongoli'],
        'Hard':  ['zimbabwean', 'azerbaijan', 'czechoslov', 'bangladesh', 'guadeloupe', 'macedonian', 'mauritania', 'afghanista', 'micronesia', 'montserrat', 'vietnamese', 'azerbaijan', 'argentinia', 'kyrgyzstan']
    },
    'Fruits': {
        'Easy': ['grape', 'apple', 'mango', 'peach', 'melon', 'lemon', 'berry','olive', 'pears', 'grape', 'avoca', 'pears', 'dates', 'guava', 'pawpaw', 'prune'],
        'Medium': ['mangoes', 'apricot', 'avocado', 'coconut', 'kiwifruit', 'mangost', 'papayas', 'peaches', 'plumcot', 'soursop', 'bananas'],
        'Hard': ['blackberry', 'pomegranat', 'honeycrisp',  'persimmons', 'bloodorang', 'tamarillos', 'boysenberr', 'ackeefruit', 'watermelon', 'kiwiberrie',  'cantaloupe', 'clementine',  'guavafruit']}}

def hint(gussedletters,Secretword):
    # finds a letter thats part of the secret word and shows it
    valid_letters = [letter for letter in Secretword if letter not in gussedletters]
    gussed_letter=random.choice(valid_letters)
    print(f"Hint {gussed_letter} has been added!")
    gussedletters.append(gussed_letter)
    return gussed_letter

def play(difficulty,hints,category):
    global list,username
    # number of lives
    Lives=6
    gussedletters=[]
    # number of hints per difficulty
    guesses={"Easy":3, "Medium":2, "Hard":1}
    if category ==0:
        category= random.choice(["Animals","Countries","Fruits"])
        print(f"No category selected. Choosing {category} instead.")
    if difficulty==0:
        difficulty=random.choice(["Easy","Medium","Hard"])
        print(f"No difficulty selected. Choosing {difficulty} instead.")
    word = words[category][difficulty]
    Secretword=random.choice(word).lower()
    length=len(Secretword)
    blanks=length*"_"
    # incase a costume hint is chosen in the main menue
    if hints==0:
        guesses=guesses[difficulty]
    else:
        guesses=hints
    print("The Game has begun!")
    print("\nDuring any point of the game, you may type 'hint' in order to use any of your remaining hints!\n")
    print("During any point of the game, you may type the word!\n")
    print(f"You've got {guesses} hints!\n")
    print(f"the word has {length} letters!")

    # runs till the word is found or the player runs out of lives
    while Lives>=1:
        if blanks==Secretword:
            print(f"You got it right with {Lives} lives remaning!")
            time.sleep(3)
            # Score calculation
            score=Lives*100+hints*100
            if difficulty=="Hard":
                score+=1000
            elif difficulty=="Medium":
                score+=500
            print(f"{username} has completed {difficulty} difficulty having {guesses} hints available and having {Lives} lives remaining.\nOverall score: {score} points!")
            # Adds it to the database
            c.execute('INSERT INTO scores (username, score) VALUES (?, ?)', (username, score))
            conn.commit()
            main()
        # prints the blanks including the found letters
        print(blanks)
        try:
            letterguess=str(input("\nGuess a letter:")).lower()
            # if there are hints avalible and the player would like to use them
            if letterguess=="hint" and guesses>0:
                guessedletter=hint(gussedletters,Secretword)
                positions = [i for i, letter in enumerate(Secretword) if letter in guessedletter]
                for i in positions:
                    blanks = blanks[:i] + guessedletter + blanks[i+1:]
                guesses-=1
                continue
            # if there are no hints available and the player would like to use them
            if letterguess=="hint" and guesses==0:
                print("\nyou've ran out of hints!:(")
                continue
            # incase the user guesses the word
            if letterguess==Secretword:
                blanks=Secretword
                print("Congragulations! you've got it right!")
                continue
            # incorrect input
            elif len(letterguess)<1 or len(letterguess)>1:
                raise
            # repetition of guesses
            elif letterguess in gussedletters:
                print("you've already gussed this letter!")
                continue
        except:
            print("Thats not a valid input!")
            continue
        # guessed letter correctly
        if letterguess in Secretword:
            print(letterguess,"Is in the secret word!")
            positions = [i for i, letter in enumerate(Secretword) if letter in letterguess]
            for i in positions:
                blanks = blanks[:i] + letterguess + blanks[i+1:]
        else:
            print("thats not correct")
            Lives-=1
            print(f"You've got {Lives} Lives left!")
        gussedletters.append(letterguess)
    if Lives==0:
        print(f"The secret word was {Secretword}!!")

def difficulty_choice():
    # option to choose difficulty
    while True:
        print("========================================")
        print("|        Choose Difficulty Level       |")
        print("========================================")
        print("| 1. Easy (5 letter words, 6 guesses)  |")
        print("| 2. Medium (7 letter words, 4 guesses)|")
        print("| 3. Hard (10 letter words, 2 guesses) |")
        print("| 4. Back to Main Menu                 |")
        print("========================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3,4]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        return("Easy")

    elif playerschoice==2:
        return("Medium")
    elif playerschoice==3:
        return("Hard")
    elif playerschoice==4:
        main()

def hint_choice():
    # option to choose hint difficulty level
    while True:
        print("==================================")
        print("|          Hint System           |")
        print("==================================")
        print("| 1. Easy (2 hints per game)     |")
        print("| 2. Medium (1 hint per game)    |")
        print("| 3. Hard (no hints)             |")
        print("| 4. Back to Main Menu           |")
        print("==================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3,4]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        return(2)
    elif playerschoice==2:
        return(1)
    elif playerschoice==3:
        return(0)
    elif playerschoice==4:
        main()

def categories_choice():
    # option to chosse what category of words
    while True:
        print("==================================")
        print("|         Word Categories        |")
        print("==================================")
        print("| 1. Animals                     |")
        print("| 2. Countries                   |")
        print("| 3. Fruits                      |")
        print("| 4. Back to Main Menu           |")
        print("==================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3,4]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        return("Animals")
    elif playerschoice==2:
        return("Countries")
    elif playerschoice==3:
        return("Fruits")
    elif playerschoice==4:
        main()

def scoreboard():
    # option to show or clear the score board
    while True:
        print("==================================")
        print("|      High Score Tracking       |")
        print("==================================")
        print("| 1. View High Scores            |")
        print("| 2. Clear High Scores           |")
        print("| 3. Back to Main Menu           |")
        print("==================================")
        playerschoice=input("Enter your choice: ")
        # makes sure the input is correct
        if playerschoice.isdigit() and int(playerschoice) in [1,2,3]:
            break
        else:
            print("Please pick a digit between 1-4!")
            time.sleep(2)
    playerschoice=int(playerschoice)
    if playerschoice==1:
        # Retrieve the scores from the database and display them
        c.execute('SELECT * FROM scores ORDER BY score DESC')
        sorted_items = c.fetchall()
        if sorted_items:
            print("Leaderboard:")
            for rank, (username, score) in enumerate(sorted_items, start=1):
                print(f"{rank}. {username}: {score}")
        else:
            print("no one has played yet!")
    elif playerschoice==2:
        # deletes the score board data
        c.execute('DELETE FROM scores')
        conn.commit()
        print("Leaderboard has been cleared!\n")
    elif playerschoice==3:
        main()

def main():
    # shows main menue and checks to see if the username is taken
    global difficulty,hints,category,username
    while True:
        username = input("Please enter your name: ")
        rand_num = str(random.randint(0, 9999)).zfill(4)
        username=(f"{username}#{rand_num}")
        c.execute('SELECT * FROM scores WHERE username=?', (username,))
        result = c.fetchone()
        if result is not None or username=='':
            print("Sorry, that username is unavailable. Please choose another.")
            username=0
            continue
        break

    print(f"Hello, {username}!")
    while True:
        print("==================================")
        print("|       Welcome to Hangman!      |")
        print("==================================")
        print("| 1. Play Game                  |")
        print("| 2. Choose Difficulty Level    |")
        print("| 3. Hint System                |")
        print("| 4. Word Categories            |")
        print("| 5. High Score Tracking        |")
        print("| 6. Exit                       |")
        print("==================================")
        # checks to see if input is correct
        try:
            playerschoice=int(input("Enter your choice: "))
            if playerschoice not in [1,2,3,4,5,6]:
                raise
        except:
            print("Please pick a digit between 1-7!")
            time.sleep(2)
            continue
        if playerschoice==1:
            play(difficulty,hints,category)
        elif playerschoice==2:
            difficulty=difficulty_choice()
            print(f"\nDifficulty {difficulty} has been chosen!\n")
        elif playerschoice==3:
            hints=hint_choice()
            print(f"\n{hints} hints has been given!\n")
        elif playerschoice==4:
            category=categories_choice()
            print(f"\n{category} category has been chosen!\n")
        elif playerschoice==5:
            scoreboard()
        elif playerschoice==6:
            break
main()
conn.close()


from core.data_loader import load_data

lower_letters = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z".split(",")
upper_letters = [i.upper() for i in lower_letters]

priority_map = dict(zip(lower_letters + upper_letters, list(range(1, 53))))

data = load_data("backpack_items.txt")

parsed_data = data.split("\n")[:-1]

total = 0

for bag in parsed_data:
    split_point = len(bag)//2
    comp1 = {i for i in bag[:split_point]}
    comp2 = {i for i in bag[split_point:]}
    common = comp1.intersection(comp2)
    total += sum(map(lambda x: priority_map[x], common))

print(total)

###################### PART 2 ###########################

total = 0

start_index = 0
end_index = 3
for _ in range(0, len(parsed_data)//3):
    group = [{i for i in bag} for bag in parsed_data[start_index:end_index]]
    badge = list(group[0].intersection(group[1]).intersection(group[2]))[0]
    total += priority_map[badge]
    start_index += 3
    end_index += 3

print(total)


import json

def main():
    input_filename = "data.json"
    output_filename = "result.json"

    with open(input_filename, "r") as input_file:
        data = json.load(input_file)

    unique_part_numbers = set()
    unique_items = []

    for item in data:
        part_number = item.get("partNumber")
        if part_number and part_number not in unique_part_numbers:
            unique_part_numbers.add(part_number)
            unique_items.append(item)

    with open(output_filename, "w") as output_file:
        json.dump(unique_items, output_file, indent=4)

    print(f"Unique part numbers saved in {output_filename}")

if __name__ == "__main__":
    main()


import matplotlib.pyplot as plt
import numpy as np

N = 5000

def solveLoop(x, y):
    xs = []
    ys = []
    time = []

    t = 0.0
    dt = 0.001
    for i in range(N):
        x += dt * (3 - x - 2 * y)
        y += dt * (2 - x - y)
        t += dt

        xs.append(x)
        ys.append(y)
        time.append(t)

    return xs, ys

x = [0, 0, 3, 1, 4, 5, 6, 7, 8, 9, 10, 0, 1, 2, 3, 5]
y = [0, 2, 0, 1, 4, 0, 3, 2, 10, 9, 5, 1.5, 0, 2, 5, 6]

plotNo = len(x)
xsPlot = np.zeros((plotNo, N))
ysPlot = np.zeros((plotNo, N))

for i in range(len(xsPlot)):
    xsPlot[i, :], ysPlot[i, :] = solveLoop(x[i], y[i])

for i in range(len(xsPlot)):
    plt.plot(xsPlot[i, :], ysPlot[i, :], label="(x,y): " + str(x[i]) + "," + str(y[i]))

plt.legend()
plt.grid()
plt.show()


op = []
idade = []
p = 0
while p < 15:
  """
  forneca a opinião das pessoas como 1 = ruim, 2 = regular, 3 = bom
  """
  idade.append(int(input("qual a idade da pessoa?:")))
  op.append(int(input("qual o nivel de opniao?:")))
  p += 1

media = sum(idade) / len(idade)
print(f"a media da idade do grupo eh: {media} anos")
qreg = op.count(2) #count(op)
print(f"{qreg} pessoas votaram regular")
pbom = (op.count(2) / len(op)) * 100
print(f"{pbom}% das pessoas votaram bom")


#!/usr/bin/python3

from pathlib import Path
import argparse
import hashlib
import json
import os
import re
import subprocess
import urllib.request, urllib.parse, urllib.error

HOME = Path.home()
# Paths.
LOOKUP_DATA_DIR = HOME / ".goto_build"
LOOKUP_DATA_PATH = LOOKUP_DATA_DIR / "build_lookup.json"
CUSTOM_BUILDOZER_PATH = LOOKUP_DATA_DIR / "buildozer"
# Buildozer details.
CUSTOM_BUILDOZER_URL = "https://github.com/kentsommer/buildtools/releases/download/4.2.0-1/buildozer"
CUSTOM_BUILDOZER_SHA = "9a9193b77f51dcff416cdc5039a7a78e7b7ace7b019c1c952ab8028e6ee3303f"

def sha256sum(path):
    """Calculates sha256sum of the file at the given path."""
    h = hashlib.sha256()
    b = bytearray(128 * 1024)
    mv = memoryview(b)
    with open(path, mode="rb", buffering=0) as f:
        for n in iter(lambda: f.readinto(mv), 0):
            h.update(mv[:n])
    return h.hexdigest()

def make_executable(path):
    """Makes the file at the given path executable."""
    mode = os.stat(path).st_mode
    mode |= (mode & 0o444) >> 2  # copy R bits to X
    os.chmod(path, mode)

def fetch_buildozer():
    """Download custom buildozer."""
    # Prepare our directory if it doesn't exist.
    os.makedirs(LOOKUP_DATA_DIR, exist_ok=True)
    # Download buildozer binary.
    buildozer_binary = urllib.request.urlopen(CUSTOM_BUILDOZER_URL).read()
    with open(CUSTOM_BUILDOZER_PATH, mode="wb") as fp:
        fp.write(buildozer_binary)
    make_executable(CUSTOM_BUILDOZER_PATH)

def maybe_fetch_buildozer():
    """Download custom buildozer if not downloaded already."""
    if os.path.isfile(CUSTOM_BUILDOZER_PATH):
        if sha256sum(CUSTOM_BUILDOZER_PATH) != CUSTOM_BUILDOZER_SHA:
            fetch_buildozer()
    else:
        fetch_buildozer()

def build_lookup_data():
    """Build map from file path to corresponding BUILD file and target."""
    lookup_data = subprocess.check_output(
        [
            CUSTOM_BUILDOZER_PATH,
            "print startline path srcs hdrs",
            "//...:*",
        ],
        stderr=subprocess.DEVNULL,
    ).decode("utf-8")
    pattern = re.compile(
        r"^(\d*) (\/.*?BUILD).*?(?:\[(.*?)\]|glob\((.*?)\)|(\(missing\))).*?(?:\[(.*?)\]|glob\((.*?)\)|(\(missing\)))",
        re.DOTALL + re.MULTILINE,
    )
    matches = pattern.findall(lookup_data)
    result = {}
    for match in matches:
        line = match[0]
        BUILD = match[1]
        prefix = BUILD.split("BUILD")[0]
        srcs = [f"{prefix}{src}" for src in match[2].split(" ")] if match[2] else []
        hdrs = [f"{prefix}{hdr}" for hdr in match[5].split(" ")] if match[5] else []
        for src in srcs:
            result[src] = f"{BUILD}:{line}"
        for hdr in hdrs:
            result[hdr] = f"{BUILD}:{line}"
    # Prepare our directory if it doesn't exist.
    os.makedirs(LOOKUP_DATA_DIR, exist_ok=True)
    # Save our file so we can potentially reuse the map for future queries.
    with open(LOOKUP_DATA_PATH, mode="w+", encoding="utf-8") as fp:
        json.dump(result, fp, indent=2)
    return result

def get_corresponding_build_info(args):
    """Load (build if does not exist) the lookup_data map from and return corresponding BUILD file and target.

    Will rebuild the map if src file is not found in the map and file was loaded.
    """
    did_build = False
    # Try to load lookup_data.
    if os.path.isfile(LOOKUP_DATA_PATH):
        with open(LOOKUP_DATA_PATH, mode="r", encoding="utf-8") as fp:
            try:
                lookup_data = json.load(fp)
            # If we have issues loading the json file, build it.
            except json.decoder.JSONDecodeError as ex:
                lookup_data = build_lookup_data()
    # If lookup data does not exist, build it.
    else:
        lookup_data = build_lookup_data()
        did_build = True

    # If our file exists in the map, return the BUILD and target information.
    if args.input in lookup_data:
        return lookup_data[args.input]
    else:
        # If the file does not exist and we did not build, rebuild the map.
        if not did_build:
            lookup_data = build_lookup_data()
        # If the file exists in the newly built map, return the BUILD and target information.
        if args.input in lookup_data:
            return lookup_data[args.input]
    return None

def main(args):
    # Ensure our custom buildozer binary exists.
    maybe_fetch_buildozer()
    # Fetch build info.
    build_info = get_corresponding_build_info(args)
    if build_info:
        print(build_info)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(__doc__)
    parser.add_argument(
        "-i", "--input", required=True, type=str, help="Input file for which to find the corresponding BUILD file"
    )
    args = parser.parse_args()
    main(args)


#!/usr/bin/env python3

import tensorflow as tf
import tensorflow_addons as tfa
import einops

def get_pixel_value(
        img, x, y, data_format=None):
    """
    Utility function to get pixel value for coordinate
    vectors x and y from a  4D tensor image.
    Input
    -----
    - img: tensor of shape (B, H, W, C)
    - x: flattened tensor of shape (B*H*W, )
    - y: flattened tensor of shape (B*H*W, )
    Returns
    -------
    - output: tensor of shape (B, H, W, C)
    """
    if data_format is None:
        data_format = tf.keras.backend.image_data_format()

    if data_format == 'channels_first':
        axis = -3
    else:
        axis = -1

    batch_dims = tf.rank(img) - 3

    # NOTE(ycho): HAS TO BE -1 due to tensorflow constraints.
    # indices[-1]
    indices = tf.stack([y, x], axis=-1)

    if data_format == 'channels_first':
        img = einops.rearrange(img, '... c h w -> ... h w c')
    out = tf.gather_nd(img, indices, batch_dims=batch_dims)
    if data_format == 'channels_first':
        out = einops.rearrange(out, '... h w c -> ... c h w')

    #print(x.shape) # 1,256,512
    #print(y.shape) # 1,256,512
    #print(indices.shape) # 1,256,512,2
    #print(img.shape) #1,3,256,512
    #out = tf.gather_nd(img, indices, batch_dims=batch_dims)
    return out
    #shape = tf.shape(x)
    #batch_size = shape[0]
    #height = shape[1]
    #width = shape[2]

    # batch_idx = tf.range(0, batch_size)[:, None, None, None]  # B111
    # if axis == 1:
    #    b = tf.tile(batch_idx, (1, 1, height, width))  # B1HW
    # else:
    #    b = tf.tile(batch_idx, (1, height, width, 1))  # BHW1

    #indices = tf.stack([b, ALL, y, x], axis)
    # return tf.gather_nd(img, indices)

def tf_warp(img, flow, data_format=None):
    if data_format is None:
        data_format = tf.keras.backend.image_data_format()
    # 3D pattern
    if data_format == 'channels_first':
        pattern = '_ h w'
        axis = -3
    else:
        pattern = 'h w _'
        axis = -1

    # Check if batched ...
    if tf.rank(flow) >= 4:
        print('is_batch')
        is_batch = True

    if is_batch:
        pattern = '_ ' + pattern

    shape = einops.parse_shape(img, pattern)
    W, H = shape['w'], shape['h']
    print('w={}, h={}'.format(W, H))

    # Compute grid coordinates.
    x, y = tf.meshgrid(tf.range(W), tf.range(H))

    # Add channel dims
    x = tf.expand_dims(x, axis=axis)
    y = tf.expand_dims(y, axis=axis)

    # Add batch dims
    if is_batch:
        x = tf.expand_dims(x, axis=0)
        y = tf.expand_dims(y, axis=0)

    x = tf.cast(x, tf.float32)
    y = tf.cast(y, tf.float32)
    grid = tf.concat([x, y], axis=axis)

    flows = grid + flow
    max_y = tf.cast(H - 1, tf.int32)
    max_x = tf.cast(W - 1, tf.int32)
    zero = tf.constant(0, dtype=tf.int32)

    # Deal with individual components
    if data_format == 'channels_first':
        x, y = einops.rearrange(flows, 'n c h w -> c n h w', c=2)
    else:
        x, y = einops.rearrange(flows, 'n h w c -> c n h w', c=2)

    x0 = x
    y0 = y
    x0 = tf.cast(x0, tf.int32)
    x1 = x0 + 1
    y0 = tf.cast(y0, tf.int32)
    y1 = y0 + 1

    # clip to range [0, H/W] to not violate img boundaries
    x0 = tf.clip_by_value(x0, zero, max_x)
    x1 = tf.clip_by_value(x1, zero, max_x)
    y0 = tf.clip_by_value(y0, zero, max_y)
    y1 = tf.clip_by_value(y1, zero, max_y)

    # get pixel value at corner coords
    Ia = get_pixel_value(img, x0, y0, data_format)
    Ib = get_pixel_value(img, x0, y1, data_format)
    Ic = get_pixel_value(img, x1, y0, data_format)
    Id = get_pixel_value(img, x1, y1, data_format)

    # recast as float for delta calculation
    x0 = tf.cast(x0, tf.float32)
    x1 = tf.cast(x1, tf.float32)
    y0 = tf.cast(y0, tf.float32)
    y1 = tf.cast(y1, tf.float32)

    # calculate deltas
    wa = (x1 - x) * (y1 - y)
    wb = (x1 - x) * (y - y0)
    wc = (x - x0) * (y1 - y)
    wd = (x - x0) * (y - y0)

    # add dimension for addition
    wa = tf.expand_dims(wa, axis=axis)
    wb = tf.expand_dims(wb, axis=axis)
    wc = tf.expand_dims(wc, axis=axis)
    wd = tf.expand_dims(wd, axis=axis)

    # compute output
    out = tf.add_n([wa * Ia, wb * Ib, wc * Ic, wd * Id])

    return out

def dense_image_warp(image, flow, name=None) -> tf.Tensor:
    """Image warping using per-pixel flow vectors.
    Apply a non-linear warp to the image, where the warp is specified by a
    dense flow field of offset vectors that define the correspondences of
    pixel values in the output image back to locations in the source image.
    Specifically, the pixel value at output[b, j, i, c] is
    images[b, j - flow[b, j, i, 0], i - flow[b, j, i, 1], c].
    The locations specified by this formula do not necessarily map to an int
    index. Therefore, the pixel value is obtained by bilinear
    interpolation of the 4 nearest pixels around
    (b, j - flow[b, j, i, 0], i - flow[b, j, i, 1]). For locations outside
    of the image, we use the nearest pixel values at the image boundary.
    PLEASE NOTE: The definition of the flow field above is different from that
    of optical flow. This function expects the negative forward flow from
    output image to source image. Given two images `I_1` and `I_2` and the
    optical flow `F_12` from `I_1` to `I_2`, the image `I_1` can be
    reconstructed by `I_1_rec = dense_image_warp(I_2, -F_12)`.
    Args:
      image: 4-D float `Tensor` with shape `[batch, height, width, channels]`.
      flow: A 4-D float `Tensor` with shape `[batch, height, width, 2]`.
      name: A name for the operation (optional).
      Note that image and flow can be of type tf.half, tf.float32, or
      tf.float64, and do not necessarily have to be the same type.
    Returns:
      A 4-D float `Tensor` with shape`[batch, height, width, channels]`
        and same type as input image.
    Raises:
      ValueError: if height < 2 or width < 2 or the inputs have the wrong
        number of dimensions.
    """
    with tf.name_scope(name or "dense_image_warp"):
        image = tf.convert_to_tensor(image)
        flow = tf.convert_to_tensor(flow)
        batch_size, height, width, channels = (
            tf.shape(image)[0],
            tf.shape(image)[1],
            tf.shape(image)[2],
            tf.shape(image)[3],
        )

        # The flow is defined on the image grid. Turn the flow into a list of query
        # points in the grid space.
        grid_x, grid_y = tf.meshgrid(tf.range(width), tf.range(height))
        stacked_grid = tf.cast(tf.stack([grid_y, grid_x], axis=2), flow.dtype)
        batched_grid = tf.expand_dims(stacked_grid, axis=0)
        query_points_on_grid = batched_grid + flow
        query_points_flattened = tf.reshape(
            query_points_on_grid, [batch_size, height * width, 2]
        )
        # Compute values at the query points, then reshape the result back to the
        # image grid.
        interpolated = tfa.image.interpolate_bilinear(
            image, query_points_flattened)
        interpolated = tf.reshape(
            interpolated, [batch_size, height, width, channels])
        return interpolated


import setuptools

with open("README.md", "r") as f:
	readme_description = f.read()

setuptools.setup(
	name="pytextdist",
	version="0.1.6",
	author="Yifan Wu",
	author_email="yw693@cornell.edu",
	description="A python implementation of a variety of text distance and similarity metrics.",
	long_description=readme_description,
    long_description_content_type="text/markdown",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    python_requires=">=3.3"
)


from pathlib import Path
import numpy as np

from type_def import Converter, MultiConverter, Storage, TechnologyType, CodeGenerator, Code, InputEnergy, OutputEnergy
from misc import CodeBook, seperator_to_csv, ConverterStorageCodeBook, StorageCodeBook
from build_in_functions import iterate_mapping
from load_data import dump_transmission_db, load_transmission_db

def converter_detail_block(code, input_energy, out_energy, is_bidirectional, year, efficiency, total_cost, lifetime, OaM_rate, converter_list):
    name = code
    comment = "this is a comment"
    if input_energy != InputEnergy.ELECTRIC_ENERGY:
        input_energy = input_energy.upper()
    converter_list.append(["#code",code,"#name",name,"#input",input_energy,"#output",*(i for i in out_energy),"#bidirectional",is_bidirectional,"#comment",comment])
    #efficiency row
    type_ = "DVP_linear"

    start_date = str(year) + "-01-01_00:00"
    converter_list.append(["efficiency_new","#type",type_,"#data",start_date,efficiency])

    converter_list.append(["cost","#type",type_,"#data",start_date,total_cost])

    converter_list.append(["lifetime","#type",type_,"#data",start_date,lifetime])

    converter_list.append(["OaM_rate","#type",type_,"#data",start_date,OaM_rate])
    #last_row
    converter_list.append(["#endblock"])

def converter_block(technology, technology_type, input_energy, out_energy, year, efficiency, lifetime, total_cost, OaM_rate, e2p_ratio, converter_list):
    if technology_type in (TechnologyType.BATTERY, TechnologyType.PUMPED):
        is_bidirectional = str(True).lower()
    else:
        is_bidirectional = str(False).lower()

    # if technology_type == TechnologyType.HYDROGEN_GAS:
    #     code = Code.H2_ELECTROLYSER
    #     inp_energy = InputEnergy.ELECTRIC_ENERGY
    #     out_energy = [OutputEnergy.H2]
    #     efficiency = 1
    #     total_cost = total_cost*(e2p_ratio[0]/(e2p_ratio[0]+1))/2
    #     converter_detail_block(code, inp_energy, out_energy, is_bidirectional, year, efficiency, total_cost, lifetime, OaM_rate, converter_list)

    # if technology_type == TechnologyType.HYDROGEN_FUELCELL:
    #     code = Code.H2_ELECTROLYSER_FC
    #     inp_energy = InputEnergy.ELECTRIC_ENERGY
    #     out_energy = [OutputEnergy.H2_FC]
    #     efficiency = 1
    #     total_cost = total_cost*(e2p_ratio[0]/(e2p_ratio[0]+1))/2
    #     converter_detail_block(code, inp_energy, out_energy, is_bidirectional, year, efficiency, total_cost, lifetime, OaM_rate, converter_list)

    code = CodeBook[CodeGenerator(technology, technology_type, input_energy).to_str()]
    if technology_type in ConverterStorageCodeBook.keys():
        code = ConverterStorageCodeBook[technology_type].code
        input_energy = ConverterStorageCodeBook[technology_type].input_energy
        out_energy = [ConverterStorageCodeBook[technology_type].output_energy]
        efficiency = 1

    if technology_type == TechnologyType.BATTERY:
        total_cost = total_cost*(e2p_ratio[0]/(e2p_ratio[0]+1))
    elif technology_type == TechnologyType.PUMPED:
        total_cost = total_cost*(e2p_ratio[0]/(e2p_ratio[0]+1))

    if code == Code.WIND_OFF:
        input_energy = InputEnergy.WIND_OFF
    elif code == Code.WIND_ONS:
        input_energy = InputEnergy.WIND_ONS
    elif code == Code.TRANSMISSION_IMPORT:
        input_energy = InputEnergy.TRADE_IMPORT

    input_energy = input_energy.replace(" ","_")
    input_energy = InputEnergy.ELECTRIC_ENERGY if input_energy == InputEnergy.ELECTRICITY else input_energy

    converter_detail_block(code, input_energy, out_energy, is_bidirectional, year, efficiency, total_cost, lifetime, OaM_rate, converter_list)

def storage_detail_block(technology_type, year, efficiency, lifetime, total_cost, OaM_rate, e2p_ratio, storage_list):
    code = StorageCodeBook[technology_type].code
    input_energy = StorageCodeBook[technology_type].input_energy
    out_energy = StorageCodeBook[technology_type].output_energy
    name = code
    storage_list.append(["#code",code,"#name",name,"#input",input_energy,"#output", out_energy])
    #efficiency row
    type_ = "DVP_linear"
    start_date = str(year) + "-01-01_00:00"
    storage_list.append(["efficiency_new","#type",type_,"#data",start_date,efficiency])

    if technology_type == TechnologyType.BATTERY:
        total_cost = total_cost/(e2p_ratio+1)
    elif technology_type == TechnologyType.HYDROGEN_FUELCELL:
        total_cost = total_cost/(e2p_ratio+1)
    elif technology_type == TechnologyType.HYDROGEN_GAS:
        total_cost = total_cost/(e2p_ratio+1)
    elif technology_type == TechnologyType.PUMPED:
        total_cost = total_cost/(e2p_ratio+1)

    storage_list.append(["cost","#type",type_,"#data",start_date,total_cost])

    storage_list.append(["lifetime","#type",type_,"#data",start_date,lifetime])

    storage_list.append(["OaM_rate","#type",type_,"#data",start_date,OaM_rate])
    #last_row
    storage_list.append(["#endblock"])

def multiconverter_detail_block(technology, technology_type, input_energy, out_energy, year, emission_factor, efficiency, lifetime, total_cost, OaM_rate, multiconverter_list):
    code = CodeBook[CodeGenerator(technology, technology_type, input_energy).to_str()]
    name = code
    input_energy = input_energy.replace(" ","_")
    input_energy = InputEnergy.ELECTRIC_ENERGY if input_energy == InputEnergy.ELECTRICITY else input_energy.upper()
    multiconverter_list.append(["#code",code,"#name",name,"#input",input_energy])
    #output_energy row
    if ('co2' or 'CO2') not in out_energy:
        out_energy.append('CO2')

    multiconverter_list.append(["#output",*(i for i in out_energy)])
    #conversion row
    if emission_factor == 0:
        emission_factor = 1e-9
    else:
        emission_factor = 1000*emission_factor

    multiconverter_list.append(["#conversion",str(-1),emission_factor])
    #efficiency row
    type_ = "DVP_linear"

    start_date = str(year) + "-01-01_00:00"
    multiconverter_list.append(["efficiency_new","#type",type_,"#data",start_date,efficiency])

    multiconverter_list.append(["cost","#type",type_,"#data",start_date,total_cost])

    multiconverter_list.append(["lifetime","#type",type_,"#data",start_date,lifetime])

    multiconverter_list.append(["OaM_rate","#type",type_,"#data",start_date,OaM_rate])
    #last_row
    multiconverter_list.append(["#endblock"])

def transmission_detail_block(region_A, region_B, technology, technology_type, input_energy, out_energy, year, efficiency, lifetime, total_cost, OaM_rate, transmission_list):
    code  = 'hvac' + '_' + region_A + '_' + region_B
    name = str(technology_type) + '_' + 'Elec'
    is_bidirectional = str(True).lower()
    input_energy = InputEnergy.ELECTRIC_ENERGY if input_energy == InputEnergy.ELECTRICITY else input_energy.upper()
    transmission_list.append(["#code",code,"#name",name,"#input",input_energy,"#output",*(i for i in out_energy),"#bidirectional",is_bidirectional])
    #efficiency row
    type_ = "DVP_linear"

    start_date = str(year) + "-01-01_00:00"
    transmission_list.append(["efficiency_new","#type",type_,"#data",start_date,efficiency])

    transmission_list.append(["cost","#type",type_,"#data",start_date,total_cost])

    transmission_list.append(["lifetime","#type",type_,"#data",start_date,lifetime])

    transmission_list.append(["OaM_rate","#type",type_,"#data",start_date,OaM_rate])

    transmission_list.append(["length_dep_loss","#type",type_,"#data",start_date,str(0)])
    transmission_list.append(["length_dep_cost","#type",type_,"#data",start_date,str(0)])
    #last_row
    transmission_list.append(["#endblock"])

def transmission_detail(technology, technology_type, inp_energy, out_energy, year, efficiency, lifetime, cost_per_len, OaM_rate, transmission_list, SCENARIO_ID):
    dump_transmission_db(SCENARIO_ID)
    data = load_transmission_db(SCENARIO_ID)
    links = iterate_mapping(data,"scalars_transmission[? year == `{}` && parameter_name == 'installed capacity' && technology_type=='{}'].region".format(year, technology_type))
    for link in links:
        if len(link) == 2:
            try:
                length = iterate_mapping(data,"scalars_transmission[? year == `{}` && parameter_name == 'distance' && technology_type=='{}' && region==['{}','{}']].value".format(year, technology_type, link[0], link[1]))[0]
            except:
                length = 300
            total_cost = length*1000 * cost_per_len
            transmission_detail_block(link[0], link[1], technology, technology_type, inp_energy, out_energy, year, efficiency, lifetime, total_cost, OaM_rate, transmission_list)

def primary_energy_block(energy, year, base, value, energy_list):
    if energy != InputEnergy.ELECTRIC_ENERGY:
        energy = energy.upper()
    energy_list.append(['#code', energy, '#name', energy])
    table = 'TBD_lookupTable'
    energy_list.append(['cost_table', '#type', table])
    type_ = 'DVP_const'
    start_date = str(year) + "-01-01_00:00"
    energy_list.append(['base', '#type', type_,'#data', start_date, base])
    energy_list.append(['value', '#type', type_,'#data', start_date, value])
    energy_list.append(['#endtable'])
    energy_list.append(['#endblock'])

def link_detail_block(link, year, length, installation, link_list):
    region_A = link[0]
    region_B = link[1]
    code = ("_").join([region_A, region_B])
    link_list.append(["#code",code,"#region_A",region_A,"#region_B",region_B])
    #length row
    type_ = "DVP_const"
    start_date = str(year) + "-01-01_00:00"
    link_list.append(["length","#type",type_,"#data",start_date,length])
    # converter_code row
    converter_code = 'hvac_' + code
    link_list.append(["#converter","#code",converter_code])
    #installation row
    link_list.append(["installation","#type",type_,"#data",start_date,installation])

    link_list.append(["#endblock"])

def timeseries_detail_block(year, region, input_energy, timeseries, cwd):
    csv_list = []
    csv_list.append(["#comment","===============generation time series============================================"])
    base_type = "DVP_const"
    base = 1000000
    year = year.replace('T','_')[:-3]
    csv_list.append(["base", "#type", base_type, "#data", year, base])
    value_type = "TS_repeat_const"
    csv_list.append(["value", "#type", value_type, "#interval", "1h", "#start", year, "#data", *(t for t in timeseries)])
    csv_list.append(["#endtable"])

    filename = year.split("-")[0] + '/TimeSeries/' + region + '/' + region + '_' + input_energy.replace(" ","_").upper() + '.csv'
    seperator_to_csv(csv_list, filename, cwd)

def primary_energy_minus_one_detail_block(year, cwd):
    csv_list = []
    csv_list.append(["#comment","unlimited -1 primary ressource"])
    base_type = "DVP_const"
    base = 1E15
    date = str(year) + "-01-01_00:00"
    csv_list.append(["base", "#type", base_type, "#data", date, base])
    value_type = "DVP_linear"
    value = -1
    csv_list.append(["value", "#type", value_type, "#data", date, value])
    csv_list.append(["#endtable"])

    filename = str(year) + '/TimeSeries/PrimaryEnergyUnlimited_minusOne.csv'
    seperator_to_csv(csv_list, filename, cwd)

def installation_list_result(year, cwd):
    csv_list = []
    csv_list.append(["#comment","MOUNTING-CODE.TECH-CODE;DATA-TYPE;DATA(may contain placeholders varxy);(if applicable) next lines:;#varxy;INIT-POINT;lBOUND;uBOUND;"])
    csv_list.append(["#empty"])
    filename = str(year) + '/InstallationListResult.csv'
    seperator_to_csv(csv_list, filename, cwd)

def region_detail_block(region, year, demand_per_a, region_csv):
    region_csv.append(["#code", region, "#name", region])
    type_dyn = "TS_repeat_const"
    start_date = year.replace('T','_')[:-3]

    source_path = "./TimeSeries/" + region + "/demand_elec.csv"
    region_csv.append(["demand_electric_dyn", "#type", type_dyn, "#interval", "1h", "#start", start_date, "#data_source_path", source_path])
    type_a = "DVP_linear"
    region_csv.append(["demand_electric_per_a", "#type", type_a, "#data", start_date, demand_per_a])

def region_primary_energy_block(region, input_energy, region_csv):
    region_csv.append(["#primary_energy", "#code", input_energy.replace(' ','_').upper()])
    lookUpTable = "TBD_lookupTable"
    energy = input_energy.replace(" ","_").upper()
    source_path = "./TimeSeries/" + region + "/" + region + "_" + energy + ".csv"
    region_csv.append(["potential", "#type", lookUpTable, "#data_source_path", source_path])

def determine_primary_source_path(year, region, input_energy, cwd):
    year = year.split('-')[0]
    domestic_limit_path = '{}/{}/TimeSeries/PrimaryEnergyLimited_{}_{}.csv'.format(cwd, year, region, input_energy)
    if Path(domestic_limit_path).exists():
        return './TimeSeries/PrimaryEnergyLimited_{}_{}.csv'.format(region, input_energy)
    else:
        return './TimeSeries/PrimaryEnergyUnlimited_minusOne.csv'

def region_primary_energy_block_minusone(year, region, input_energy, region_csv, cwd):
    region_csv.append(["#primary_energy", "#code", input_energy.replace(' ','_').upper()])
    lookUpTable = "TBD_lookupTable"
    source_path = determine_primary_source_path(year, region, input_energy, cwd)
    region_csv.append(["potential", "#type", lookUpTable, "#data_source_path", source_path])

def region_converter_block(region, code, installation, start_date, end_date, region_csv):
    region_csv.append(["#converter", "#code", code])
    converter_type = "DVP_const"
    region_csv.append(["installation", "#type", converter_type, "#data", start_date, installation, end_date, 0])

def region_multiconverter_block(region, code, installation, start_date, end_date, region_csv):
    region_csv.append(["#multi-converter", "#code", code])
    converter_type = "DVP_const"
    region_csv.append(["installation", "#type", converter_type, "#data", start_date, installation, end_date, 0])

def region_storage_block(region, code, installation, start_date, end_date, region_csv):
    region_csv.append(["#storage", "#code", code])
    converter_type = "DVP_const"
    region_csv.append(["installation", "#type", converter_type, "#data", start_date, installation, end_date, 0])

TRADE_DEMAND = {}
TRADE_DEMAND[2016]=[]
TRADE_DEMAND[2030]=[]
TRADE_DEMAND[2050]=[]
TIME_DEMAND={}
TIME_DEMAND[2016]=[]
TIME_DEMAND[2030]=[]
TIME_DEMAND[2050]=[]

def region_dir_block(region, year, timeseries, trade_series, outputs_primary_energy, trade_primary_energy, outputs_converter, e2p_ratio, data, region_csv, cwd):
    dirname = year.split("-")[0]+'/regions/'
    Path(dirname).mkdir(exist_ok=True, parents=True)

    demand_per_a = find_demand(trade_series, timeseries, year)

    region_detail_block(region, year, demand_per_a, region_csv)

    input_energies = set([output['energy'] for output in outputs_primary_energy if output['energy']])
    for input_energy in input_energies:
        if input_energy != InputEnergy.AIR:
            region_primary_energy_block(region, input_energy, region_csv)

    for output in outputs_primary_energy:
        input_energy = output['energy']
        if input_energy == InputEnergy.AIR:
            tech_type = output['tech_type']
            if tech_type == TechnologyType.ONSHORE:
                input_energy = InputEnergy.WIND_ONS
            elif tech_type == TechnologyType.OFFSHORE:
                input_energy = InputEnergy.WIND_OFF

            region_primary_energy_block(region, input_energy, region_csv)

    if len(trade_primary_energy):
        region_primary_energy_block(region, 'trade import', region_csv)

    outputs_converter_set = set([output['energy'] for output in outputs_converter])
    for input_energy in outputs_converter_set:
        if input_energy not in (output['energy'] for output in outputs_primary_energy) and input_energy not in ('unknown', 'electricity'):
            region_primary_energy_block_minusone(year, region, input_energy, region_csv, cwd)

    for output in outputs_converter:
        input_energy = output['energy']
        tech = output['tech']
        if tech in [mconverter.value for mconverter in MultiConverter]:
            region_primary_energy_block_minusone(year, region, "CO2", region_csv, cwd)
            break

    for output in outputs_converter:
        input_energy = output['energy']
        tech = output['tech']
        tech_type = output['tech_type']
        installation = output['installation']/1000.0
        year = year.split("-")[0]
        start_date = str(year) + "-01-01_00:00"
        end_date = str(int(year)+1) + "-01-01 00:00:00"
        if CodeGenerator(tech, tech_type, input_energy).to_str() in CodeBook:
            code = CodeBook[CodeGenerator(tech, tech_type, input_energy).to_str()]
        else:
            continue

        if (tech in [converter.value for converter in Converter] or tech_type=='trade import' or\
            (tech=='generator' and tech_type==TechnologyType.GAS and input_energy==InputEnergy.HYDROGEN)):
            region_converter_block(region, code, installation, start_date, end_date, region_csv)

        # if tech_type == TechnologyType.HYDROGEN_GAS:
            # code = Code.H2_ELECTROLYSER
            # region_converter_block(region, code, installation, start_date, end_date, region_csv)

        # if tech_type == TechnologyType.HYDROGEN_FUELCELL:
            # code = Code.H2_ELECTROLYSER_FC
            # region_converter_block(region, code, installation, start_date, end_date, region_csv)

        if tech_type in ConverterStorageCodeBook.keys():
            code = ConverterStorageCodeBook[tech_type].code
            region_converter_block(region, code, installation, start_date, end_date, region_csv)

    for output in outputs_converter:
        input_energy = output['energy']
        tech = output['tech']
        tech_type = output['tech_type']
        installation = output['installation']/1000.0
        year = year.split("-")[0]
        start_date = str(year) + "-01-01_00:00"
        end_date = str(int(year)+1) + "-01-01_00:00"
        if CodeGenerator(tech, tech_type, input_energy).to_str() in CodeBook:
            code = CodeBook[CodeGenerator(tech, tech_type, input_energy).to_str()]
        else:
            continue

        code = CodeBook[CodeGenerator(tech, tech_type, input_energy).to_str()]

        if tech in [mconverter.value for mconverter in MultiConverter]:
            region_multiconverter_block(region, code, installation, start_date, end_date, region_csv)

    for output in outputs_converter:
        input_energy = output['energy']
        tech = output['tech']
        tech_type = output['tech_type']
        installation = output['installation']
        year = year.split("-")[0]
        start_date = str(year) + "-01-01_00:00"
        end_date = str(int(year)+1) + "-01-01_00:00"
        if CodeGenerator(tech, tech_type, input_energy).to_str() in CodeBook:
            code = CodeBook[CodeGenerator(tech, tech_type, input_energy).to_str()]
        else:
            continue
        code = CodeBook[CodeGenerator(tech, tech_type, input_energy).to_str()]
        if tech in [storage.value for storage in Storage]:
            try:
                ratio = [e2p['E2P'] for e2p in e2p_ratio if e2p['tech_type'] == tech_type][0]
            except:
                ratio = 1
            storage_installation = installation * ratio
            region_storage_block(region, code, storage_installation, start_date, end_date, region_csv)

    region_csv.append(["#endblock"])

def find_demand(trade_series, timeseries, year):
    try:
        demand_per_a_trade = sum(trade_series[0])/1000.0
    except:
        demand_per_a_trade = 0
    try:
        demand_per_a_time = sum(timeseries[0])/1000.0
    except:
        demand_per_a_time = 0

    try:
        year = int(year.split("-")[0])
    except:
        year = int(year)

    TRADE_DEMAND[year].append(demand_per_a_trade)
    TIME_DEMAND[year].append(demand_per_a_time)
    demand_per_a = demand_per_a_time + demand_per_a_trade
    return demand_per_a

def installation_list_block(name, installed_capacity, region_code_installation_value, installation_csv, year):
    start_date = "{}-01-01_00:00".format(year)
    end_date = "{}-01-01_00:00".format(year+1)
    installation_csv.append([name, "#type", "DVP_linear", "#data", start_date, "var0", end_date, 0,''])
    # installation_csv.append(["#var0", installed_capacity, installed_capacity, region_code_installation_value,''])
    installation_csv.append(["#var0", 0, 0, region_code_installation_value,''])


# -*- coding: utf-8 -*-
# Time : 2019/12/30 0030  17:21
# Author : dengfan
import shutil, os

xml_path = r'E:\study_code\TC_CQ\data\train\xml_new'

train_files = r'train_big.txt'
valid_files = r'valid_big.txt'

train_save = r'./big_train_xml'
valid_save = r'./big_valid_xml'

def get_name(name):
    names = []
    with open(name, 'r') as r:
        lines = r.readlines()
        for line in lines:
            names.append(line.strip()+'.xml')
    return names

train_xml = get_name(train_files)
valid_xml = get_name(valid_files)

for i in train_xml:
    shutil.copyfile(os.path.join(xml_path, i), os.path.join(train_save, i))

for i in valid_xml:
    shutil.copyfile(os.path.join(xml_path, i), os.path.join(valid_save, i))


def cellCompete(states, days):
    # WRITE YOUR CODE HERE
    results = [0]*len(states)

    for i in range(days):
        for j in range(len(states)):
            status = getStatus(states, j)
            results[j] = status

        states = results[:]
    return results

def getStatus(state, i):
    left = state[i - 1] if i > 0 else 0
    right = state[i + 1] if i + 1 < len(state) else 0

    if left == right:
        return 0
    else:
        return 1

assert(cellCompete([1,1,1,0,1,1,1,1], 2) == [0, 0, 0, 0, 0, 1, 1, 0])
assert(cellCompete([1,0,1,0,1,0,0,1], 4) == [0,0,1,1,1,1,1,0])


# 65. 有效数字
# 有效数字（按顺序）可以分成以下几个部分：
# 一个 小数 或者 整数
# （可选）一个 'e' 或 'E' ，后面跟着一个 整数
# 小数（按顺序）可以分成以下几个部分：
# （可选）一个符号字符（'+' 或 '-'）
# 下述格式之一：
# 至少一位数字，后面跟着一个点 '.'
# 至少一位数字，后面跟着一个点 '.' ，后面再跟着至少一位数字
# 一个点 '.' ，后面跟着至少一位数字
# 整数（按顺序）可以分成以下几个部分：
# （可选）一个符号字符（'+' 或 '-'）
# 至少一位数字
# 部分有效数字列举如下：
# ["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]
# 部分无效数字列举如下：
# ["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]
# 给你一个字符串 s ，如果 s 是一个 有效数字 ，请返回 true 。
def isNumber(s: str) -> bool:
    posNegSign, decimalSign, eSign, digitSign, length = False, False, False, False, len(s)
    posNeg, decimalPoint, e = ['+', '-'], ['.'], ['e', 'E']
    for i in range(len(s)):
        if s[i] in posNeg:
            if posNegSign:
                return False
            posNegSign = True
        elif s[i] in decimalPoint:
            if decimalSign and i == len(s) - 1 or not s[i + 1].isdigit():
                return False
            decimalSign = True
        elif s[i].isalpha():
            if s[i] in e:
                if eSign or not digitSign:
                    return False
                eSign = True
                posNegSign = False
                decimalSign = False
                digitSign = False
            else:
                return False
        elif s[i].isdigit():
            digitSign = True
    return True

isNumber('e')

65. 有效数字（需要学习）.py