'''
You can modify the parameters, return values and data structures used in every function if it conflicts with your
coding style or you want to accelerate your code.

You can also import packages you want.

But please do not change the basic structure of this file including the function names. It is not recommended to merge
functions, otherwise it will be hard for TAs to grade your code. However, you can add helper function if necessary.
'''

from flask import Flask, request
from flask import render_template
import time
import json
from scipy.interpolate import interp1d
import numpy as np
import math
from sklearn.metrics.pairwise import euclidean_distances
import sys

app = Flask(__name__)

centroids_X = [50, 205, 135, 120, 100, 155, 190, 225, 275, 260, 295, 330, 275, 240, 310, 345, 30, 135, 85, 170, 240, 170, 65, 100, 205, 65]
centroids_Y = [85, 120, 120, 85, 50, 85, 85, 85, 50, 85, 85, 85, 120, 120, 50, 50, 50, 50, 85, 50, 50, 120, 50, 120, 50, 120]

words, probabilities = [], {}
template_points_X, template_points_Y = [], []
file = open('words_10000.txt')
content = file.read()
file.close()
content = content.split('\n')
for line in content:
    line = line.split('\t')
    words.append(line[0])
    probabilities[line[0]] = float(line[2])
    template_points_X.append([])
    template_points_Y.append([])
    for c in line[0]:
        template_points_X[-1].append(centroids_X[ord(c) - 97])
        template_points_Y[-1].append(centroids_Y[ord(c) - 97])

alphaList = np.zeros((100))

template_sample_points_X = []
template_sample_points_Y = []

def generate_sample_points(pointsX, pointsY):
    '''Generate 100 sampled points for a gesture.

    In this function, we should convert every gesture or template to a set of 100 points, such that we can compare
    the input gesture and a template.

    :param points_X: A list of X-axis values of a gesture.
    :param points_Y: A list of Y-axis values of a gesture.

    :return:
        sample_points_X: A list of X-axis values of a gesture after sampling, containing 100 elements.
        sample_points_Y: A list of Y-axis values of a gesture after sampling, containing 100 elements.
    '''

    sample_points_X, sample_points_Y = [], []
    euclideanDistances = np.sqrt(np.ediff1d(pointsX, to_begin= 0)**2 + np.ediff1d(pointsY, to_begin= 0)**2)
    prefixSums  = np.cumsum(euclideanDistances)

    prefixSums = prefixSums / prefixSums[-1]

    transFactorX = interp1d(prefixSums, pointsX)
    transFactorY = interp1d(prefixSums, pointsY)

    alphaSpace = np.linspace(0, 1, 100)

    sampleX = transFactorX(alphaSpace).tolist()
    sampleY = transFactorY(alphaSpace).tolist()

    return sampleX, sampleY

def normalizePoints(x, y):
    scaledCentroidX = np.mean(x, axis=1)
    scaledCentroidY = np.mean(y, axis=1)

    xTrans = -scaledCentroidX
    yTrans = -scaledCentroidY

    translation_matrix_X = np.reshape(xTrans, (-1, 1))
    translation_matrix_Y = np.reshape(yTrans, (-1, 1))

    return translation_matrix_X + x, translation_matrix_Y + y

def sampleTemplates(templatePointsX, templatePointsY):
    global template_sample_points_X
    global template_sample_points_Y
    for i in range(10000):
        sampleX, sampleY = generate_sample_points(templatePointsX[i], templatePointsY[i])
        template_sample_points_X.append(sampleX)
        template_sample_points_Y.append(sampleY)

normalized_template_sample_points_X  = []
normalized_template_sample_points_Y = []
def getDifference(li):
    max = np.max(li, axis = 1)
    min = np.min(li, axis = 1)
    return max - min

def preProcess(template_sample_points_X, template_sample_points_Y):
    global normalized_template_sample_points_X
    global normalized_template_sample_points_Y
    L = 250
    W = getDifference(template_sample_points_X)
    H = getDifference(template_sample_points_Y)

    # S = L / Max(W, H)
    s = L / np.max(np.array([W, H]), axis=0)

    scale = np.diag(s)
    scaled_template_points_X = np.matmul(scale, template_sample_points_X)
    scaled_template_points_Y = np.matmul(scale, template_sample_points_Y)

    normalized_template_sample_points_X, normalized_template_sample_points_Y = normalizePoints(scaled_template_points_X, scaled_template_points_Y)

def do_pruning(gesture_points_X, gesture_points_Y, template_sample_points_X, template_sample_points_Y):
    '''Do pruning on the dictionary of 10000 words.

    In this function, we use the pruning method described in the paper (or any other method you consider reasonable)
    to narrow down the number of valid words so that ambiguity can be avoided.

    :param gesture_points_X: A list of X-axis values of input gesture points, which has 100 values since we have
        sampled 100 points.
    :param gesture_points_Y: A list of Y-axis values of input gesture points, which has 100 values since we have
        sampled 100 points.
    :param template_sample_points_X: 2D list, containing X-axis values of every template (10000 templates in total).
        Each of the elements is a 1D list and has the length of 100.
    :param template_sample_points_Y: 2D list, containing Y-axis values of every template (10000 templates in total).
        Each of the elements is a 1D list and has the length of 100.

    :return:
        valid_words: A list of valid words after pruning.
        valid_probabilities: The corresponding probabilities of valid_words.
        valid_template_sample_points_X: 2D list, the corresponding X-axis values of valid_words. Each of the elements
            is a 1D list and has the length of 100.
        valid_template_sample_points_Y: 2D list, the corresponding Y-axis values of valid_words. Each of the elements
            is a 1D list and has the length of 100.
    '''
    valid_words, valid_template_sample_points_X, valid_template_sample_points_Y = [], [], []

    threshold = 20

    startIdx = gesture_points_X[0]
    startJdx = gesture_points_Y[0]

    endIdx = gesture_points_X[len(gesture_points_X) - 1]
    endJdx = gesture_points_Y[len(gesture_points_Y) - 1]

    start = np.array([startIdx, startJdx])
    end = np.array([endIdx, endJdx])

    startPoints = []
    endPoints = []

    for idx in range(len(template_sample_points_X)):
        startPoints.append([template_sample_points_X[idx][0], template_sample_points_Y[idx][0]])
    startPoints = np.array(startPoints)

    for idx in range(len(template_sample_points_X)):
        endPoints.append([template_sample_points_X[idx][-1], template_sample_points_Y[idx][-1]])
    endPoints = np.array(endPoints)

    start = np.reshape(start, (1, -1))
    end = np.reshape(end, (1, -1))
    startDiff = euclidean_distances(start, startPoints)[0]
    endDiff = euclidean_distances(end, endPoints)[0]

    refinedIdxes = []

    for idx in range(len(startDiff)):
        if startDiff[idx] + endDiff[idx] < threshold:
            refinedIdxes.append(idx)

    refinedXes = []
    refinedYes = []
    refinedXes = np.array(template_sample_points_X)[refinedIdxes]
    refinedYes = np.array(template_sample_points_Y)[refinedIdxes]
    refinedWords = [words[idx] for idx in refinedIdxes]

    return refinedIdxes, refinedWords, refinedXes, refinedYes

def get_scaled_points(sample_points_X, sample_points_Y, L):
    x_maximum = max(sample_points_X)
    x_minimum = min(sample_points_X)
    W = x_maximum - x_minimum
    y_maximum = max(sample_points_Y)
    y_minimum = min(sample_points_Y)
    H = y_maximum - y_minimum
    r = L/max(H, W)

    gesture_X, gesture_Y = [], []
    for point_x, point_y in zip(sample_points_X, sample_points_Y):
        gesture_X.append(r * point_x)
        gesture_Y.append(r * point_y)

    centroid_x = (max(gesture_X) - min(gesture_X))/2
    centroid_y = (max(gesture_Y) - min(gesture_Y))/2
    scaled_X, scaled_Y = [], []
    for point_x, point_y in zip(gesture_X, gesture_Y):
        scaled_X.append(point_x - centroid_x)
        scaled_Y.append(point_y - centroid_y)
    return scaled_X, scaled_Y

def getNormalizedPoints(scaledIdxes):
    centroidDashX = np.mean(scaledIdxes[0])
    xDash = 0 - centroidDashX

    centroidDashY = np.mean(scaledIdxes[1])
    yDash = 0 - centroidDashY

    changeFactor = np.array([[xDash],
                                   [yDash]])

    normalizedPoints = changeFactor + scaledIdxes

    return normalizedPoints

def populateAlphas():
    global alphaList

    for num in range(50):

        alphaList[50 - num - 1], alphaList[50 + num] = num/2450, num/2450

def get_shape_scores(refinedIdxes, gesture_sample_points_X, gesture_sample_points_Y, valid_template_sample_points_X, valid_template_sample_points_Y):
    '''Get the shape score for every valid word after pruning.

    In this function, we should compare the sampled input gesture (containing 100 points) with every single valid
    template (containing 100 points) and give each of them a shape score.

    :param gesture_sample_points_X: A list of X-axis values of input gesture points, which has 100 values since we
        have sampled 100 points.
    :param gesture_sample_points_Y: A list of Y-axis values of input gesture points, which has 100 values since we
        have sampled 100 points.
    :param valid_template_sample_points_X: 2D list, containing X-axis values of every valid template. Each of the
        elements is a 1D list and has the length of 100.
    :param valid_template_sample_points_Y: 2D list, containing Y-axis values of every valid template. Each of the
        elements is a 1D list and has the length of 100.

    :return:
        A list of shape scores.
    '''
    # TODO: Set your own L

    # TODO: Calculate shape scores (10 points)
    shape_scores = []
    L = 200

    maxX = np.max(gesture_sample_points_X)
    minX = np.min(gesture_sample_points_X)

    width = maxX - minX

    maxY = np.max(gesture_sample_points_Y)
    minY = np.min(gesture_sample_points_Y)

    height = maxY - minY

    s = L / max(width, height, 1)

    originalIdxes = np.array([gesture_sample_points_X,
                                   gesture_sample_points_Y])

    scale = np.array([[s, 0],[0, s]])

    scaledIdxes = np.matmul(scale, originalIdxes)

    normalizedPoints = getNormalizedPoints(scaledIdxes)

    valid_normalized_template_sample_points_X = normalized_template_sample_points_X[refinedIdxes]
    valid_normalized_template_sample_points_Y = normalized_template_sample_points_Y[refinedIdxes]

    return getScore(normalizedPoints, valid_normalized_template_sample_points_X, valid_normalized_template_sample_points_Y)

def getScore(normalizedPoints, valid_normalized_template_sample_points_X, valid_normalized_template_sample_points_Y):
    xi = valid_normalized_template_sample_points_X
    xj = np.reshape(normalizedPoints[0], (1, -1))
    xi_j = (xi - xj) ** 2

    yi = valid_normalized_template_sample_points_Y
    yj = np.reshape(normalizedPoints[1], (1, -1))
    yi_j = (yi - yj) ** 2

    score = np.sum((xi_j + yi_j) ** 0.5, axis=1) / 100

    return score

def get_small_d(p_X, p_Y, q_X, q_Y):
    min_distance = []
    for n in range(0, 100):
        distance = math.sqrt((p_X - q_X[n])**2 + (p_Y - q_Y[n])**2)
        min_distance.append(distance)
    return (sorted(min_distance)[0])

def get_big_d(p_X, p_Y, q_X, q_Y, r):
    final_max = 0
    for n in range(0, 100):
        local_max = 0
        distance = get_small_d(p_X[n], p_Y[n], q_X, q_Y)
        local_max = max(distance-r , 0)
        final_max += local_max
    return final_max

def get_delta(u_X, u_Y, t_X, t_Y, r, i):
    D1 = get_big_d(u_X, u_Y, t_X, t_Y, r)
    D2 = get_big_d(t_X, t_Y, u_X, u_Y, r)
    if D1 == 0 and D2 == 0:
        return 0
    else:
        return math.sqrt((u_X[i] - t_X[i])**2 + (u_Y[i] - t_Y[i])**2)

def get_location_scores(gesture_sample_points_X, gesture_sample_points_Y, valid_template_sample_points_X, valid_template_sample_points_Y):
    '''Get the location score for every valid word after pruning.

    In this function, we should compare the sampled user gesture (containing 100 points) with every single valid
    template (containing 100 points) and give each of them a location score.

    :param gesture_sample_points_X: A list of X-axis values of input gesture points, which has 100 values since we
        have sampled 100 points.
    :param gesture_sample_points_Y: A list of Y-axis values of input gesture points, which has 100 values since we
        have sampled 100 points.
    :param template_sample_points_X: 2D list, containing X-axis values of every valid template. Each of the
        elements is a 1D list and has the length of 100.
    :param template_sample_points_Y: 2D list, containing Y-axis values of every valid template. Each of the
        elements is a 1D list and has the length of 100.

    :return:
        A list of location scores.
    '''

    location_scores = [0 for _ in range(len(valid_template_sample_points_X))]
    location_scores = np.array(location_scores)

    radius = 15
    # TODO: Calculate location scores (10 points)
    gestureIdxes = []
    gestureIdxesX = []
    gestureIdxesY = []
    for idx in range(100):
        gestureIdxesX.append(gesture_sample_points_X[idx])
    for idx in range(100):
        gestureIdxesY.append(gesture_sample_points_Y[idx])
    print(len(gestureIdxesX), len(gestureIdxesY))
    for idx in range(100):
        gestureIdxes.append([gestureIdxesX[idx], gestureIdxesY[idx]])

    for i in range(len(valid_template_sample_points_X)):

        templateIdxes = []
        templateIdxesX = []
        templateIdxesY = []
        # for jdx in range(num_sample_points):
        #     templateIdxesX.append(valid_template_sample_points_X[i][jdx])
        # for jdx in range(num_sample_points):
        #     templateIdxesY.append(valid_template_sample_points_Y[i][jdx])
        # print(len(gestureIdxesX), len(gestureIdxesY))
        # for jdx in range(num_sample_points):
        #     templateIdxes.append([templateIdxesX[jdx], templateIdxesY[jdx]])
        for jdx in range(100):
            xCoord = valid_template_sample_points_X[i][jdx]
            yCoord = valid_template_sample_points_Y[i][jdx]
            templateIdxes.append([xCoord, yCoord])

        currentDistances = euclidean_distances(gestureIdxes, templateIdxes)

        closestGesturePoint = np.min(currentDistances, axis=0)

        closestTemplatePoint = np.min(currentDistances, axis=1)
        flag = True if np.any(closestTemplatePoint > radius) or np.any(closestGesturePoint > radius) else False
        if flag:
            deltaList = np.diagonal(currentDistances)
            location_scores[i] = np.sum(np.multiply(alphaList, deltaList))

    return location_scores

def get_integration_scores(shape_scores, location_scores):
    integration_scores = []

    a = 0.4
    b = 0.6
    for i in range(len(shape_scores)):
        integration_scores.append(a * shape_scores[i] + b * location_scores[i])
    return integration_scores

def get_best_word(valid_words, integration_scores):
    '''Get the best word.

    In this function, you should select top-n words with the highest integration scores and then use their corresponding
    probability (stored in variable "probabilities") as weight. The word with the highest weighted integration score is
    exactly the word we want.

    :param valid_words: A list of valid words.
    :param integration_scores: A list of corresponding integration scores of valid_words.
    :return: The most probable word suggested to the user.
    '''

    n = 3

    if n >= len(integration_scores):
        n = len(integration_scores) - 1
    # Ref: https://stackoverflow.com/questions/34226400/find-the-index-of-the-k-smallest-values-of-a-numpy-array
    nIdxes = np.argpartition(integration_scores, n)

    topWords = [ valid_words[idx] for idx in nIdxes ]

    bestScore = integration_scores[nIdxes[0]] * (1 - probabilities[topWords[0]])
    bestWord = topWords[0]

    for word, idx in zip(topWords[1::], nIdxes[1::]):
        currentScore = integration_scores[idx] * (1 - probabilities[word])
        if currentScore < bestScore:
            bestScore = currentScore
            bestWord = word
        # print(bestScore, bestWord)
    return bestWord

@app.route("/")
def init():
    # sampleTemplates(template_points_X, template_points_Y)
    # preProcess(template_sample_points_X, template_sample_points_Y)
    return render_template('index.html')

@app.route('/shark2', methods=['POST'])
def shark2():
    global template_sample_points_X
    global template_sample_points_Y
    global normalized_template_sample_points_X
    global normalized_template_sample_points_Y
    start_time = time.time()
    data = json.loads(request.get_data())

    gesture_points_X = []
    gesture_points_Y = []
    for i in range(len(data)):
        gesture_points_X.append(data[i]['x'])
        gesture_points_Y.append(data[i]['y'])
    template_sample_points_X = []
    template_sample_points_Y = []
    normalized_template_sample_points_X = []
    normalized_template_sample_points_Y = []

    sampleTemplates(template_points_X, template_points_Y)
    preProcess(template_sample_points_X, template_sample_points_Y)
    gesture_sample_points_X, gesture_sample_points_Y = generate_sample_points(gesture_points_X, gesture_points_Y)

    refinedIndexes, valid_words, valid_template_sample_points_X, valid_template_sample_points_Y = do_pruning(gesture_points_X, gesture_points_Y, template_sample_points_X, template_sample_points_Y)
    if len(valid_words) == 0:
        end_time = time.time()
        return '{"Word not found", "elapsed_time":"' + str(round((end_time - start_time) * 1000, 5)) + 'ms"}'

    best_word = "Word not found"

    shape_scores = get_shape_scores(refinedIndexes, gesture_sample_points_X, gesture_sample_points_Y, valid_template_sample_points_X, valid_template_sample_points_Y)

    location_scores = get_location_scores(gesture_sample_points_X, gesture_sample_points_Y, valid_template_sample_points_X, valid_template_sample_points_Y)

    integration_scores = get_integration_scores(shape_scores, location_scores)

    best_word = get_best_word(valid_words, integration_scores)

    end_time = time.time()

    return '{"best_word":"' + best_word + '", "elapsed_time":"' + str(round((end_time - start_time) * 1000, 5)) + 'ms"}'

if __name__ == "__main__":
    app.run()


"""Collection of methods for type input checking."""
import re
import os
import math

try:
    INFPOS = math.inf
    INFNEG = -1 * math.inf
except AttributeError:
    # python 2
    INFPOS = float('inf')
    INFNEG = float('-inf')

def valid_string(value, input_name=''):
    """Get a valid string for both Radiance and EnergyPlus.

    This is used for honeybee face and honeybee zone names.
    """
    try:
        val = re.sub(r'[^.A-Za-z0-9_-]', '', value)
    except TypeError:
        raise TypeError('Input {} must be a text string. Got {}: {}.'.format(
            input_name, type(value), value))
    assert len(val) > 0, 'Input {} "{}" contains no valid characters.'.format(
        input_name, value)
    assert len(val) <= 100, 'Input {} "{}" must be less than 100 characters.'.format(
        input_name, value)
    return val

def valid_rad_string(value, input_name=''):
    """Get a valid string for Radiance that can be used for rad material names, etc.

    This includes stripping out illegal characters and white spaces.
    """
    try:
        val = re.sub(r'[^.A-Za-z0-9_-]', '', value)
    except TypeError:
        raise TypeError('Input {} must be a text string. Got {}: {}.'.format(
            input_name, type(value), value))
    assert len(val) > 0, 'Input {} "{}" contains no valid characters.'.format(
        input_name, value)
    return val

def valid_ep_string(value, input_name=''):
    """Get valid string for EnergyPlus that can be used for energy material names, etc.

    This includes stripping out all illegal characters, removing trailing white spaces,
    and ensuring the name is not longer than 100 characters.
    """
    try:
        val = ''.join(i for i in value if ord(i) < 128)  # strip out non-ascii
        val = re.sub(r'[,;!\n\t]', '', val)  # strip out E+ special characters
    except TypeError:
        raise TypeError('Input {} must be a text string. Got {}: {}.'.format(
            input_name, type(value), value))
    val = val.strip()
    assert len(val) > 0, 'Input {} "{}" contains no valid characters.'.format(
        input_name, value)
    assert len(val) <= 100, 'Input {} "{}" must be less than 100 characters.'.format(
        input_name, value)
    return val

def float_in_range(value, mi=INFNEG, ma=INFPOS, input_name=''):
    """Check a float value to be between minimum and maximum."""
    try:
        number = float(value)
    except (ValueError, TypeError):
        raise TypeError('Input {} must be a number. Got {}: {}.'.format(
            input_name, type(value), value))
    assert mi <= number <= ma, 'Input number {} must be between {} and {}. ' \
        'Got {}'.format(input_name, mi, ma, value)
    return number

def int_in_range(value, mi=INFNEG, ma=INFPOS, input_name=''):
    """Check an integer value to be between minimum and maximum."""
    try:
        number = int(value)
    except ValueError:
        # try to convert to float and then digit if possible
        try:
            number = int(float(value))
        except (ValueError, TypeError):
            raise TypeError('Input {} must be an integer. Got {}: {}.'.format(
                input_name, type(value), value))
    except (ValueError, TypeError):
        raise TypeError('Input {} must be an integer. Got {}: {}.'.format(
            input_name, type(value), value))
    assert mi <= number <= ma, 'Input integer {} must be between {} and {}. ' \
        'Got {}.'.format(input_name, mi, ma, value)
    return number

def float_positive(value, input_name=''):
    """Check a float value to be positive."""
    return float_in_range(value, 0, INFPOS, input_name)

def int_positive(value, input_name=''):
    """Check if an integer value is positive."""
    return int_in_range(value, 0, INFPOS, input_name)

def tuple_with_length(value, length=3, item_type=float, input_name=''):
    """Try to create a tuple with a certain value."""
    try:
        value = tuple(item_type(v) for v in value)
    except (ValueError, TypeError):
        raise TypeError('Input {} must be a {}.'.format(
            input_name, item_type))
    assert len(value) == length, 'Input {} length must be {} not {}'.format(
        input_name, length, len(value))
    return value

def list_with_length(value, length=3, item_type=float, input_name=''):
    """Try to create a list with a certain value."""
    try:
        value = [item_type(v) for v in value]
    except (ValueError, TypeError):
        raise TypeError('Input {} must be a {}.'.format(
            input_name, item_type))
    assert len(value) == length, 'Input {} length must be {} not {}'.format(
        input_name, length, len(value))
    return value

wrapper = '"' if os.name == 'nt' else '\''
"""String wrapper."""

def normpath(value):
    """Normalize a path by eliminating double slashes, etc and put it in quotes if
    needed. Then, convert all the slashes are forwarded slashes to maintain compatibility
    across platforms"""

    value = os.path.normpath(value)

    # Needed For Windows.
    value = value.replace('\\', '/')
    if ' ' in value:
        value = '{0}{1}{0}'.format(wrapper, value)
    return value

def path_checker(file_path, extn_list=None, file_descr=''):
    """A utility method to check for input file path and normalize the path if present.
    If extension list and file_descr are provided, then do additional checks to
    ensure that the correct file type has been specified.

    Args:
        file_path: The path of the input. Will be normalized through 'typing'
        extn_list: List of extensions, including the leading dot e.g. ['.hdr','.pic']
            which if provided will be checked for before the path is set. If there
            is no match, a value error will be raised.
        file_descr: A phrase describing the file (e.g. 'Radiance HDR') that can be
            used to compose the error message in case the extension check fails.
    """

    if file_path is None:
        return None
    else:
        file_name, file_extn = os.path.splitext(file_path)

        if extn_list:
            assert type(extn_list) in (list, tuple), \
                'The input for extn_list(%s) should either be a list or a tuple that ' \
                'contains extensions (e.g. [".jpg",".bmp"]'

        if extn_list and file_extn.lower() not in extn_list:
            file_descr = 'for %s files' % file_descr if file_descr else ''
            err_msg = 'The provided input (%s) is invalid %s as only a file with the ' \
                      'following extensions is allowed: %s' % (file_path, file_descr,
                                                               ','.join(extn_list))
            raise ValueError(err_msg)
        return normpath(file_path)

def path_checker_multiple(file_paths, extn_list=None, file_descr='',
                          outputs_as_string=False):
    """A utility method to check for list (or tuple) of input file paths and
        return either a list of normalized paths or a single string containing
        space-separated normalized paths. If extension list and file_descr are
        provided, then do additional checks to ensure that the correct file type
        has been specified.

    Args:
        file_paths: List of input file paths. Will be normalized through 'typing'
        extn_list: List of extensions, including the leading dot e.g. ['.hdr','.pic']
            which if provided will be checked for before the path is set. If there
            is no match, a value error will be raised.
        file_descr: A phrase describing the file (e.g. 'Radiance HDR') that can be
            used to compose the error message in case the extension check fails.
        outputs_as_string: If set to True, the files will be returned as single
            string of normalized paths. Else a list of normalized paths will
            be returned.
    """

    if not file_paths:
        file_paths = []
    elif not isinstance(file_paths, (list, tuple)):
        file_paths = [file_paths]

    final_path_list = [path_checker(file_path,
                                    extn_list=extn_list, file_descr=file_descr)
                       for file_path in file_paths]

    if outputs_as_string:
        return ' '.join(final_path_list)
    else:
        return final_path_list


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon May  1 16:06:00 2023

@author: chris
"""

import numpy as np
import matplotlib.pyplot as plt
from model.plotting.plotting import *
from model.model import ModelResult
from model.helper import calculate_percentiles

mstar = load_model('mstar', 'stellar_blackhole', redshift=0)

total_bhmf = np.load('model/data/BHMF/Schulze2010total.npz')
total_bhmf = {0:total_bhmf['0']}

model = ModelResult(0, total_bhmf,
              'mbh', 'quasar', 'successive',
              fitting_method='mcmc',
              saving_mode='temp',
              fixed_m_c=False)

x = np.linspace(6,9.2,100)
phi_sample = np.array(model.get_ndf_sample(z=0, num=1000,
                                           quantity_range=x))[:,:,1]
ndf = calculate_percentiles(phi_sample).T

plt.close()

plt.fill_between(x, ndf[:,1], ndf[:,2], alpha=0.2, color='purple',
                 label='black hole mass model')
#plt.plot(x, ndf[:,0], color='purple', linewidth= 5, label='Model')

plt.scatter(total_bhmf[0][:,0],total_bhmf[0][:,1], color='black',
            label = 'Schulze2010 total BHMF')

plt.xlabel('log (black hole mass)')
plt.ylabel('log phi (black hole mass)')

plt.legend()

plt.savefig('totalBHMF.png')

# p =Plot_q1_q2_relation(mstar, model, datapoints=True,
#                     quantity_range=np.linspace(8.7,11.9,100),
#                     sigma=2,
#                     columns='single')


#! /usr/bin/env python3

from collections import OrderedDict
import datetime
import os
import sys
import textwrap

from plaid import Client
from plaid import errors as plaid_errors

import plaid2text.config_manager as cm
from plaid2text.interact import prompt, clear_screen, NullValidator
from plaid2text.interact import NumberValidator, NumLengthValidator, YesNoValidator, PATH_COMPLETER

class PlaidAccess():
    def __init__(self, client_id=None, secret=None):
        if client_id and secret:
            self.client_id = client_id
            self.secret = secret
        else:
            self.client_id, self.secret = cm.get_plaid_config()

        self.client = Client(self.client_id, self.secret, "development", suppress_warnings=True)

    def get_transactions(self,
                         access_token,
                         start_date,
                         end_date,
                         account_ids):
        """Get transaction for a given account for the given dates"""

        ret = []
        total_transactions = None
        page = 0
        account_array = []
        account_array.append(account_ids)
        while True:
            page += 1
            if total_transactions:
                print("Fetching page %d, already fetched %d/%d transactions" % ( page, len(ret), total_transactions))
            else:
                print("Fetching page 1")

            try:
                response = self.client.Transactions.get(
                                access_token,
                                start_date.strftime("%Y-%m-%d"),
                                end_date.strftime("%Y-%m-%d"),
                                account_ids=account_array,
                                offset=len(ret))
            except plaid_errors.ItemError as ex:
                print("Unable to update plaid account [%s] due to: " % account_ids, file=sys.stderr)
                print("    %s" % ex, file=sys.stderr )
                sys.exit(1)

            total_transactions = response['total_transactions']

            ret.extend(response['transactions'])

            if len(ret) >= total_transactions: break

        print("Downloaded %d transactions for %s - %s" % ( len(ret), start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d")))

        return ret


# coding=utf-8
from pymongo import MongoClient

class Singleton(object):
    """
    单例模式
    """
    instance = None

    def __new__(cls, *args, **kw):
        if cls.instance is None:
            cls.instance = super().__new__(cls, *args, **kw)
        return cls.instance

class MYMongoclient(Singleton):
    def __init__(self):
        client = MongoClient()
        self.collection = client["job"]["zhilian"]

    def save_item(self, item):
        if isinstance(item, dict):
            self.collection.insert(item)

_mongo_client = MYMongoclient()
save_item = _mongo_client.save_item

if __name__ == '__main__':
    _mongo_client1 = MYMongoclient()
    _mongo_client2 = MYMongoclient()
    print(_mongo_client1)
    print(_mongo_client2)


__author__ = 'Daniel'

class Solution:
    def evalRPN(self, tokens):

        return self.eval_postfix(tokens)

    def eval_postfix(self, post):
        stk = []
        for elt in post:
            if elt.strip("-").isdigit():
                stk.append(int(elt))
            else:
                b = stk.pop()
                a = stk.pop()
                if elt == "+":
                    stk.append(a+b)
                elif elt == "-":
                    stk.append(a-b)
                elif elt == "*":
                    stk.append(a*b)
                else:
                    stk.append(self.__div(a, b))

        if stk:
            return stk[-1]
        return 0

    def __div(self, a, b):
        sign = 1
        if a*b < 0:
            sign = -1

        return abs(a)/abs(b)*sign

data_files/Evaluate Reverse Polish Notation.py


'''
Determine whether an integer is a palindrome. An integer is a palindrome when it reads
the same backward as forward.

Example 1:
Input: 121
Output: true

Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-.
Therefore it is not a palindrome.

Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
'''

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x<0:
            return False
        ######## USING STRING ###########
        s = str(x)
        l = len(s)
        i,j = 0,l-1
        while(i < j):
            if s[i]==s[j]:
                i += 1
                j -= 1
            else:
                return False
        if (i==j or i>j):
            return True

        ######## WITHOUT STRING ################
        reverse = 0
        y = x
        while x>0:
            temp = x%10
            reverse = reverse*10 + temp
            x = x//10
        if y==reverse:
            return True
        else:
            return False


from math import factorial as f
import sys

for line in sys.stdin:
    dups = {}

    line = line.strip()
    for c in line:
        if c in dups:
            dups[c] += 1
        else:
            dups[c] = 1

    # all permutations (including duplicates)
    perms = f(len(line))

    # If there are v instances of k, assume for a moment that
    # they are distinct.  There are v! permutations of those v copies
    # of the letter k.
    # We must divide out the v! occurrences because they represent
    # the number of times we counted duplicates in our original figure.

    # Do so for all letters
    for k, v in dups.items():
        perms = perms // f(v)

    print(perms)


import numpy as np

def kernel(x, y, d):
    return (1 + np.dot(x, y)) ** d

class KernelVotedPerceptron:
    def __init__(self, T, d):
        self.T = T
        self.C = []
        self.K = []
        self.WY = []
        self.WX = []
        self.d = d

    def train(self, x, y):

        k = 0
        wy = []
        wx = []
        c = [0]
        partial = []
        for epoch in range(self.T):
            for i in range(len(x)):
                s = 0
                if k == 0:
                    s = 0
                else:
                    for j in range(k):
                        s += wy[j] * kernel(wx[j], x[i], d=self.d)
                pred = 1 if s > 0 else -1
                if pred == y[i]:
                    c[k] += 1
                else:
                    wy.append(y[i])
                    wx.append(x[i])
                    c.append(1)
                    k += 1
                if epoch != 0 or i != 0:          #every tenth of an epoch (exluding 0) we save the number of errors k so that we can recreate the partial wight vector
                    if i % (len(x) / 10) == 0: partial.append(k)

        self.C = c
        self.K = k
        self.WY = wy
        self.WX = wx

        return partial

    def vote(self, x, partial):
        predictions = []
        x0 = np.zeros(len(x[0]))

        for l in range(len(x)):

            #for each x, we store the product vx as an array so we don't have to calculate it every cycle
            vx = []
            vx.append(0 + 1*kernel(x0, x[l], d= self.d)) #this is the first element, we treat the first mistaken x as a vector of all zeros
            for j in range(1, partial[-1]):
                vx.append(vx[j - 1] + self.WY[j] * kernel(self.WX[j], x[l], d = self.d))

            #we now compute a prediction using every partial weight vector
            partial_predictions = []
            for k in range (len(partial)):
                s = 0
                for i in range(partial[k]):
                    s = s + self.C[i] * np.sign(vx[i])
                partial_predictions.append(np.sign(s))

            predictions.append(partial_predictions)
        return predictions


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Code source: Gaël Varoquaux
#              Andreas Müller
# Modified for documentation by Jaques Grobler and by Aldebaro Klautau
# License: BSD 3 clause

import numpy as np
import csv
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import make_moons, make_circles, make_classification
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis

from ml4comm.qam_analyzer import ser

def train_classifier(clf_name, X, y, num_classes):
    """
    Parameters
    ==========
    clf_name: str
        Classifier name to be selected
    X:
    y:
    num_classes: int
        Total number of classes

    """
    names = ["Naive Bayes",
             "Decision Tree", "Random Forest",
             "AdaBoost",
             "Linear SVM", "RBF SVM", "Gaussian Process",
             "Neural Net",
             "QDA", "Nearest Neighbors"]

    classifiers = [
        GaussianNB(),
        DecisionTreeClassifier(max_depth=100),
        RandomForestClassifier(max_depth=100, n_estimators=30),
        AdaBoostClassifier(),
        LinearSVC(), #linear SVM (maximum margin perceptron)
        SVC(gamma=1, C=1),
        GaussianProcessClassifier(1.0 * RBF(1.0)),
        MLPClassifier(alpha=0.1, max_iter=500),
        QuadraticDiscriminantAnalysis(),
        KNeighborsClassifier(3)]

    assert(clf_name in names)

    clf_ind = names.index(clf_name)
    clf = classifiers[clf_ind]
    clf.fit(X, y)

    return clf

def main():
    file_name = 'qam_awgn.csv'
    with open(file_name, 'r') as f:
        data = list(csv.reader(f, delimiter=","))
    data = np.array(data, dtype=float)

    X = data[:,:-1] # Data points
    y = data[:,-1]  # Labels

    train_size = int(0.5*len(y))
    X_train = X[:train_size]
    y_train = y[:train_size]
    X_test  = X[train_size:]
    y_test  = y[train_size:]

    # iterate over classifiers
    names = ["Naive Bayes",
             "Decision Tree", "Random Forest",
             "AdaBoost",
             "Linear SVM", "RBF SVM", "Gaussian Process",
             "Neural Net",
             "QDA", "Nearest Neighbors"]

    for name in names:
        print("###### Training classifier: ", name)

        clf = train_classifier(name, X_train, y_train, np.max(y))
        clf.fit(X_train, y_train)

        pred_train = clf.predict(X_train)
        print('\nPrediction accuracy for the train dataset:\t {:.2%}'.format(
            metrics.accuracy_score(y_train, pred_train)
        ))

        pred_test = clf.predict(X_test)
        print('\nPrediction accuracy for the test dataset:\t {:.2%}'.format(
            metrics.accuracy_score(y_test, pred_test)
        ))

        ser_test = ser(clf, X_test, y_test)
        print('\nSymbol error rate (SER) for the test dataset:\t {:.2%}'.format(
            ser_test
        ))

        print('\n\n')

if __name__ == '__main__':
    main()


from django.urls import path

from . import views

urlpatterns=[
    path('login',views.login,name="login"),
    path('register',views.register,name="register"),
    path('logout',views.logout_user,name="logout"),
    # Here we are using logout_user for views because there is an built-in function named logout so that name is unavailable
    path('dashboard',views.dashboard,name="dashboard"),
]


# -*- coding: utf-8 -*-
"""
Created on Sat Oct  5 17:40:41 2019

@author: LINMUX
"""
"""
主要包括： 1.堆的pop和push，根据优先级的大小pop
          2.Removing Duplicates from a Sequence while Maintaining Order
          3."Determining the Most Frequently Occurring Items in a Sequence"
          4." Grouping Records Together Based on a Field "
"""
#############################################################################
"""q = PriorQueue()
                q.push(1,Item('foo'))
                q.push(5,Item('bar'))
                q.push(2,Item('spam'))
                q.push(3,Item('grok'))
        q.queue=
                [(1, 0, item('foo')),
                 (3, 3, item('grok')),
                 (2, 2, item('spam')),
                 (5, 1, item('bar'))]
                """
import heapq

class PriorQueue:
    def __init__(self):
        self.queue=[];
        self.index=0
    def push(self,Priority,item):
        heapq.heappush(self.queue,(Priority,self.index,item))
        self.index+=1
    def pop(self):
       return heapq.heappop(self.queue)[-1]

class Item:
    def __init__(self,name):
        self.name=name
    def __repr__(self):
       return 'item({!r})'.format(self.name) #str.format()用于填充字符串

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

"Removing Duplicates from a Sequence while Maintaining Order "
###############################################################################
#注意到yield函数的特殊用法

"""对于set()也有同样的作用，但是set后的list是无序的
例如：
a = [1, 5, 2, 1, 9, 1, 5, 10]
set(a)=[1, 2, 5, 9, 10]
"""
def dedupe(items):
    seen=set()
    for item in items:
        if item not in seen:
            yield item
            seen.add(item)

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

"Determining the Most Frequently Occurring Items in a Sequence"
###############################################################################
from collections import Counter

words = [   'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
         'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
         'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
         'my', 'eyes', "you're", 'under' ]
words_count=Counter(words)
max(zip(words_count.values(),words_count.keys()))
###############################################################################

" Grouping Records Together Based on a Field "
###############################################################################
from operator import itemgetter
from itertools import groupby

rows = [{'address': '5412 N CLARK', 'date': '07/01/2012'},
        {'address': '5148 N CLARK', 'date': '07/04/2012'},
        {'address': '5800 E 58TH', 'date': '07/02/2012'},
        {'address': '2122 N CLARK', 'date': '07/03/2012'},
        {'address': '5645 N RAVENSWOOD', 'date': '07/02/2012'},
        {'address': '1060 W ADDISON', 'date': '07/02/2012'},
        {'address': '4801 N BROADWAY', 'date': '07/01/2012'},
        {'address': '1039 W GRANVILLE', 'date': '07/04/2012'}
        ]

rows.sort(key=itemgetter('date'))

for date, items in groupby(rows, key=itemgetter('date')):
    print(date)
    for i in items:
        print('    ', i)

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


from appium import webdriver
import time

from appium.webdriver.common.appiumby import AppiumBy
from selenium.common.exceptions import ElementNotVisibleException, ElementNotSelectableException, NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait

"""
1.) Mobile Browser version and ChromeDriver or respective Browser Driver should be in same version
2.)
Two Ways of Identifying locators on webview i) open chrome browser and type "chrome://inspect/#devices" ii) Use Browser
inspectors

"""
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '11'
desired_caps['deviceName'] = 'Pixel'
desired_caps['app'] = ('/Users/sujithreddy/Documents/Code2Lead/Others/kwad.apk')
desired_caps['appPackage'] = 'com.android.chrome'
desired_caps['appActivity'] = 'com.google.android.apps.chrome.Main'

# 1. Create the Driver object
driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", desired_caps)

# 2. Create WebDriverWait
wait = WebDriverWait(driver, 25, poll_frequency=1,
                     ignored_exceptions=[ElementNotVisibleException, ElementNotSelectableException,
                                         NoSuchElementException])

# 3. Open the URL in Browser
ele = wait.until(lambda x: x.find_element(AppiumBy.ID, "com.android.chrome:id/terms_accept"))
ele.click()

ele2 = wait.until(lambda x: x.find_element(AppiumBy.ID, "com.android.chrome:id/negative_button"))
ele2.click()

ele3 = wait.until(lambda x: x.find_element(AppiumBy.ID, "com.android.chrome:id/search_box_text"))
ele3.click()

ele4 = wait.until(lambda x: x.find_element(AppiumBy.ID, "com.android.chrome:id/url_bar"))
ele4.click()
ele4.send_keys("https://www.google.com/")

driver.press_keycode(66)

time.sleep(5)

# 4. Get the list of Contexts in App
appContexts = driver.contexts
print("AppContexts : ", appContexts)

# 5. switch to webview to perform action on Required URL or on WebView
for appType in appContexts:
    if appType == "WEBVIEW_chrome":
        driver.switch_to.context(appType)

# 6. Do testing on Webview screen in chrome browser or any if we want
ele4 = wait.until(lambda x: x.find_element(AppiumBy.XPATH, "//*[@name='q']"))
ele4.send_keys("Skill2Lead")

# 7. Switch back to native view to perform action
for appType in appContexts:
    if appType == "NATIVE_APP":
        driver.switch_to.context(appType)

# 8. Do testing on native app screen if we want

ele4 = wait.until(lambda x: x.find_element(AppiumBy.ID, "com.android.chrome:id/url_bar"))
ele4.click()
ele4.send_keys("https://www.skill2lead.com/")
driver.press_keycode(66)

# 9. Quit or close the driver object

time.sleep(5)
driver.quit()


#!/usr/bin/python
from ming import *

import sys
mediadir = sys.argv[1]+'/../Media'

Ming_useSWFVersion(7);
m =  SWFMovie();

mc =  SWFMovieClip();

stream = SWFSoundStream(mediadir + '/audio01.mp3')
mc.setSoundStream(stream, m.getRate())
for i in range (0, 200):
	mc.nextFrame()

m.add(mc);
m.nextFrame();

m.save("test02.swf");


#!/usr/bin/env python
# coding: utf-8

# # *section 4: Strings*
#
# ### writer : Faranak Alikhah 1954128

# ### 4.Set .discard(), .remove() & .pop():
#

# In[ ]:

n = int(input())
s = set(map(int, input().split()))
num_comments=int(input())
for i in range(num_comments):
    comments=input().split( )
    if comments[0]=="remove":
            s.remove(int(comments[1]))
    elif comments[0]=="discard":
            s.discard(int(comments[1]))
    else :
         s.pop()

print(sum(s))

#


import os
import sys
import json
import jsonschema
import jsonref

def findadd(n):
    if ( (type(n) is dict) or (type(n) is jsonref.JsonRef) ):
        # print (n)
        if "attributes" in n:
            print("YESSSS")
        for p in n:
            if ( (type(n[p]) is list) or (type(n[p]) is dict) ):
                findadd(n[p])
            # else:
                # print("---", n[p])
    elif (type(n) is list):
        for each in n:
            if ( (type(each) is dict) or (type(each) is jsonref.JsonRef) or (type(each) is list) ):
                # print(each)
                # sys.exit()
                findadd(each)
            # else:
                # print("-->", each)
    # else:
        # print("***", type(n), n)

        # if "attributes" in n:
        #     print(n)
        # else:

root_schema = '/Users/hugo/projects/cityjson/schemas/cityjson.schema.json'
fins = open(root_schema)

abs_path = os.path.abspath(os.path.dirname(root_schema))
base_uri = 'file://{}/'.format(abs_path)

js = jsonref.loads(fins.read(), jsonschema=True, base_uri=base_uri)
findadd(js)

# print (type(js))
# print (type(js["properties"]["CityObjects"]["additionalProperties"]["oneOf"]))
# print(js)

# -- output stitched_schema
json_str = json.dumps(js, indent=2)
f = open('/Users/hugo/temp/out.json', "w")
f.write(json_str)


# https://github.com/amalshaji/style-transfer/blob/master/backend/inference.py
import cv2

from style_transfer_utility.config import MODEL_PATH

def inference(model, image):
    model_name = f"{MODEL_PATH}{model}.t7"
    model = cv2.dnn.readNetFromTorch(model_name)

    height, width = int(image.shape[0]), int(image.shape[1])
    new_width = int((640 / height) * width)
    resized_image = cv2.resize(image, (new_width, 640), interpolation=cv2.INTER_AREA)

    # Create our blob from the image
    # Then perform a forward pass run of the network
    # The Mean values for the ImageNet training set are R=103.93, G=116.77, B=123.68

    inp_blob = cv2.dnn.blobFromImage(
        image=resized_image,
        scalefactor=1.0,
        size=(new_width, 640),
        mean=(103.93, 116.77, 123.68),
        swapRB=False,
        crop=False,
    )

    model.setInput(inp_blob)
    output = model.forward()

    # Reshape the output Tensor,
    # add back the mean substraction,
    # re-order the channels
    output = output.reshape(3, output.shape[2], output.shape[3])
    output[0] += 103.93
    output[1] += 116.77
    output[2] += 123.68

    output = output.transpose(1, 2, 0)
    return output, resized_image


from PyQt5.QtWebEngineWidgets import QWebEngineView

class Browser(QWebEngineView):

    def __init__(self,parent = None):
        # print('new browser')
        super().__init__(parent=parent)
        self.setZoomFactor(1.25)
        # print(self.zoomFactor())

if __name__ == '__main__':
    bro = Browser()
    bro.keyPressEvent()


import json, re, requests
from action import Action
from const import CARD_USAGE_LEAGUES, CARD_USAGE_URL, DETA_KEY, ON_DEMAND_ISR_URL
from datetime import datetime, timedelta
from deta import Deta
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from itertools import chain
from pytz import timezone
from typing import Optional
from utility import get_cards, search_card

app = FastAPI()

origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

db = Deta(DETA_KEY).Base("card-usages")

with open("kitty_card_ids.json", "r") as k:
    ids = json.load(k)
ids_reversed = {value: key for key, value in ids.items()}
usage_caches = {}

@app.get("/cards")
def get_card(name: Optional[str] = None, id: Optional[str] = None, stringify: Optional[bool] = False):
    if not name and not id:
        return {"result": get_cards()}
    else:
        return {"result": search_card(stringify, name, id)}

@app.get("/usages")
def get_card_usages(league: Optional[str] = None, target_date: Optional[str] = None):
    date = validate_date(datetime.now(timezone("Asia/Seoul")).strftime("%Y%m%d")) if not target_date else target_date

    if date in usage_caches.keys():
        return {"result": usage_caches[date] if not league else usage_caches[date][league]}

    usages = db.get(date)["usages"]
    usage_caches[date] = usages

    if league:
        usages = {league: usages[league]}

    for usage in usages.values():
        for tier, value in usage.items():
            usage[tier] = {
                "neutral": [x for x in value if ids_reversed[x][0] == "N"],
                "swarm": [x for x in value if ids_reversed[x][0] == "S"],
                "winter": [x for x in value if ids_reversed[x][0] == "W"],
                "shadowfen": [x for x in value if ids_reversed[x][0] == "F"],
                "ironclad": [x for x in value if ids_reversed[x][0] == "I"]
            }

    return {"result": usages if not league else usages[league]}

@app.get("/usage-ranks")
def get_card_usage_ranks(league: Optional[str] = None, target_date: Optional[str] = None):
    kingdoms = ["neutral", "swarm", "winter", "shadowfen", "ironclad"]

    result = {x: {} for x in CARD_USAGE_LEAGUES} if not league else {league: {}}
    date = validate_date(datetime.now(timezone("Asia/Seoul")).strftime("%Y%m%d") if not target_date else target_date)
    usages = get_card_usages(league, date)["result"]

    for key in result.keys():
        ranks = {x: [] for x in kingdoms}

        for value in (usages[key].values() if not league else usages.values()):
            for kingdom in kingdoms:
                ranks[kingdom][:0] = value[kingdom]

        for kingdom, cards in ranks.items():
            for card in cards:
                result[key][card] = ranks[kingdom].index(card) + 1

    return {"result": result if not league else result[league]}

@app.get("/usage-changes")
def get_card_usage_changes(league: Optional[str] = None, target_date: Optional[str] = None):
    kingdoms = ["neutral", "swarm", "winter", "shadowfen", "ironclad"]

    result = {x: {} for x in CARD_USAGE_LEAGUES} if not league else {league: {}}
    date = validate_date(datetime.now(timezone("Asia/Seoul")).strftime("%Y%m%d") if not target_date else target_date)
    now = get_card_usages(league, date)["result"]
    ago = get_card_usages(league, subtract_a_day(date))["result"]

    if now == ago: #아직 업데이트되지 않았을 때
        ago = get_card_usages(league, subtract_a_day(subtract_a_day(date)))["result"]

    for key in result.keys():
        now_list = {x: [] for x in kingdoms}
        ago_list = {x: [] for x in kingdoms}

        for now_value in (now[key].values() if not league else now.values()):
            for kingdom in kingdoms:
                now_list[kingdom][:0] = now_value[kingdom]

        for ago_value in (ago[key].values() if not league else ago.values()):
            for kingdom in kingdoms:
                ago_list[kingdom][:0] = ago_value[kingdom]

        for kingdom, cards in now_list.items():
            for card in cards:
                if card not in ago_list[kingdom]:
                    shift = "new"
                else:
                    temp = ago_list[kingdom].index(card) - now_list[kingdom].index(card)
                    now_tier = get_tier(now[key] if not league else now, card)
                    ago_tier = get_tier(ago[key] if not league else ago, card)

                    if now_tier < ago_tier: #하위 티어로 내려갔을 때
                        temp -= 1
                    elif now_tier > ago_tier: #상위 티어로 올라갔을 때
                        temp += 1

                    shift = str(temp)

                result[key][card] = shift

    return {"result": result if not league else result[league]}

@app.get("/ranged-usages")
def get_ranged_card_usages(id: str, league: Optional[str] = None, dates: Optional[int] = 7):
    result = {x: {} for x in CARD_USAGE_LEAGUES} if not league else {league: {}}
    date = validate_date(datetime.now(timezone("Asia/Seoul")).strftime("%Y%m%d"))

    for _ in range(dates):
        all_ranks = get_card_usage_ranks(league, date)["result"]

        for key in result.keys():
            ranks = all_ranks[key] if not league else all_ranks
            result[key][date[4:]] = "-" if id not in ranks.keys() else str(ranks[id])

        date = subtract_a_day(date)

    return {"result": result if not league else result[league]}

@app.get("/ranged-usage-changes")
def get_ranged_card_usage_changes(id: str, league: Optional[str] = None, dates: Optional[int] = 7):
    result = {x: {} for x in CARD_USAGE_LEAGUES} if not league else {league: {}}
    date = validate_date(datetime.now(timezone("Asia/Seoul")).strftime("%Y%m%d"))

    for _ in range(dates):
        all_changes = get_card_usage_changes(league, date)["result"]

        for key in result.keys():
            changes = all_changes[key] if not league else all_changes
            result[key][date[4:]] = "-" if id not in changes.keys() else changes[id]

        date = subtract_a_day(date)

    return {"result": result if not league else result[league]}

@app.get("/test/get-cached-usages")
def get_cached_usages():
    return {"result": usage_caches}

@app.post("/__space/v0/actions")
def post_actions(action: Action):
    if action.event.id == "save_card_usage":
        save_card_usages()

def save_card_usages():
    global usage_caches
    result = {x: {} for x in CARD_USAGE_LEAGUES}

    for league in CARD_USAGE_LEAGUES:
        response = requests.get(f"{CARD_USAGE_URL}{league}")
        regex = re.search('"tiers":.+?(?=,"breadcrumbs")', response.text)
        datas = json.loads(f"{{{regex.group()}}}")

        for tier in datas["tiers"]:
            result[league][tier["name"]] = [ids[x] for x in tier["cards"]]

    usage_caches = {}
    db.put(data={"usages": result}, key=datetime.now(timezone("Asia/Seoul")).strftime("%Y%m%d"))
    requests.post(ON_DEMAND_ISR_URL)

def validate_date(date: str):
    result = db.fetch({"key": date})

    return date if result.items else subtract_a_day(date)

def subtract_a_day(date: str):
    return (datetime.strptime(date, "%Y%m%d") - timedelta(days=1)).strftime("%Y%m%d")

def get_tier(source: dict, target: str):
    for tier, kingdom in source.items():
        for cards in kingdom.values():
            if target in cards:
                return tier

    return None


import numpy as np
import cv2
import tensorflow as tf
from dataset.mtcnn.detect_face import create_mtcnn, detect_face
from main.setup import Setup

sess = tf.Session()
with sess.as_default():
    pnet, rnet, onet = create_mtcnn(sess, None)

img = cv2.imread("D:/s5/lena/s05.jpg")

# 缩放因子
factor_mini = Setup.s3_factor_mini
# 缩小图像加快检测速度
width, height = img.shape[1], img.shape[0]
img_mini = cv2.resize(img, (int(width * factor_mini), int(height * factor_mini)))

total_boxes, points = detect_face(img_mini, Setup.s3_minsize, pnet, rnet, onet,
                                  Setup.s3_threshold, Setup.s3_factor)
total_boxes = np.divide(total_boxes, factor_mini)
points = np.transpose(np.divide(points, factor_mini))
print(total_boxes)
print(points)

for i, box in enumerate(total_boxes):
    p1 = (int(box[0]), int(box[1]))
    p2 = (int(box[2]), int(box[3]))
    img = cv2.rectangle(img, p1, p2, (255, 0, 0), 3)

    color = (255, 0, 0) if i % 2 == 0 else (0, 255, 0)
    for j in range(int(len(points[i]) / 2)):
        img = cv2.circle(img, (int(points[i][j]), int(points[i][j + 5])),
                         5, color, thickness=3)

cv2.imshow("es", img)
cv2.waitKey(0)


import os
import subprocess
from audio_length import escape_characters
import argparse

filetypes_to_convert=[".mp3",".m4a", ".webm"]

def convert(filename):
  filename_extensionless, extension = os.path.splitext(filename)
  new_filename = "".join([filename_extensionless, ".wav"])
  if not os.path.exists(new_filename):
    command = "ffmpeg -i \"{}\" -ac 1 \"{}\"".format(escape_characters(filename), escape_characters(new_filename))
    subprocess.call(command, shell=True)

def walk_path(path):
  for root, dirs, files in os.walk(path):
    for sound_file in files:
      _, extension = os.path.splitext(sound_file)
      #print sound_file
      if extension in filetypes_to_convert:
        yield os.path.join(root, sound_file)
      else:
        continue

if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--path', dest='path', help='Directory for the files to convert', required=True)
  args = parser.parse_args()

  for sound_file in walk_path(args.path):
    convert(sound_file)


# !/usr/bin/python
# -*- coding: UTF-8 -*-
"""
import: pytest, flask, flask_cors
"""
import os
import sys
import time
from concurrent.futures import ThreadPoolExecutor
import pytest
from flask import Flask, request, make_response
from flask_cors import *
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
sys.path.append(os.path.dirname(__file__))

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
CORS(app, supports_credentials=True)

app.executor = ThreadPoolExecutor(10)

def analytical_data(data, report_name):
    """
    将请求中的参数放入队列
    """
    pytest_run_data = ['-v', f'--html={report_name}']
    for i in data:

        if len(i) == 1:
            data_str = '' + i[0]
            pytest_run_data.append(data_str)
            continue
        else:
            data_str = '' + i[0] + '::'
            if issubclass(type(i[1][0]), list):
                for y in i[1][0]:
                    pytest_run_data.append(data_str + y)
                    continue
            elif len(i[1]) == 1:
                pytest_run_data.append(data_str + i[1][0])
                continue
            else:
                for y in i[1][1]:
                    pytest_run_data.append(data_str + i[1][0] + '::' + y)
    pytest.main(pytest_run_data)

@app.route('/run_ui_auto', methods=["POST"])
def run_ui_auto():
    """

    接口接收一个list
    [[test_file.py, [class_name, [model_name1, model_name2]]]]: 有类，有方法执行
    [[test_file.py, [[model_name1, model_name2]]]]: 没有类，指定方法执行
    [[test_file.py, []]]: 按照文件运行
    [
     [test_file.py, []],
     [test_file.py, [[model_name1, model_name2]]],
     [test_file.py, [类名, [model_name1, model_name2]]]
    ]: 多文件运行
    """
    report_key = str(int(time.time() * 1000))
    report_name = 'test_No.' + report_key + '.html'
    data_list = request.json.get('data_list')
    app.executor.submit(analytical_data, data_list, report_name)

    return make_response({'msg': 'running.....', 'report_key': report_key})

if __name__ == '__main__':
    app.run(debug=False, host='127.0.0.1', port=5005, threaded=False)


import traceback

import redis
from django.core.management.base import BaseCommand
import socket

from scanner.models import Website, Subdomain

class Command(BaseCommand):
    help = 'Submit Results'

    def add_arguments(self, parser):
        parser.add_argument('website', nargs=1, type=str)

    def handle(self, *args, **options):
        website = options["website"]
        website = website[0]
        website_obj = Website.objects.get(domain=website)
        website = website.encode()
        try:
            redis_con = redis.Redis(host='localhost', port=6379, db=0)
            while redis_con.exists(website):
                result = redis_con.lpop(website)
                result = result.decode()
                subdomain_name, result = result.split('@@@@')
                try:
                    Subdomain.objects.create(subdomain_name=subdomain_name, result=result, website=website_obj,
                                             ip_address=socket.gethostbyname(subdomain_name))
                except socket.gaierror:
                    Subdomain.objects.create(subdomain_name=subdomain_name, result=result, website=website_obj)
            website_obj.status = Website.FINISHED
            website_obj.save()
        except Exception as exp:
            print(str(exp))
            print(traceback.format_exc())
            website_obj.status = Website.ERROR
            website_obj.save()


import json
import subprocess

import common
from autotest_lib.client.common_lib import utils
from autotest_lib.server import frontend

# _OMAHA_STATUS - URI of a file in GoogleStorage with a JSON object
# summarizing all versions currently being served by Omaha.
#
# The principal data is in an array named 'omaha_data'.  Each entry
# in the array contains information relevant to one image being
# served by Omaha, including the following information:
#   * The board name of the product, as known to Omaha.
#   * The channel associated with the image.
#   * The Chrome and Chrome OS version strings for the image
#     being served.
#
_OMAHA_STATUS = 'gs://chromeos-build-release-console/omaha_status.json'

# _BUILD_METADATA_PATTERN - Format string for the URI of a file in
# GoogleStorage with a JSON object that contains metadata about
# a given build.  The metadata includes the version of firmware
# bundled with the build.
#
_BUILD_METADATA_PATTERN = 'gs://chromeos-image-archive/%s/metadata.json'

# _FIRMWARE_UPGRADE_DENYLIST - a set of boards that are exempt from
# automatic stable firmware version assignment.  This denylist is
# here out of an abundance of caution, on the general principle of "if
# it ain't broke, don't fix it."  Specifically, these are old, legacy
# boards and:
#   * They're working fine with whatever firmware they have in the lab
#     right now.
#   * Because of their age, we can expect that they will never get any
#     new firmware updates in future.
#   * Servo support is spotty or missing, so there's no certainty that
#     DUTs bricked by a firmware update can be repaired.
#   * Because of their age, they are somewhere between hard and
#     impossible to replace.  In some cases, they are also already in
#     short supply.
#
# N.B.  HARDCODED BOARD NAMES ARE EVIL!!!  This denylist uses hardcoded
# names because it's meant to define a list of legacies that will shrivel
# and die over time.
#
# DO NOT ADD TO THIS LIST.  If there's a new use case that requires
# extending the denylist concept, you should find a maintainable
# solution that deletes this code.
#
# TODO(jrbarnette):  When any board is past EOL, and removed from the
# lab, it can be removed from the denylist.  When all the boards are
# past EOL, the denylist should be removed.

_FIRMWARE_UPGRADE_DENYLIST = set([
        'butterfly',
        'daisy',
        'daisy_skate',
        'daisy_spring',
        'lumpy',
        'parrot',
        'parrot_ivb',
        'peach_pi',
        'peach_pit',
        'stout',
        'stumpy',
        'x86-alex',
        'x86-mario',
        'x86-zgb',
])

def _read_gs_json_data(gs_uri):
    """Read and parse a JSON file from GoogleStorage.

    This is a wrapper around `gsutil cat` for the specified URI.
    The standard output of the command is parsed as JSON, and the
    resulting object returned.

    @param gs_uri   URI of the JSON file in GoogleStorage.
    @return A JSON object parsed from `gs_uri`.
    """
    with open('/dev/null', 'w') as ignore_errors:
        sp = subprocess.Popen(['gsutil', 'cat', gs_uri],
                              stdout=subprocess.PIPE,
                              stderr=ignore_errors)
        try:
            json_object = json.load(sp.stdout)
        finally:
            sp.stdout.close()
            sp.wait()
    return json_object

def _read_build_metadata(board, cros_version):
    """Read and parse the `metadata.json` file for a build.

    Given the board and version string for a potential CrOS image,
    find the URI of the build in GoogleStorage, and return a Python
    object for the associated `metadata.json`.

    @param board         Board for the build to be read.
    @param cros_version  Build version string.
    """
    image_path = frontend.format_cros_image_name(board, cros_version)
    return _read_gs_json_data(_BUILD_METADATA_PATTERN % image_path)

def _get_by_key_path(dictdict, key_path):
    """Traverse a sequence of keys in a dict of dicts.

    The `dictdict` parameter is a dict of nested dict values, and
    `key_path` a list of keys.

    A single-element key path returns `dictdict[key_path[0]]`, a
    two-element path returns `dictdict[key_path[0]][key_path[1]]`, and
    so forth.  If any key in the path is not found, return `None`.

    @param dictdict   A dictionary of nested dictionaries.
    @param key_path   The sequence of keys to look up in `dictdict`.
    @return The value found by successive dictionary lookups, or `None`.
    """
    value = dictdict
    for key in key_path:
        value = value.get(key)
        if value is None:
            break
    return value

def _get_model_firmware_versions(metadata_json, board):
    """Get the firmware version for all models in a unibuild board.

    @param metadata_json    The metadata_json dict parsed from the
                            metadata.json file generated by the build.
    @param board            The board name of the unibuild.
    @return If the board has no models, return {board: None}.
            Otherwise, return a dict mapping each model name to its
            firmware version.
    """
    model_firmware_versions = {}
    key_path = ['board-metadata', board, 'models']
    model_versions = _get_by_key_path(metadata_json, key_path)

    if model_versions is not None:
        for model, fw_versions in model_versions.iteritems():
            fw_version = (fw_versions.get('main-readwrite-firmware-version') or
                          fw_versions.get('main-readonly-firmware-version'))
            model_firmware_versions[model] = fw_version
    else:
        model_firmware_versions[board] = None

    return model_firmware_versions

def get_omaha_version_map():
    """Convert omaha versions data to a versions mapping.

    Returns a dictionary mapping board names to the currently preferred
    version for the Beta channel as served by Omaha.  The mappings are
    provided by settings in the JSON object read from `_OMAHA_STATUS`.

    The board names are the names as known to Omaha:  If the board name
    in the AFE contains '_', the corresponding Omaha name uses '-'
    instead.  The boards mapped may include boards not in the list of
    managed boards in the lab.

    @return A dictionary mapping Omaha boards to Beta versions.
    """
    def _entry_valid(json_entry):
        return json_entry['channel'] == 'beta'

    def _get_omaha_data(json_entry):
        board = json_entry['board']['public_codename']
        milestone = json_entry['milestone']
        build = json_entry['chrome_os_version']
        version = 'R%d-%s' % (milestone, build)
        return (board, version)

    omaha_status = _read_gs_json_data(_OMAHA_STATUS)
    return dict(_get_omaha_data(e) for e in omaha_status['omaha_data']
                    if _entry_valid(e))

def get_omaha_upgrade(omaha_map, board, version):
    """Get the later of a build in `omaha_map` or `version`.

    Read the Omaha version for `board` from `omaha_map`, and compare it
    to `version`.  Return whichever version is more recent.

    N.B. `board` is the name of a board as known to the AFE.  Board
    names as known to Omaha are different; see
    `get_omaha_version_map()`, above.  This function is responsible
    for translating names as necessary.

    @param omaha_map  Mapping of Omaha board names to preferred builds.
    @param board      Name of the board to look up, as known to the AFE.
    @param version    Minimum version to be accepted.

    @return Returns a Chrome OS version string in standard form
            R##-####.#.#.  Will return `None` if `version` is `None` and
            no Omaha entry is found.
    """
    omaha_version = omaha_map.get(board.replace('_', '-'))
    if version is None:
        return omaha_version
    if omaha_version is not None:
        if utils.compare_versions(version, omaha_version) < 0:
            return omaha_version
    return version

def get_firmware_versions(board, cros_version):
    """Get the firmware versions for a given board and CrOS version.

    During the CrOS auto-update process, the system will check firmware
    on the target device, and update that firmware if needed.  This
    function finds the version string of the firmware that would be
    installed from a given CrOS build.

    A build may have firmware for more than one hardware model, so the
    returned value is a dictionary mapping models to firmware version
    strings.

    The returned firmware version value will be `None` if the build
    isn't found in storage, if there is no firmware found for the build,
    or if the board is denylisted from firmware updates in the test
    lab.

    @param board          The board for the firmware version to be
                          determined.
    @param cros_version   The CrOS version bundling the firmware.
    @return A dict mapping from board to firmware version string for
            non-unibuild board, or a dict mapping from models to firmware
            versions for a unibuild board (see return type of
            _get_model_firmware_versions)
    """
    if board in _FIRMWARE_UPGRADE_DENYLIST:
        return {board: None}
    try:
        metadata_json = _read_build_metadata(board, cros_version)
        unibuild = bool(_get_by_key_path(metadata_json, ['unibuild']))
        if unibuild:
            return _get_model_firmware_versions(metadata_json, board)
        else:
            key_path = ['board-metadata', board, 'main-firmware-version']
            return {board: _get_by_key_path(metadata_json, key_path)}
    except Exception as e:
        # TODO(jrbarnette): If we get here, it likely means that the
        # build for this board doesn't exist.  That can happen if a
        # board doesn't release on the Beta channel for at least 6 months.
        #
        # We can't allow this error to propagate up the call chain
        # because that will kill assigning versions to all the other
        # boards that are still OK, so for now we ignore it.  Probably,
        # we should do better.
        return {board: None}


from pizza import Pizza

# a:
print("Todas las pizzas tienen un tamaño {} y un valor de {}".format(
    Pizza.tamano, Pizza.precio
))

# b:
print(Pizza.validando_elemento("salsa de tomate", ["salsa de tomate", "salsa bbq"]))

# c:
pizza = Pizza()
pizza.pedido()

# d:
print("\nVegetales: {}\nCarne: {}\nTipo de masa: {}\n¿Es una pizza válida?: {}\n".format(
    pizza.vegetales, pizza.carnes, pizza.tipo_de_masa, pizza.pizza_valida
))

# e:
print("¿La clase es una pizza válida?: {}".format(pizza.pizza_valida))


def tiga_nilai_terbaik(daftar_nilai): #hasilnya tuple
    #urutkan secara descending
    daftar_nilai.sort(reverse=True) #urutkan secara descending
    hasil = tuple(daftar_nilai[:3]) #ambil tiga yang terdepan
    return hasil

n = 0
while n < 3:
    n = int(input('Masukkan n (minimal 3): '))

data = []
for i in range(n):
    nilai = int(input('Masukkan nilai: '))
    data.append(nilai)

hasil = tiga_nilai_terbaik(data)

print(f'1, {hasil[0]}\n2. {hasil[1]}\n3. {hasil[2]}')


import numpy as np
import matplotlib.pyplot as plt

#To get started choose only a few patterns to make the matrix invertible

N = {"horizontal":{"inputs":5,"hidden":{"layers":2,"neurons":3},"output":1},
	 "vertical":{"associative layer":2},"patterns":2}

for _ in range(10):
	arr = np.array([np.random.choice([0,1],size=N['horizontal']['hidden']['neurons']*N['horizontal']['hidden']['layers'])
					for _ in range(N['horizontal']['hidden']['neurons']*N['horizontal']['hidden']['layers'])])

	if np.linalg.det(arr) != 0:
		#Should normalize array
		#arr = np.divide(arr,np.linalg.norm(arr))
		B = np.linalg.inv(arr)

		for i in range(arr.shape[0]):
			print ('-----------------')
			print ('Presenting pattern %d'%i)
			presentation = B.dot(arr[:,i])
			presentation[np.absolute(presentation)<0.0001] #HACK
			idx = np.where(presentation==1)[0]
			if idx:
				print (idx[0] == i)
			else:
				print ('Did not recognize pattern %d'%i)
				print (arr[:,i])
				print (B.dot(arr[:,i]))
	'''
	fig = plt.figure()
	ax = fig.add_subplot(111)
	cax = ax.imshow(arr, interpolation='nearest',aspect='auto', cmap=plt.cm.bone_r)
	plt.colorbar(cax)
	ax.set_xlabel('Pattern')
	ax.set_ylabel('Hidden Neuron')
	fig.tight_layout()
	plt.show()
	'''


def main():
    n = int(input())
    obelisk_arr = [tuple(map(int, input().split())) for _ in range(n)]
    clue_arr = [tuple(map(int, input().split())) for _ in range(n)]

    set_arr = []
    for obelisk in obelisk_arr:
        temp_set = set()
        for clue in clue_arr:
            temp_set.add((clue[0] + obelisk[0], clue[1] + obelisk[1]))
        set_arr.append(temp_set)

    intersection_set = set_arr[0]
    for i in range(1, n):
        intersection_set = intersection_set.intersection(set_arr[i])

    for element in intersection_set:
        print(*element)
        break

if __name__ == "__main__":
    main()

# correct
# can be done in O(n) time by summimg the x and y coordinates of the obelisk and the clue and then dividing by n

codeforces/New Year and the Treasure Geolocation.py


def idendity_array(tab):
 deb=0
 fin=len(tab)-1
 while deb<=fin:
  if tab[deb]==tab[fin]:
   print(tab[deb])
   print(tab[fin])
   deb+=1
   fin-=1
  else:
   return -1
tab=["a","a","a","a","a","c","a","a","a","a"]
print(idendity_array(tab))


import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torchvision
from PIL import Image

train_dataset = torchvision.datasets.CIFAR10("./data", train=True, transform=torchvision.transforms.ToTensor, download=True)
test_dataset = torchvision.datasets.CIFAR10("./data", train=False, transform=torchvision.transforms.ToTensor)

train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=8)
test_loader = DataLoader(test_dataset, batch_size=64, num_workers=8)

class TrainNet(nn.Module):
    def __init__(self):
        super(TrainNet, self).__init__()
        self.model = nn.Sequential(
            nn.Conv2d(3, 32, (3, 3), (1, 1)),
            nn.ReLU(inplace=True),
            nn.MaxPool2d((2, 2), (1, 1)),

        )

for data in train_loader:
    img, target = data
    print(img)
    print(target)


import os
import subprocess as sp

from utils import dotdict

datasets_dir = os.path.dirname(os.path.realpath(__file__))

_ws_datasets = {
    # default word similarity datasets for English
    None: {
        "wordsim353": {
            "url": "https://leviants.com/wp-content/uploads/2020/01/wordsim353.zip",
            "raw_txt_rel_path": "combined.tab",
            "skip_lines": 1,
        },
        "rw": {
            "url": "https://nlp.stanford.edu/~lmthang/morphoNLM/rw.zip",
            "raw_txt_rel_path": "rw/rw.txt",
        },
        "card660": {
            "url": "https://pilehvar.github.io/card-660/dataset.tsv",
            "no_zip": True,
            "raw_txt_rel_path": "dataset.tsv",
        },
    },
    # multilingual word similarity datasets
    "en": {},
    "it": {},
    "ru": {},
    "de": {},
}

for lang, full_name in [('en', 'english'), ('it', 'italian'), ('ru', 'russian'), ('de', 'german')]:
    for ws_suffix in ("-rel", "-sim", ""):
        _ws_datasets[lang][f"ws353-{lang}{ws_suffix}"] = {
            "url": f"https://raw.githubusercontent.com/iraleviant/eval-multilingual-simlex/master/evaluation/ws-353/wordsim353-{full_name}{ws_suffix}.txt",
            "raw_txt_rel_path": f"wordsim353-{full_name}{ws_suffix}.txt",
            "no_zip": True,
            "skip_lines": 1,
        }

    _ws_datasets[lang][f"simlex999-{lang}"] = {
        "url": f"https://raw.githubusercontent.com/nmrksic/eval-multilingual-simlex/master/evaluation/simlex-{full_name}.txt",
        "raw_txt_rel_path": f"simlex-{full_name}.txt",
        "no_zip": True,
        "skip_lines": 1,
    }

def get_ws_dataset_names(lang=None):
    return list(_ws_datasets[lang])

def _get_ws_dataset_info(name):
    for datasets in _ws_datasets.values():
        if name in datasets:
            return datasets[name]

    raise NotImplementedError

def prepare_ws_dataset_paths(name):
    binfo = _get_ws_dataset_info(name)

    raw_txt_path = f"{datasets_dir}/{name}/{binfo['raw_txt_rel_path']}"
    txt_path = f"{datasets_dir}/{name}/{name}.txt"
    query_path = f"{datasets_dir}/{name}/queries.txt"

    if not os.path.exists(raw_txt_path):
        sp.call(
            f"""
            wget -c {binfo['url']} -P {datasets_dir}/{name}
        """.split()
        )
        if not binfo.get("no_zip"):
            sp.call(
                f"""
                unzip {datasets_dir}/{name}/{name}.zip -d {datasets_dir}/{name}
            """.split()
            )

    if not os.path.exists(txt_path):
        with open(raw_txt_path) as f, open(txt_path, "w") as fout:
            for i, line in enumerate(f):
                # discard head lines
                if i < binfo.get("skip_lines", 0):
                    continue
                # NOTE: in `fastText/eval.py`, golden words get lowercased anyways,
                # but predicted words remain as they are.
                print(line, end="", file=fout)

    if not os.path.exists(query_path):
        words = set()
        with open(txt_path) as f:
            for line in f:
                w1, w2 = line.split()[:2]
                words.add(w1)
                words.add(w2)
        with open(query_path, "w") as fout:
            for w in words:
                print(w, file=fout)

    return dotdict(
        txt_path=txt_path,
        query_path=query_path,
    )

def prepare_ws_combined_query_path(lang=None):
    """
    Prepare the combined query path for word similarity datasets dataset
    """

    combined_query_path = f"{datasets_dir}/combined_query_{lang}.txt"

    if not os.path.exists(combined_query_path):
        all_words = set()
        for bname in get_ws_dataset_names(lang):
            query_path = prepare_ws_dataset_paths(bname).query_path
            with open(query_path) as fin:
                for line in fin:
                    all_words.add(line.strip())
                    all_words.add(line.strip().lower())
        with open(combined_query_path, 'w') as fout:
            for w in all_words:
                print(w, file=fout)

    return combined_query_path

if __name__ == '__main__':
    for lang in [None, "en", "it", "ru", "de"]:
        for bname in get_ws_dataset_names(lang):
            prepare_ws_dataset_paths(bname)
        prepare_ws_combined_query_path(lang)


from random import randint

playing = True

while playing:
    print('Choose a number between 1 and 10')
    number = randint(1, 10)

    response = None
    while playing:
        response = int(input())
        if response == number:
            print('You got it! Yayyy!')
            break
        elif response < number:
            print('Too low, try again.')
        else:
            print('Too high, try again.')

    response = input('Do you want to play again? (y/n) ')
    if response[0].lower() == 'n':
        playing = False


import os
import uuid
from datetime import datetime

import boto3
import mailparser

from utils.models import IdeaModel, UserModel

from mail_templates.idea_received_confirmation.send_confirmation_idea_received import send_confirmation

AWS_REGION = os.environ['SES_AWS_REGION']
SES_S3_BUCKET_NAME = os.environ['SES_S3_BUCKET_NAME']
MAILBOX_ADDR = os.environ['MAILBOX_ADDR']
BASE_SITE_URL = f"https://{os.environ['DOMAIN_NAME']}/"

s3 = boto3.client('s3')
ses = boto3.client('ses', region_name=AWS_REGION)

import bleach

def sanitize_title(raw_text):
    if not raw_text or not len(raw_text):
        return ''
    return bleach.clean(raw_text,
                        tags=[],
                        strip_comments=True, strip=True)

def sanitize_no_html_text(raw_text):
    if not raw_text or not len(raw_text):
        return ''
    return bleach.clean(raw_text,
                        tags=['br'],
                        strip_comments=True, strip=True)

def sanitize_idea_content(content):
    if not content or not len(content):
        return None
    return bleach.clean(content,
                        tags=['br', 'a', 's', 'em', 'u',
                              'ol', 'ul', 'li',
                              'h1', 'h2', 'h3', 'h4',
                              'sub', 'sup',
                              'del', 'blockquote', 'pre'],
                        attributes={'a': ['href']}, strip_comments=True, strip=True)

def clean_email_html(email_html_content):
    """ Email clients have various tags case and ways to split lines.
    1) lowering tags case
    2) converting p and div to br to unify formatting.
    3) sanitizing tags that are not allowed in content
    4) getting title from first line
    5) getting content from rest lines
    6) pack into div for compatibility with trix editor
    """
    text_like_html = sanitize_idea_content(
        email_html_content
        .replace('
', '
')
        .replace('
', '
')
        .replace('
', '
')
        .replace('
', '
')

        .replace('
', '
')
        .replace('
', '
')
        .replace('
', '
')

        .replace('
', '
')
        .replace('
', '')
        .replace('
', '
')
        .replace('
', '')
        .replace('
', '
')
        .replace('
', '
\n')
    )
    raw_content_lines = text_like_html.splitlines()
    content_lines = []
    while len(raw_content_lines) and not raw_content_lines[0]:
        raw_content_lines = raw_content_lines[1:]
    title = None
    if len(raw_content_lines):
        title = sanitize_title(raw_content_lines[0])
        if len(raw_content_lines) > 1:
            for line in raw_content_lines[1:]:
                if MAILBOX_ADDR in line:
                    if len(content_lines) > 0:
                        content_lines = content_lines[:-1]  # last line before quote is usually "XXX wrote:" or spacer.
                    break
                content_lines.append(line)
    return title, ('
' + '\n'.join(content_lines) + '
').replace('\n', '').replace('

', '
')

def clean_email_text(email_text_content):
    raw_content_lines = email_text_content.splitlines()
    title = None
    content_lines = []
    while len(raw_content_lines) and not raw_content_lines[0]:
        raw_content_lines = raw_content_lines[1:]
    if len(raw_content_lines):
        title = sanitize_title(raw_content_lines[0])
        if len(raw_content_lines) > 1:
            for line in raw_content_lines[1:]:
                if MAILBOX_ADDR in line or line.startswith('>'):
                    if len(content_lines) > 0:
                        content_lines = content_lines[:-1]  # last line before quote is usually "XXX wrote:" or spacer.
                    break
                content_lines.append(line + '
')
    return title, '
' + sanitize_no_html_text('\n'.join(content_lines)) + '
'

def get_cleaned_email(parsed_email):
    text_part = parsed_email.text_plain[0] if parsed_email.text_plain else None
    html_part = parsed_email.text_html[0] if parsed_email.text_html else None
    if not text_part and not html_part:
        return None, None
    if text_part:
        return clean_email_text(text_part)
    return clean_email_html(html_part)

def processIncomingMail(parsed_email):
    from_email = parsed_email.from_
    found_users = UserModel.emailIndex.query(from_email[0][1])
    user = None
    for found_user in found_users:
        user = found_user
    if not user:
        # TOdo process email from user that dont registered
        return

    idea = IdeaModel(user.userId, str(uuid.uuid4()))
    title, content = get_cleaned_email(parsed_email)
    if title is None:
        return  # may be send notification about error?
    idea.content = content
    idea.title = title
    idea.authorName = user.name
    idea.authorSlug = user.slug
    idea.createdDate = datetime.now()
    idea.visibility = 'PUBLIC'
    idea_date_str = parsed_email.subject.split('[Daily Idea] Idea for ', 1)[1]
    idea.ideaDate = datetime.strptime(idea_date_str, '%a %b %d %Y')
    idea.likesCount = 0
    idea.commentsCount = 0
    idea.save()
    return idea

def endpoint(event, context):
    if 'ses' not in event['Records'][0]:
        print('this was not an SES event.  event["Records"][0]["ses"] not found')
        return
    ses_notification = event['Records'][0]['ses']
    mail_message_id = ses_notification['mail']['messageId']
    print(f"Message Id received: {mail_message_id}")

    try:
        data = s3.get_object(Bucket=SES_S3_BUCKET_NAME, Key=mail_message_id)
        raw_email = data['Body'].read()
        parsed_email = mailparser.parse_from_string(raw_email.decode('utf-8'))
        idea = processIncomingMail(parsed_email)
        send_confirmation(parsed_email.from_[0][1], idea, f"Re: {parsed_email.subject}")
    except Exception as e:
        print(e)
        raise e


#!/usr/bin/env python3
import math
import time
from threading import Lock

import RPi.GPIO as GPIO

import ioexpander as io

# Anemometer pins
ANI1 = 5       # P0.0
ANI2 = 6       # P0.1

# Wind vane (ADC)
WV = 8         # P0.3 ANI6
WV_RADIUS = 7  # Radius from center to the center of a cup, in CM
WV_CIRCUMFERENCE = WV_RADIUS * 2 * math.pi

# Rain gauge
R2 = 3         # P1.2
R3 = 7         # P1.1
R4 = 2         # P1.0
R5 = 1         # P1.5
RAIN_MM_PER_TICK = 0.2794

# Dictionary to map compass directions to ADC values
compass_values = {
    "North": 0.9,
    "North East": 2.0,
    "East": 3.0,
    "South East": 2.8,
    "South": 2.5,
    "South West": 1.5,
    "West": 0.3,
    "North West": 0.6
}

wind = 0
rain = 0

wind_overflows = 0
rain_overflows = 0

last_wind = 0
last_rain = 0

lock = Lock()

def handle_interrupt(stuff):
    global wind, rain, last_wind, last_rain, wind_overflows, rain_overflows
    lock.acquire(blocking=True)
    ioe.clear_interrupt()
    new_wind, _ = ioe.read_switch_counter(ANI2)
    new_rain, _ = ioe.read_switch_counter(R4)

    if new_wind < last_wind:
        wind_overflows += 1
    last_wind = new_wind
    wind = (wind_overflows * 128) + new_wind

    if new_rain < last_rain:
        rain_overflows += 1
    last_rain = new_rain
    rain = (rain_overflows * 128) + new_rain

    lock.release()

ioe = io.IOE(i2c_addr=0x18, interrupt_pin=4)

# Fudge to enable pull-up on interrupt pin
ioe._gpio.setup(ioe._interrupt_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP)

ioe.set_adc_vref(3.3)  # Input voltage of IO Expander, this is 3.3 on Breakout Garden

# Wind Vane
ioe.set_mode(WV, io.ADC)

# Anemometer
ioe.set_mode(ANI1, io.OUT)
ioe.output(ANI1, 0)
ioe.set_pin_interrupt(ANI2, True)
ioe.setup_switch_counter(ANI2)

# Rain Sensor
ioe.set_mode(R2, io.IN_PU)
ioe.set_mode(R3, io.OUT)
ioe.set_mode(R4, io.IN_PU)
ioe.setup_switch_counter(R4)
ioe.set_mode(R5, io.IN_PU)
ioe.output(R3, 0)
ioe.set_pin_interrupt(R4, True)

ioe.on_interrupt(handle_interrupt)
ioe.clear_interrupt()

last_wind_counts = 0
last_rain_counts = 0

while True:
    lock.acquire(blocking=True)
    wind_hz = (wind - last_wind_counts) / 2.0  # Two pulses per rotation
    wind_cms = wind_hz * WV_CIRCUMFERENCE
    wind_mph = wind_cms / 44.705
    rain_hz = rain - last_rain_counts
    rain_mm_sec = rain_hz * RAIN_MM_PER_TICK
    rain_mm_total = rain * RAIN_MM_PER_TICK
    direction = ioe.input(WV)
    compass_direction, value = min(compass_values.items(), key=lambda item: abs(item[1] - direction))
    print(f"""
Wind Counts: {wind} ({int(wind_hz * 60)} RPM)
Wind Speed: {wind_cms:1.2f} cm/sec {wind_mph:1.2f} MPH
Wind Direction: {direction:1.2f} ({compass_direction})
Rain Counts: {rain} ({rain_mm_total:0.2f} mm)
Rain Speed: {rain_mm_sec} mm/sec ({rain_hz} tips/sec)
""")
    last_wind_counts = wind
    last_rain_counts = rain
    lock.release()
    time.sleep(1.0)


from collections import deque
class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, newColor: int) -> List[List[int]]:
        """LC 733 Floor fill
        Time complexity: O(E + N)
        Space O(N)
        Difficulty: easy
        Args:
            image (List[List[int]]): [description]
            sr (int): [description]
            sc (int): [description]
            newColor (int): [description]

        Returns:
            List[List[int]]: [description]
        """
        queue = deque()
        m = len(image)
        n = len(image[0])
        check = [[False] * n for _ in range(m)]
        queue.append((sr, sc))
        check[sr][sc] = True
        target = image[sr][sc]
        while len(queue) > 0:
            x, y = queue.popleft()
            image[x][y] = newColor
            direction = [0, 1, 0, -1, 0]
            for i in range(4):
                next_x, next_y = x+direction[i], y + direction[i + 1]
                if 0 <= next_x < m and 0 <= next_y < n and not check[next_x][next_y] and image[next_x][next_y] == target:
                    queue.append((next_x, next_y))
                    check[next_x][next_y] = True
        return image


from os.path import split

from typing import List, Optional, Tuple

def extract_categories(infile: str, verbose: Optional[bool] = None) -> Tuple[List[str], List[str]]:
    path, uri = split(infile)
    uri, ext = uri.split('.YAMLDATA.yml')

    if verbose:
        print(f'Check {uri}')
        print(infile)

    with open(infile, 'r', encoding='utf-8') as yml_data_fh:
        content = yml_data_fh.read()

    mius = content.split('#MIU#Header#End#')
    categories = []
    reviewers = []

    for miu in mius:
        cat = [line.lstrip('category   : ').strip('"') for line in miu.split('\n') if line.startswith('category')]
        categories.extend(cat)
        rev = [line.lstrip('reviewer   : ').strip('"') for line in miu.split('\n') if line.startswith('reviewer')]
        reviewers.extend(rev)

    return categories, reviewers


'''

https://www.codingame.com/training/easy/chuck-norris

'''

def convert_to_bytes(message: str) -> str:
    res = []
    for ch in message:
        converted = bin(int.from_bytes(ch.encode(), 'big'))[2:].zfill(7)
        res.append(converted)

    return ''.join(res)

binary = convert_to_bytes(input())

out = []
dig_count = 1
for i, dig_cur in enumerate(binary):

    flag = '0' if dig_cur == '1' else '00'

    try:
        dig_nxt = binary[i+1]
    except:
        dig_nxt = ''

    if dig_nxt:
        if dig_cur == dig_nxt:
            dig_count += 1
        else:
            out.append(flag + ' ' + '0'* dig_count)
            dig_count = 1
    else:
        out.append(flag + ' ' + '0'* dig_count)
        dig_count = 1

print(' '.join(out))


def basic_clean(string):

    string = string.lower()

    string = unicodedata.normalize('NFKD', string).encode('ascii', 'ignore').decode('utf-8', 'ignore')

    string = re.sub(r"[^a-z0-9\s']", '', string)

    return string

def tokenize(string):

    tokenizer = ToktokTokenizer()

    return tokenizer.tokenize(string, return_str=True)

def stem(string):

    ps = nltk.porter.PorterStemmer()

    stems = [ps.stem(word) for word in string.split()]

    stemmed_string = ' '.join(stems)

    return stemmed_string

def lemmatize(string):

    wnl = nltk.stem.WordNetLemmatizer()

    lemmas = [wnl.lemmatize(word) for word in string.split()]

    lemmatized_string = ' '.join(lemmas)

    return lemmatized_string

def remove_stopwords(string, extra_words=None, exclude_words=None):

    stopword_list = stopwords.words('english')

    if exclude_words:

        stopword_list = stopword_list + exclude_words

    if extra_words:

        for word in extra_words:

            stopword_list.remove(word)

    words = string.split()

    filtered_words = [word for word in words if word not in stopword_list]

    filtered_string = ' '.join(filtered_words)

    return filtered_string


# %%
import tensorflow as tf

a = tf.placeholder(tf.int32, shape=[])
b = tf.constant(7, name='input_b')

c = tf.multiply(a, b, name='mul_c')
d = tf.add(a, b, name='add_d')
e = tf.add(c, d, name='add_e')

sess = tf.Session()
print(sess.run(e, feed_dict={a:10}))


import json
from login import login
import requests

def status_query(s, ip, detect_wan):
    adsl_status = s.post(f'http://{ip}/Action/call', json=detect_wan).text
    adsl_status = json.loads(adsl_status)

    ret = {}
    for i in adsl_status['Data']['iface_check']:
        ret[i['interface']] = i['errmsg']

    return ret

if __name__ == '__main__':
    ret = json.loads(open('ikuai.json', 'r').read())
    detect_wan = ret['detect_wan']

    s = requests.session()
    s.headers = {
        'Accept-Language': 'zh-CN,zh;q=0.9',
        'Content-Type': 'application/json;charset=UTF-8',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36 Edg/103.0.1264.62',
        'Accept': 'application/json, text/plain, */*'
    }

    login(s, 'admin', 'a12345')

    print(status_query(s, detect_wan))


import os
import cv2
import pydload
import logging
from . import data_utils
from .craft_model import build_craft_vgg_model

model_links = {
                'generic-english': 'https://github.com/bedapudi6788/keras-craft/releases/download/checkpoint-release/generic-english'
            }

model_alternate_names = {
    'default': 'generic-english'
}

class Detector():
    model = build_craft_vgg_model()
    def __init__(self, model_name = 'default'):
        if model_name in model_alternate_names:
            model_name = model_alternate_names[model_name]

        home = os.path.expanduser("~")
        checkpoint_dir = os.path.join(home, '.keras_craft_' + model_name)
        checkpoint_path = os.path.join(checkpoint_dir, 'checkpoint')

        if not os.path.exists(checkpoint_dir):
            os.mkdir(checkpoint_dir)

        if not os.path.exists(checkpoint_path):
            print('Downloading checkpoint', model_links[model_name], 'to', checkpoint_path)
            pydload.dload(url=model_links[model_name], save_to_path=checkpoint_path, max_time=None)

        Detector.model.load_weights(checkpoint_path)

    def detect(self, image_paths, max_width=720, max_height=None, batch_size=8, return_cropped_images=False):
        '''
        Function for reading image(s), running predictions.

        :param image_paths: single or list of opencv images or image file paths
        :max_width: images are scaled to this width keeping the aspect ratio.
        :max_height: either max_width or max_height should be used.

        :return: list of numpy arrays. each array is all the detected boxes in the corresponding image.
        '''
        return_single = False

        if not isinstance(image_paths, list):
            logging.warn('Batch for better performance')
            return_single = True
            image_paths = [image_paths]

        if not (max_width or max_height):
            logging.warn("Both max_width and max_height are set to None. Only do this if you are aware of the implications.")

        image_paths = [cv2.imread(im) for im in image_paths]

        loaded_images, scales_before_padding, shapes_before_padding = data_utils.read_images(image_paths, max_width = max_width, max_height = max_height)

        model_predictions = Detector.model.predict(loaded_images, batch_size=batch_size)

        boxes = data_utils.keras_pred_to_boxes(model_predictions, shapes=shapes_before_padding, scales=scales_before_padding)

        if return_cropped_images:
            cropped_images = []

            for image, _boxes in zip(image_paths, boxes):
                cropped_images.append([data_utils.get_crop_in_box(image, box) for box in _boxes])

            if return_single:
                cropped_images = cropped_images[0]
                boxes = boxes[0]

            return boxes, cropped_images

        if return_single:
            boxes = boxes[0]

        return boxes