from typing import List, Tuple, Dict

items = [(2, 10), (4, 15), (8, 4)]

def fractional_knapsack(items: List[Tuple], capacity: int) -> Dict[Tuple, float]:

    sorted_density: List[Tuple] = []
    result: Dict[Tuple, float] = {}

    for indx, elm in enumerate(items):
        assert elm[1] != 0, "vazn bayad vozorgtar az sefr bashe"
        # if elm[1] == 0:
        #     raise Exception("vazn bayad vozorgtar az sefr bashe")

        sorted_density.append((indx, elm[0] / elm[1]))
    sorted_density.sort(key=lambda x : x[1], reverse=True)
    for index, _ in sorted_density:
        item_weight = items[index][1]
        if capacity == 0:
            break
        elif capacity >= item_weight:
            result[items[index]] = 1
            capacity -= item_weight
        else:
            result[items[index]] = capacity / item_weight
            break
    return result

print(fractional_knapsack(items, 2))


from itertools import permutations
import math

def primeNum(num):
    if(num==0 or num==1):
        return False
    for i in range(2,int(math.sqrt(num)+1)):
        if(num%i==0):
            return False
    return True

def solution(numbers):
    NumList=[]
    numbersList=list(numbers)
    for i in range(1,len(numbersList)+1):
        SortNum=list(set(permutations(numbersList,i)))
        for j in range(len(SortNum)):
            tmp=int("".join(SortNum[j]))
            if(primeNum(tmp)==True):
                NumList.append(tmp)

    NumList=list(set(NumList))
    return len(NumList)


import matplotlib.pyplot as pyplot
import seaborn as S
import pandas as P
import numpy as N

def create_df_from_result(r):
    d = P.DataFrame(N.array(r).reshape(-1, 6),
                    columns=['iterations', 'susc', 'latent',
                             'infect', 'asympt', 'recov'])
    d['pop'] = d['susc'] \
        + d['latent'] + d['infect'] \
        + d['asympt'] + d['recov']
    return d

def plot_history(r):
    df = create_df_from_result(r)
    S.lineplot(x='iterations', y='value', hue='variable',
           data=df.melt(id_vars='iterations'))


from keras.initializers import RandomNormal
from keras.layers import Dense, Dropout, Multiply, Add, Concatenate
from keras.models import Model
from Layers import GradientReversal

#
# defines the blocks for the models.
# It is important to always return a descriptor of the OUTPUT shape
# of the model, such that it can be used to define the INPUT to a subsequent
# block consistently
#

def common_features(Inputs, dropoutrate=0.03):
    X = Inputs
    X = Dense(30, activation='relu', name='common_dense_0')(X)
    X = Dropout(dropoutrate)(X)
    X = Dense(20, activation='relu')(X)
    X = Dropout(dropoutrate)(X)
    X = Dense(20, activation='relu')(X)
    X = Dropout(dropoutrate)(X)
    X = Dense(15, activation='relu')(X)
    X = Dropout(dropoutrate)(X)
    return Model(inputs=Inputs, outputs=X, name='common_features')

def datamc_discriminator(XInputs, rev_grad=10, dropoutrate=0.03):
    Ad = GradientReversal(hp_lambda=rev_grad, name='Ad_gradrev')(XInputs)
    Ad = Dense(20, activation='relu')(Ad)
    Ad = Dropout(dropoutrate)(Ad)
    Ad = Dense(15, activation='relu')(Ad)
    Ad = Dropout(dropoutrate)(Ad)
    Ad = Dense(15, activation='relu')(Ad)
    Ad = Dropout(dropoutrate)(Ad)
    Ad = Dense(10, activation='relu')(Ad)
    Ad = Dropout(dropoutrate)(Ad)
    Ad = Dense(1, activation='sigmoid', name='Add')(Ad)
    # just for compatibility for now
    Ad1 = Dense(
        1, activation='linear', use_bias=False, trainable=False,
        name='Add1')(Ad)
    return Model(inputs=XInputs, outputs=[Ad, Ad1], name="datamc_discriminator")

def btag_discriminator(XInputs, dropoutrate=0.03):
    X = XInputs
    X = Dense(15, activation='relu')(X)
    X = Dropout(dropoutrate)(X)
    X = Dense(15, activation='relu')(X)
    X = Dropout(dropoutrate)(X)
    X = Dense(1, activation='sigmoid', name='mc')(X)
    X1 = Dense(
        1, activation='linear', use_bias=False, trainable=False,
        kernel_initializer='Ones', name='data')(X)
    return Model(inputs=XInputs, outputs=[X, X1], name="btag_discriminator")

def mc_correction(XInputsList, nodes, layers=1, dropoutrate=0.03):

    # the output shape of the correction should be the same as the input
    outshape = XInputsList[0].get_shape().as_list()[1]

    X = XInputsList[0]
    isMC = XInputsList[1]
    noise = XInputsList[2]
    isBs = XInputsList[3]

    X = Concatenate()([X, noise, isBs])

    for i in range(layers):
        X = Dense(nodes, activation='relu')(X)
        X = Dropout(dropoutrate)(X)

    X = Dense(outshape, activation='relu',
              kernel_initializer=RandomNormal(mean=0.0, stddev=0.05))(X)
    X = Dropout(dropoutrate)(X)
    X = Multiply()([X, isMC])
    X = Add()([XInputsList[0], X])
    return Model(inputs=XInputsList, outputs=X, name="mc_correction")


# External imports
import os
import json
import pandas as pd

# Project level imports
import transcription
import config

# Get all files from a directory and subdirectories, or all files of a specified type (eg: ".wav")
# returns a list of file paths
# def getAllFiles(rootSearchPath, specificExt):
#     filePaths = []
#     # Search dirs and subdirs
#     for root, dirs, files in os.walk(rootSearchPath):
#         for file in files:
#             if specificExt == "":
#                 filePaths.append(os.path.join(root, file))
#             elif file.endswith(specificExt):
#                 filePaths.append(os.path.join(root, file))
#
#     print("Found", len(filePaths), "files in", rootSearchPath)
#     return filePaths

# Get the _KEYS.json file containing the identifier structure
def getKeyIdentifiers(path, datasourceName):
    # Get the key value pairs from the file to begin labelling
    try:
        with open(os.path.join(path, datasourceName + "_KEYS.json"), "r") as keyFile:
            try:
                return json.load(keyFile)
            except json.JSONDecodeError as e:
                print("ERROR - Please ensure the *_KEYS.json file is structured correctly.")
                print(e)
                return ""
    except FileNotFoundError as e:
        print("ERROR - Please ensure the *_KEYS.json file exists.")
        print(e)
        return ""

# Utilising the identifer-value pairs label the files accordingly
def labelAllAudioFiles(identifierDict, rootSearchPath, specificExt):
    # Identify the delimiter to use on the filenames
    delimiter = ""
    if "delimiter" in identifierDict.keys():
        delimiter = identifierDict.pop("delimiter")

    # Identify if statements are given, else use transcription
    hasStatements = False
    if "statements" in identifierDict.keys():
        if identifierDict["statements"] != "":
            hasStatements = True
        else:
            print("Warning - No statements given, using transcription. This may take some time.")

    # Store the file info as a dict, path as key
    result = {}

    # Search dirs and subdirs
    for root, dirs, files in os.walk(rootSearchPath):
        for file in files:

            # Convert the filename, into it's identifer components
            filenameComponents = os.path.splitext(file)[0]
            if delimiter != "":
                filenameComponents = filenameComponents.split(delimiter)

            if specificExt == "" or file.endswith(specificExt):

                # For each of the file identifier categories (emotion, gender, modality, etc)
                fileInfo = dict.fromkeys(identifierDict.keys())
                for k in identifierDict.keys():
                    # When no statements are given transcribe
                    if k == "statements" and not hasStatements:
                        print("Transcribing Speech From File:", file)
                        fileInfo[k] = transcription.transcribe(os.path.join(root, file))
                    else:
                        possibleIdentifiers = identifierDict[k]["keyValue"].keys()
                        identifierIndex = identifierDict[k]["index"]
                        identifierSize = identifierDict[k]["size"]
                        # Compare the actual file identifier with the values as defined in *_KEYS.json
                        fileIdValue = filenameComponents[identifierIndex:(identifierIndex+identifierSize)]
                        if fileIdValue in possibleIdentifiers:
                            fileInfo[k] = identifierDict[k]["keyValue"][fileIdValue]
                        else:
                            print("WARNING - Unable to determine filename identifier (", fileIdValue, ") for file:", file)

                # Store the file path, and the file info dict
                result[os.path.join(root, file)] = fileInfo

    return result

# Utilises a datasource name to identify and file extension and label each data file using keys from an external file
# returns a pandas dataframe of file paths and their corresponding labels or ""
def identifyData(dataName, dataType, fileExt):
    # Store the basepath of the datasource in question
    basepath = os.path.join(config.cfg["datasource_path"], dataName)

    # Display a notice to the user
    print("Starting data identification process\nType:", dataType, "\nLocation:", basepath,"\n")

    # Identify the type of data (Audio - Multiple Files, or Text - Single File)
    if dataType != "AUDIO" and dataType != "TEXT":
        print("ERROR - Please ensure the type is either 'AUDIO' or 'TEXT'")
        exit(-1)

    # Process the audio files - labelling
    if dataType == "AUDIO":
        # Get the identifiers dict
        identifierDict = getKeyIdentifiers(basepath, dataName)
        # Get the files
        dataFiles = labelAllAudioFiles(identifierDict, os.path.join(basepath, dataName + "_DATA"), fileExt)
        # If no data files were found return an empty string
        if len(dataFiles) == 0:
            print("ERROR - No files were returned from the labelling process")
            return ""
        # Use the filename, and key-value identifiers to label
        else:
            print(len(dataFiles), "files were returned from the labelling process")
            return pd.DataFrame.from_dict(dataFiles, orient='index')

    # Load with pandas or alternative and we may still want to use the _KEYS file just adjusted for dataframes
    else:
        try:
            if fileExt.lower() == '.csv':
                return pd.read_csv(os.path.join(basepath, dataName + "_DATA" + fileExt))
            elif fileExt.lower() == '.xlsx':
                return pd.read_excel(os.path.join(basepath, dataName + "_DATA" + fileExt))
            else:
                print("Error - Unsupported file extension ("+fileExt+")\n")
        except FileNotFoundError as e:
            print("Error - No file was found\n", e)

# print(identifyData("RAVDESS", "AUDIO", ".wav"))


#5. Умножить два бинарных числа в формате строк

def mult(a, b):
    na, nb = len(a), len(b)
    res = [False] * (na+nb)
    b = [True if d == '1' else False for d in b[::-1]]
    a = [True if d == '1' else False for d in a[::-1]]

    for i in range(nb):
        if b[i]:
            t = False
            for j in range(na):
                res[i+j], t = res[i+j]^a[j]^t, (res[i+j]+a[j]+t) > 1
            res[i+j+1] = t
    tmp = ['1' if d else '0' for d in res[::-1]]
    return ''.join(tmp).lstrip('0')

x1 = '111'
x2 = '101'

print(mult(x1, x2))
print(int(mult(x1, x2),2))


from django.contrib.auth import get_user_model
from django.db import models

User = get_user_model()

class Post(models.Model):
    text = models.TextField(
        'Текст поста',
        help_text='Введите текст поста'
    )
    pub_date = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='posts'
    )
    group = models.ForeignKey(
        'Group',
        related_name='posts',
        blank=True,
        null=True,
        on_delete=models.SET_NULL,
        help_text='Выберете группу'
    )
    image = models.ImageField(
        'Картинка',
        upload_to='posts/',
        blank=True
    )

    class Meta:
        ordering = ['-pub_date']

    def __str__(self):
        return self.text[:15]

class Group(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(unique=True)
    description = models.TextField(
        null=True
    )

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(
        Post,
        related_name='comments',
        on_delete=models.CASCADE
    )
    author = models.ForeignKey(
        User,
        related_name='comments',
        on_delete=models.CASCADE
    )
    text = models.TextField(
        verbose_name='Текст комментария',
        help_text='Введите текст комментария'
    )
    created = models.DateTimeField(
        auto_now_add=True,
        verbose_name='Дата комментария'
    )

class Follow(models.Model):
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='follower'
    )
    author = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='following'
    )


# Polymorpism dengan fungsi

print(len('Polymorpism')) # Output 12
print(len([1,2,3,4])) # Output 4

# Using Class
class jerman:
    def ibukota(self):
        print('Berlin adalah ibukota negara Jerman')

class jepang:
    def ibukota(self):
        print('Tokyo adalah ibukota neraga Jepang')

negara1 = jerman()
negara2 = jepang()

for country in (negara1, negara2):
    country.ibukota()


# coding=utf-8
#-------------------------------------------------------------------------------

#Author: Alexandre Manhaes Savio <alexsavio@gmail.com>
#Grupo de Inteligencia Computational <www.ehu.es/ccwintco>
#Universidad del Pais Vasco UPV/EHU
#
#2013, Alexandre Manhaes Savio
#Use this at your own risk!
#-------------------------------------------------------------------------------
import os

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

from .math import makespread

#-------------------------------------------------------------------------------------
# Matplotlib-based options
#-------------------------------------------------------------------------------
def show_many_slices(vol, vol2=None, volaxis=1, n_slices=[8, 8], slices_idx=None,
                     vol1_colormap=None, vol1_transp_val=None,
                     vol2_colormap=None, vol2_transp_val=0,
                     interpolation='nearest', figtitle=None, facecolor='', show_colorbar=True):
    """
    @param vol: numpy 3D array
    @param vol2: numpy 3D array
    @param volaxis: int
    @param n_slices: list of int
    @param slices_idx: list of int
    @param vol1_colormap: matplotlib colormap
    @param vol1_transp_val: vol1.dtype scalar
    Volume1 transparent value

    @param vol2_colormap: matplotlib colormap
    @param vol2_transp_val: vol2.dtype scalar
    Volume2 transparent value

    @param interpolation: string
    @param figtitle: string
    @param facecolor: string
    @param show_colorbar: bool

    @return: matplotlib figure
    """

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    from mpl_toolkits.axes_grid1 import ImageGrid

    class ImageObserver:
        'update image in response to changes in clim or cmap on another image'
        def __init__(self, follower):
            self.follower = follower
        def __call__(self, leader):
            self.follower.set_cmap(leader.get_cmap())
            self.follower.set_clim(leader.get_clim())

    if isinstance(vol2, np.ndarray):
        assert vol.shape == vol2.shape, 'vol do not have the same shape as vol2'
        if vol2_colormap is None:
            vol2_colormap = plt.cm.jet

    if vol1_colormap is None:
        vol1_colormap = plt.cm.gray

    size   = vol.shape[volaxis]
    n_rows = len(n_slices)
    n_cols = max(n_slices)

    if not slices_idx:
        slice_idx = makespread(list(range(size)), np.sum(n_slices))

    fig  = plt.figure(figtitle, frameon=False)

    if facecolor:
        fig.set_facecolor(facecolor)

    barargs = {}
    if show_colorbar:
        barargs = dict(cbar_location="right",
                       cbar_mode='single',
                       cbar_size='10%',
                       cbar_pad=0.05)

    grid = ImageGrid(fig, 111,
                     nrows_ncols=(n_rows, n_cols),
                     axes_pad=0,
                     direction='column',
                     **barargs)

    axes   = []
    images = []
    vmin   =  1e40
    vmax   = -1e40

    for g in grid:
        g.axis('off')

    c = 1
    for i in slice_idx[:-2]:
        g = grid[c-1]

        img = vol.take([i], volaxis).squeeze()
        if vol1_transp_val is not None:
            img = np.ma.masked_where(img == vol1_transp_val, img)
        g.imshow(np.rot90(img), cmap=vol1_colormap, interpolation=interpolation)

        if isinstance(vol2, np.ndarray):
            img2 = vol2.take([i], volaxis).squeeze()
            img2 = np.ma.masked_where(img2 == vol2_transp_val, img2)
            images.append(g.imshow(np.rot90(img2), cmap=vol2_colormap, interpolation=interpolation))
            dd = np.ravel(img2)
            vmin = min(vmin, np.amin(dd))
            vmax = max(vmax, np.amax(dd))

        #gpos  = g.get_position()
        #gaxis = g.get_axis()
        axes.append(g)
        textx = img.shape[0]/2
        texty = 4
        g.text(textx, texty, str(i), horizontalalignment='center',
               fontsize=12, fontname='Arial', color = '#0055ff')

        c += 1

    if show_colorbar:
        norm = colors.Normalize(vmin=vmin, vmax=vmax)
        for i, im in enumerate(images):
            im.set_norm(norm)
            if i > 0:
                images[0].callbacksSM.connect('changed', ImageObserver(im))

        axes[-1].cax.colorbar(images[-1])

    return fig

def create_imglist_html(output_dir, img_files, filename='index.html'):
    """
    :param img_files: list of strings

    :return:
    """
    #import markdown
    #md_indexf = os.path.join(output_dir, 'index.markdown')
    html_indexf = os.path.join(output_dir, filename)

    with open(html_indexf, 'w') as f:
        for imgf in img_files:
                #line = '[![' + imgf + '](' + imgf + ')' + imgf + '](' + imgf + ')'
                #line = '[' + imgf + '](' + imgf + ')'
                line = '
' + imgf + '
'
                f.write(line + '\n')

    #markdown.markdownFromFile(md_indexf, html_indexf, encoding="utf-8")

def show_connectivity_matrix(image, cmap=None):
    """
    @param image: 2D ndarray
    @param cmap: colormap
    """
    import skimage.io as skio
    if cmap is None:
        cmap = cm.jet

    skio.imshow(image, cmap=cmap)

def autocrop_img(image, color=0):
    """
    Crops the borders of the given color of an image.

    @param image: ndarray
    @param color: int
    @return:
    ndarray
    """
    if len(image.shape) == 3:
        img = image[..., 3] if image.shape[2] == 4 else image[..., 0]

    mask = (img != color).astype(int)

    left, right, top, bottom = borders(mask, 0)

    return image[top:bottom, left:right, :]

def imshow(image, **kwargs):
    import matplotlib.pylab as plt
    fig = plt.figure(figsize=(5, 4))
    plt.imshow(image, **kwargs)
    plt.axis('off')
    return fig

def borders(im, color):
    """
    @param im:
    @param color:
    @return:
    """
    #left, right, top, bottom = -1,-1,-1,-1

    non_color_pix = np.where(im != color)
    top = non_color_pix[0].min()
    bottom = non_color_pix[0].max()
    left = non_color_pix[1].min()
    right = non_color_pix[1].max()

    return left, right, top, bottom

def slicesdir_paired_overlays(output_dir, file_list1, file_list2, dpi=150, **kwargs):
    """
    @param output_dir:
    @param file_list1: list of strings
    Paths to the background image, can be either 3D or 4D images.
    If they are 4D images, will pick one of the center.

    @param file_list2: list of strings
    Paths to the overlay images, must be 3D images.

    @param kwargs: arguments to show_many_slices
    See macuto.render.show_many_slices docstring.

    @return:
    """
    assert(len(file_list1) > 0)
    assert(len(file_list1) == len(file_list2))

    import os
    from .nifti.read import get_nii_data
    from .files.names import remove_ext, get_temp_file
    #import markdown

    import matplotlib.pyplot as plt
    import skimage.io as skio

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    img_files = []

    #CREATE separate images of each file_list2 file
    # on the corresponding file_list1 file
    for idx in list(range(len(file_list1))):
        f1_vol = get_nii_data(file_list1[idx])
        f2_vol = get_nii_data(file_list2[idx])

        if len(f1_vol.shape) > 3:
            f1_vol = f1_vol[..., int(np.floor(f1_vol.shape[3]/2))]

        fig = show_many_slices(f1_vol, f2_vol, **kwargs)

        tmpf = get_temp_file(suffix='.png').name

        fig.savefig(tmpf, transparent=True, dpi=dpi)

        img = autocrop_img(skio.imread(tmpf))

        png_fname = remove_ext(file_list1[idx])
        png_fname = os.path.relpath(png_fname).replace('.', '').replace('/', '_').replace('__', '') + '.png'

        png_path = os.path.join(output_dir, png_fname)
        skio.imsave(png_path, img)

        plt.close(fig)

        img_files.append(os.path.basename(png_path))

    #Create the index.html file with all images
    create_imglist_html(output_dir, img_files)

    return img_files

def slicesdir_oneset(output_dir, file_list1, dpi=150, **kwargs):
    """
    Creates a folder with a html file and png images of slices
    of each of nifti file in file_list1.

    @param output_dir: string
    Path to the output folder

    @param file_list1: list of strings
    Paths to the background image, can be either 3D or 4D images.
    If they are 4D images, will pick one of the center.

    @param file_list2: list of strings
    Paths to the overlay images, must be 3D images.

    @param kwargs: arguments to show_many_slices
    See macuto.render.show_many_slices docstring.

    @return:
    """
    assert(len(file_list1) > 0)

    import os
    from .nifti.read import get_nii_data
    from .files.names import remove_ext, get_temp_file
    #import markdown

    import matplotlib.pyplot as plt
    import skimage.io as skio

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    img_files = []

    show_colorbar = kwargs.pop('show_colorbar', False)

    #CREATE separate images of each file_list2 file
    # on the corresponding file_list1 file
    for idx in list(range(len(file_list1))):
        f1_vol = get_nii_data(file_list1[idx])

        if len(f1_vol.shape) > 3:
            f1_vol = f1_vol[..., int(np.floor(f1_vol.shape[3]/2))]

        fig = show_many_slices(f1_vol, show_colorbar=show_colorbar, **kwargs)

        tmpf = get_temp_file(suffix='.png').name

        fig.savefig(tmpf, transparent=True, dpi=dpi)

        img = autocrop_img(skio.imread(tmpf))

        png_fname = remove_ext(file_list1[idx])
        png_fname = os.path.relpath(png_fname).replace('.', '').replace('/', '_').replace('__', '') + '.png'

        png_path = os.path.join(output_dir, png_fname)
        skio.imsave(png_path, img)

        plt.close(fig)

        img_files.append(os.path.basename(png_path))

    #Create the index.html file with all images
    create_imglist_html(output_dir, img_files)

    return img_files

def show_3slices(vol, vol2=None, x=None, y=None, z=None, fig=None,
                 vol2_colormap=None, vol2_transp_val=0, interpolation='nearest'):
    """
    @param vol: numpy 3D array
    @param vol2: numpy 3D array
    @param x: int
    @param y: int
    @param z: int
    @param fig: matplotlib Figure
    @param vol2_colormap: matplotlib colormap
    @param vol2_transp_val: scalar
    Volume2 transparent value

    @param interpolation: string

    @return: matplotlib figure
    """

    assert vol.shape == vol2.shape, 'vol do not have the same shape as vol2'

    import numpy as np
    import matplotlib.pyplot as plt

    from matplotlib.widgets import Slider

    if not x:
        x = np.floor(vol.shape[0]/2)
    if not y:
        y = np.floor(vol.shape[1]/2)
    if not z:
        z = np.floor(vol.shape[2]/2)

    if not fig:
        fig = plt.figure()
    else:
        fig = plt.figure(fig.number)

    try:
        if not np.ma.is_masked(vol2):
            vol2 = np.ma.masked_equal(vol2, vol2_transp_val)
    except:
        pass

    if vol2_colormap is None:
        vol2_colormap = plt.cm.hot

    plt.subplot (2, 2, 1)
    plt.axis('off')
    plt.imshow(np.rot90(vol[x, ...]), cmap=plt.cm.gray, interpolation=interpolation)
    try:
        plt.imshow(np.rot90(vol2[x, ...]), cmap=vol2_colormap, interpolation=interpolation)
    except:
        pass
    #plt.imshow(vol[x,...], cmap=plt.cm.gray)
    plt.title ('X:' + str(int(x)))

    plt.subplot (2, 2, 2)
    plt.axis('off')
    plt.imshow(np.rot90(vol[:, y, :]), cmap=plt.cm.gray, interpolation=interpolation)
    try:
        plt.imshow(np.rot90(vol2[:, y, :]), cmap=vol2_colormap, interpolation=interpolation)
    except:
        pass

    plt.title ('Y:' + str(int(y)))

    plt.subplot (2, 2, 3)
    plt.axis ('off')
    plt.imshow(np.rot90(vol[..., z]), cmap=plt.cm.gray, interpolation=interpolation)
    try:
        plt.imshow(np.rot90(vol2[..., z]), cmap=vol2_colormap, interpolation=interpolation)
    except:
        pass
    plt.title ('Z:' + str(int(z)))

    plt.subplot (2, 2, 4)

    plt.axis('off')
    axcolor = 'lightgoldenrodyellow'
    xval = plt.axes([0.60, 0.20, 0.20, 0.03], axisbg=axcolor)
    yval = plt.axes([0.60, 0.15, 0.20, 0.03], axisbg=axcolor)
    zval = plt.axes([0.60, 0.10, 0.20, 0.03], axisbg=axcolor)

    xsli = Slider(xval, 'X', 0, vol.shape[0]-1, valinit=x, valfmt='%i')
    ysli = Slider(yval, 'Y', 0, vol.shape[1]-1, valinit=y, valfmt='%i')
    zsli = Slider(zval, 'Z', 0, vol.shape[2]-1, valinit=z, valfmt='%i')

    def update(val):
        x = np.around(xsli.val)
        y = np.around(ysli.val)
        z = np.around(zsli.val)
        #debug_here()
        show_3slices(vol, vol2, x, y, z, fig)
        #fig.set_data()

    xsli.on_changed(update)
    ysli.on_changed(update)
    zsli.on_changed(update)

    plt.show()

    return fig

def slicesdir_connectivity_matrices(output_dir, cmat_list, dpi=150, lower_triangle=True, **kwargs):
    """
    @param output_dir:
    @param file_list1: list of ndarrays
    List of connectivity matrices

    @param dpi: int
    Dots per inch resolution of the plot images

    @param lower_triangle: bool
    If true, will plot a lower triangle of the matrix,
    the full matrix otherwise.

    @param kwargs: arguments to show_many_slices
    See draw_square_matrix_channels named arguments.
    """
    import os
    import skimage.io as skio
    import matplotlib.pyplot as plt
    from nitime.viz import drawmatrix_channels

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    img_files = []

    #cmap = kwargs.pop('cmap', plt.cm.rainbow)
    channel_names = kwargs.pop('channel_names', None)
    color_anchor = kwargs.pop('color_anchor', 0)
    size = kwargs.pop('size', [10., 10.])

    #CREATE separate images of each file_list2 file
    # on the corresponding file_list1 file
    for idx in list(range(len(cmat_list))):
        cmat = cmat_list[idx]

        png_fname = 'connectivity_matrix' + str(idx) + '.png'
        png_path = os.path.join(output_dir, png_fname)

        if lower_triangle:
            fig = drawmatrix_channels(cmat, channel_names, size=size,
                                      color_anchor=color_anchor, **kwargs)
        else:
            fig = draw_square_matrix_channels(cmat, channel_names, size=size,
                                              color_anchor=color_anchor, **kwargs)

        #fig  = plt.matshow(cmat, cmap=cmap)
        fig.savefig(png_path, transparent=True, dpi=dpi)

        img = autocrop_img(skio.imread(png_path))
        skio.imsave(png_path, img)

        img_files.append(os.path.basename(png_path))

        plt.close()

    #Create the index.html file with all images
    create_imglist_html(output_dir, img_files)

    return img_files

def draw_square_matrix_channels(in_m, channel_names=None, fig=None, x_tick_rot=None,
                                size=None, cmap=plt.cm.RdBu_r, colorbar=True,
                                color_anchor=None, title=None):
    """
    Copied from nitime.viz import drawmatrix_channels

    Creates a full-matrix or lower-triangle of the matrix of an nxn set of values.
    This is the typical format to show a symmetrical bivariate quantity (such as
    correlation or coherence between two different ROIs).

    @param cmat: nxn array
    with values of relationships between two sets of rois or channels

    @param channel_names (optional): list of strings
    with the labels to be applied to the channels in the input.
    Defaults to '0','1','2', etc.

    @param fig (optional): a matplotlib figure

    @param cmap (optional): a matplotlib colormap
    to be used for displaying the values of the connections on the graph

    @param title (optional): string
    to title the figure (can be like '$\alpha$')

    @param color_anchor (optional): int
    Determine the mapping from values to colormap
        if None, min and max of colormap correspond to min and max of in_m
        if 0, min and max of colormap correspond to max of abs(in_m)
        if (a,b), min and max of colormap correspond to (a,b)

    @return: fig
    a figure object
    """
    import matplotlib.ticker as ticker
    from mpl_toolkits.axes_grid import make_axes_locatable

    N = in_m.shape[0]
    ind = np.arange(N)  # the evenly spaced plot indices

    def channel_formatter(x, pos=None):
        thisind = np.clip(int(x), 0, N - 1)
        return channel_names[thisind]

    if fig is None:
        fig = plt.figure()

    if size is not None:
        fig.set_figwidth(size[0])
        fig.set_figheight(size[1])

    w = fig.get_figwidth()
    h = fig.get_figheight()

    ax_im = fig.add_subplot(1, 1, 1)

    #If you want to draw the colorbar:
    if colorbar:
        divider = make_axes_locatable(ax_im)
        ax_cb = divider.new_vertical(size="10%", pad=0.1, pack_start=True)
        fig.add_axes(ax_cb)

    #Make a copy of the input, so that you don't make changes to the original
    #data provided
    m = in_m.copy()

    #Extract the minimum and maximum values for scaling of the
    #colormap/colorbar:
    max_val = np.nanmax(m)
    min_val = np.nanmin(m)

    if color_anchor is None:
        color_min = min_val
        color_max = max_val
    elif color_anchor == 0:
        bound = max(abs(max_val), abs(min_val))
        color_min = -bound
        color_max = bound
    else:
        color_min = color_anchor[0]
        color_max = color_anchor[1]

    #The call to imshow produces the matrix plot:
    im = ax_im.imshow(m, origin='upper', interpolation='nearest',
                      vmin=color_min, vmax=color_max, cmap=cmap)

    #Formatting:
    ax = ax_im
    ax.grid(True)
    #Label each of the cells with the row and the column:
    if channel_names is not None:
        if x_tick_rot is None:
            if str(channel_names[0]).isdigit():
                x_tick_rot = 0
            else:
                x_tick_rot = 45

        for i in xrange(0, m.shape[0]):
            # if i < (m.shape[0] - 1):
            #     ax.text(i, -1, channel_names[i],
            #             rotation=x_tick_rot,
            #             horizontalalignment='right',
            #             verticalalignment='bottom',
            #             fontsize=6)
            if i > 0:
                ax.text(-1, i - 1, channel_names[i],
                        horizontalalignment='right',
                        fontsize=6,
                        linespacing=4.)

        ax.set_axis_off()
        ax.set_xticks(np.arange(N))
        ax.set_xticklabels(channel_names)

        ax.xaxis.set_major_formatter(ticker.FuncFormatter(channel_formatter))
        fig.autofmt_xdate(rotation=x_tick_rot)

        ax.set_yticks(np.arange(N))
        ax.set_yticklabels(channel_names)
        #ax.set_ybound([-0.5, N - 0.5])
        #ax.set_xbound([-0.5, N - 1.5])

    #Make the tick-marks invisible:
    for line in ax.xaxis.get_ticklines():
        line.set_markeredgewidth(0)

    for line in ax.yaxis.get_ticklines():
        line.set_markeredgewidth(0)

    ax.set_axis_off()

    if title is not None:
        ax.set_title(title)

    #The following produces the colorbar and sets the ticks
    if colorbar:
        #Set the ticks - if 0 is in the interval of values, set that, as well
        #as the maximal and minimal values:
        if min_val < 0:
            ticks = [color_min, min_val, 0, max_val, color_max]
        #Otherwise - only set the minimal and maximal value:
        else:
            ticks = [color_min, min_val, max_val, color_max]

        #This makes the colorbar:
        cb = fig.colorbar(im, cax=ax_cb, orientation='horizontal',
                          cmap=cmap,
                          norm=im.norm,
                          boundaries=np.linspace(color_min, color_max, 256),
                          ticks=ticks,
                          format='%.2f')

    # Set the current figure active axis to be the top-one, which is the one
    # most likely to be operated on by users later on
    fig.sca(ax)

    return fig

#-------------------------------------------------------------------------------------
# Mayavi2 options
#-------------------------------------------------------------------------------------
def show_cutplanes (vol, first_idx=10, second_idx=10,
                    first_plane='x_axes', second_plane='y_axes'):
    """
    @param vol: numpy 3d array
    @param first_idx: int
    @param second_idx: int
    @param first_plane: string
    @param second_plane: string
    """
    from mayavi import mlab

    mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(vol),
                            plane_orientation=first_plane,
                            slice_index=first_idx,
                            colormap='gray')

    mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(vol),
                            plane_orientation=second_plane,
                            slice_index=second_idx,
                            colormap='gray')

    mlab.outline()

def show_dynplane(vol):
    """
    @param vol: numpy 3d array
    """
    from mayavi import mlab
    src = mlab.pipeline.scalar_field(vol)
    mlab.pipeline.iso_surface(src, contours=[vol.min()+0.1*vol.ptp(), ], opacity=0.1)
    #mlab.pipeline.iso_surface(src, contours=[vol.max()-0.1*vol.ptp(), ],)
    mlab.pipeline.image_plane_widget(src,
                            plane_orientation='z_axes',
                            slice_index=10,
                            colormap='gray')

def show_contour(vol):
    """
    @param vol: numpy 3d array
    """
    from mayavi import mlab
    mlab.contour3d(vol, colormap='gray')

def show_render(vol, vmin=0, vmax=0.8):
    """
    @param vol: numpy 3d array
    @param vmin: float
    @param vmax: float
    """
    from mayavi import mlab
    mlab.pipeline.volume(mlab.pipeline.scalar_field(vol), vmin=vmin, vmax=vmax, colormap='gray')


#! /usr/bin/env python

import re
import sys

class tbg (object):
	def __init__(self, infilename): #define variables and class function
		self.infilename = infilename
		self.module_name = ""
		self.clock_name = 'clk'
		self.reset_name = 'rst'
		self.outputfile_name = None
		self.open_inputfile()
		self.parser()
		self.open_outputfile()
		self.inputfile=None
		self.outfile  = sys.stdout
		self.textinfile = ""

	def open_inputfile (self):
		try:
			self.inputfile = open(self.infilename, 'r')
			self.textinfile= self.inputfile.read()
		except:
			print ("input file cannot be opened")
			sys.exit(1)

	def open_outputfile (self):
		outputfile_name = "%s_tb.v" % self.module_name
		self.outfile = open (self.outputfile_name, 'w')


import cv2
import mediapipe as mp
import time

# create our video object
cap = cv2.VideoCapture(0)

mpHands = mp.solutions.hands
hands = mpHands.Hands() #tulis didalam () sebuah parameter, pencet ctrl dikeyboard dan klik di Hands
# kita gaperlu tulis apa2 didalam () krn didalam Hands sudah ada fungsinya sendiri
mpDraw = mp.solutions.drawing_utils

#ngitung fps
pTime = 0 #previous time
cTime = 0 #current time

while True:
    success, img = cap.read()
    imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    results = hands.process(imgRGB)
    #print(results.multi_hand_landmarks)  #fungsi disamping utk cek apakah sensor tangan bekerja di cam/tidak

    #single hand
    if results.multi_hand_landmarks:
        for handLms in results.multi_hand_landmarks:
            #get the info of cx and cy information within each of these hands
            for id, lm in enumerate(handLms.landmark):
                #print(id,lm)
                h, w, c = img.shape
                cx, cy = int(lm.x*w), int(lm.y*h)
                print(id, cx, cy)
                #jika kita ingin mendapat info dri index jari tertentu, bisa coding sperti dibawah
                if id==4:
                    cv2.circle(img, (cx, cy), 15, (255,0,255), cv2.FILLED)

            mpDraw.draw_landmarks(img, handLms, mpHands.HAND_CONNECTIONS)

    cTime = time.time() #akan give us the current time
    fps = 1/(cTime-pTime)
    pTime = cTime

    #display it on the screen jadi kita bisa lihat
    cv2.putText(img,str(int(fps)),(10,70), cv2.FONT_HERSHEY_PLAIN, 3,(255,0,255), 3)

    cv2.imshow("Image", img)
    cv2.waitKey(1)


geb = [1, 3, 7, 12]
diff = [2, 4, 5]

for g in range(4, 20001):
    for d in range(diff[g - 2] + 1, 2000000):
        if d not in geb and d not in diff:
            diff.append(d)
            geb.append(geb[-1] + d)
            break
    if len(geb) > 99:
        break

# print(geb)
print([t - s for s, t in zip(geb, geb[1:])])
print(geb[99])

print()

# Is there a general formula for geb? an asymptotic formula?
alpha = ((5 ** 0.5) - 1) / 2
# print([(n+1)*(n+2)//2 + n//2  - geb[n] for n in range(0,100)])
# print([n + int(n**0.5) + int((n*2)**0.25) + 4  - diff[n] for n in range(0,1000)])
# print([int((n + int((2 * n) ** 0.5 / 2) + 2 - diff[n]) * 100 / ((n-1) ** 0.5)) + 60 for n in range(10, 20000, 200)])
# print([n + int(n ** 0.5) + 10 - diff[n] for n in range(0, 10000, 100)])


import pymysql
def mysql(sql):
    try:
        conn = pymysql.connect(**mysql_info)
    except Exception as e:
        res = '数据库连接失败，请检查链接信息%s '%e
        print(res)
        return  res
    # 在这里可以不写else，因为上面的语句return后直接跳出一场捕获了了
    cur = conn.cursor(cursor=pymysql.cursors.DictCursor)
    try:
        cur.execute(sql)
    except Exception as e:
        res = 'sql语法不符合要求，请检查%s'%e
        print(res)
    else:
        res = cur.fetchall()
    finally:
        cur.close()
        conn.close()
    return res


#!/usr/bin/python
# -*- coding: UTF-8 -*-

from xml.parsers.expat import ParserCreate

class MovieHandler(object):
   def __init__(self):
      self.CurrentData = ""
      self.type = ""
      self.format = ""
      self.year = ""
      self.rating = ""
      self.stars = ""
      self.description = ""

   # 元素开始事件处理
   def startElement(self, tag, attributes):
      self.CurrentData = tag
      if self.CurrentData == "movie":
         print("*****Movie*****")
         title = attributes["title"]
         print("Title:", title)

   # 元素结束事件处理
   def endElement(self, tag):
      if self.CurrentData == "type":
         print("Type:", self.type)
      elif self.CurrentData == "format":
         print("Format:", self.format)
      elif self.CurrentData == "year":
         print("Year:", self.year)
      elif self.CurrentData == "rating":
         print("Rating:", self.rating)
      elif self.CurrentData == "stars":
         print("Stars:", self.stars)
      elif self.CurrentData == "description":
         print("Description:", self.description)
      self.CurrentData = ""

   # 内容事件处理
   def characters(self, content):
      if self.CurrentData == "type":
         self.type = content
      elif self.CurrentData == "format":
         self.format = content
      elif self.CurrentData == "year":
         self.year = content
      elif self.CurrentData == "rating":
         self.rating = content
      elif self.CurrentData == "stars":
         self.stars = content
      elif self.CurrentData == "description":
         self.description = content

xml = r'''<collection shelf="New Arrivals">
<movie title="Enemy Behind">
   <type>War, Thriller</type>
   <format>DVD</format>
   <year>2003</year>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Talk about a US-Japan war</description>
</movie>
<movie title="Transformers">
   <type>Anime, Science Fiction</type>
   <format>DVD</format>
   <year>1989</year>
   <rating>R</rating>
   <stars>8</stars>
   <description>A schientific fiction</description>
</movie>
   <movie title="Trigun">
   <type>Anime, Action</type>
   <format>DVD</format>
   <episodes>4</episodes>
   <rating>PG</rating>
   <stars>10</stars>
   <description>Vash the Stampede!</description>
</movie>
<movie title="Ishtar">
   <type>Comedy</type>
   <format>VHS</format>
   <rating>PG</rating>
   <stars>2</stars>
   <description>Viewable boredom</description>
</movie>
</collection>
'''

handler = MovieHandler()
parser = ParserCreate()
parser.StartElementHandler = handler.startElement
parser.EndElementHandler = handler.endElement
parser.CharacterDataHandler = handler.characters
parser.Parse(xml)
print(handler.description)


import numpy as np

def p7():
    return oddprimes(1000000)[9999]

def oddprimes(num):
    isprimes = np.ones(num//2 + 1, dtype = np.bool)
    isprimes[0] = False
    for index, isprime in enumerate(isprimes):
        if isprime:
            isprimes[2*index*(index+1)::2*index+1] = False
    return 2*np.nonzero(isprimes)[0] + 1


import tkinter as tk
import body as b
import Sim

''' Creates the GUI

def solar_preset() - used to add our solar system into the list of bodies
def solar_preset_plus() - used add our solar system with a black hole into the list of bodies
def earth_sun_preset() - add earth and sun into the list of bodies
def earth_sun_jupter_preset() - add earth, sun, and jupter into the list of bodies
def clear_bodies() - clear out the list of the bodies
def cal_duration() - calculate the total duration of the simulation given the values that the user enters
def show_body_values() - used for testing that the text box values are being taken in correctly
def body_to_string(body) = used to turn the body into a string that will be used to display the information about the body to the user
def add_body() - create a body from the user inputs and place that into the list for holding
def display_list() - used to display to the user all of the bodies that have been added into the simulation
def run_sim() - to run the simualation by calling anum_orbit from Sim.py and inputing all of the list of bodys

'''

root = tk.Tk()
root.title("Orbit Simulation")

#This is a temp holding places for the bodies that are created from the slider
list_of_all_bodies = []

#This is to hold the type of speed the sim will go by
speed_for_sim = tk.StringVar()
speed_for_sim.set("fast")

#This is to hold the type of time step
time_step = tk.IntVar()
time_step.set(60 * 60)

#---------------------
SUN =     b.body(1.989e+30,   0,         0,          0,          0)
MERCURY = b.body(0.33011e24,  57.909e9,  0,          0,          47.36e3)
VENUS = b.body(4.8675e24,    -108.209e9, 0,          0,          35.02e3)
EARTH =   b.body(5.97219e+24, 0,         148e9,      3e4,        0)
MARS = b.body(0.64171e24,     161.166e9, 161.166e9,  17.02e3,    -17.02e3)
JUPITER = b.body(1898.13e24,  0,        -778.57e9,  -13.06e3,    0)
SATURN = b.body(568.34e24,    1013.66e9, -1013.66e9,-6.845e3,   -6.845e3)
URANUS = b.body(86.8e24,      2872.46e9,  0,         0,          6.8e3)
NEPTUNE = b.body(102.413e24,  -3178.49e9, 3178.49e9,  3.839e3,    3.839e3)

XTE_J =   b.body(5.967e30,   -400e9,    -400e9,     1e3,  1e3)

full_local = [SUN,MERCURY,VENUS,EARTH,MARS,JUPITER,SATURN,URANUS,NEPTUNE]
local_plus = [SUN,MERCURY,VENUS,EARTH,MARS,JUPITER,SATURN,URANUS,NEPTUNE,XTE_J]
earth_sun = [SUN,EARTH]
earth_sun_jupter = [SUN, EARTH, JUPITER]

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

#This is used to add our solar system into the list of bodies
def solar_preset():
    error_label.config(text="")
    if len(list_of_all_bodies) == 0:
        list_of_all_bodies.extend(full_local)
        display_list()
    else:
        error_label.config(text="Sorry, can only add any preset once per a simulation. Please clear the list if you want to add a different preset.")

#This is used add our solar system with a black hole into the list of bodies
def solar_preset_plus():
    error_label.config(text="")
    if len(list_of_all_bodies) == 0:
        list_of_all_bodies.extend(local_plus)
        display_list()
    else:
        error_label.config(text="Sorry, can only add any preset once per a simulation. Please clear the list if you want to add a different preset.")

#This is used to add earth_sun into the list of bodies
def earth_sun_preset():
    error_label.config(text="")
    if len(list_of_all_bodies) == 0:
        list_of_all_bodies.extend(earth_sun)
        display_list()
    else:
        error_label.config(text="Sorry, can only add any preset once per a simulation. Please clear the list if you want to add a different preset.")

#This is used add earth_sun_jupter into the list of bodies
def earth_sun_jupter_preset():
    error_label.config(text="")
    if len(list_of_all_bodies) == 0:
        list_of_all_bodies.extend(earth_sun_jupter)
        display_list()
    else:
        error_label.config(text="Sorry, can only add any preset once per a simulation. Please clear the list if you want to add a different preset.")

#Used to clear out the list of the bodies
def clear_bodies():
    error_label.config(text="")
    list_of_all_bodies.clear()
    display_list()

#Used to calculate the total duration of the simulation
def cal_duration():
    error_label.config(text="")
    try:
        years = float(duration.get())
        if years <= 0:
            error_label.config(text="Duration needs to positive")
            return -1
        days = years *365

        # duration is a length of years split into seconds
        dur= days *24 *60 *60
        return dur

    except ValueError:
        error_label.config(text="Please make sure to only input numbers and not to leave any textboxes empty")

#This function is used for testing that the text box values are being taken in correctly
def show_body_values():
    error_label.config(text="")
    for x in range(len(list_of_all_bodies)):
        print ("This is body number: ",x + 1)
        print ("The mass of this body is: ", list_of_all_bodies[x].mass)
        print ("The X of this body is: ", list_of_all_bodies[x].x)
        print ("The Y of this body is: ", list_of_all_bodies[x].y)
        print ("The starting X velocity of this body is: ", list_of_all_bodies[x].x_velo)
        print ("The starting Y velocity of this body is: ", list_of_all_bodies[x].y_velo)

#This is used to turn the body into a string that will be used to display the information about the
#body to the user
def body_to_string(body):
    body_string = ""

    body_string += "The mass of this body is: " + str(body.mass) + "\n"
    body_string += "The X of this body is: " + str(body.x) + "\n"
    body_string += "The Y of this body is: " + str(body.y) + "\n"
    body_string += "The starting X velocity of this body is: " + str(body.x_velo) + "\n"
    body_string += "The starting Y velocity of this body is: " + str(body.y_velo) + "\n"
    body_string += "\n"

    return body_string

#This is using to create a body from the user inputs and place that into the list for holding
def add_body():
    try:
        error_label.config(text="")
        if float(size_of_body.get()) < 1:
            error_label.config(text="Mass needs to be at least 1")
        else:
            temp = b.body(float(size_of_body.get()), float(starting_x_body.get()), float(starting_y_body.get()), float(starting_xv_body.get()), float(starting_yv_body.get()))
            list_of_all_bodies.append(temp)
            display_list()

    except ValueError:
        error_label.config(text="Please make sure to only input numbers and not to leave any textboxes empty")

#This is used to display to the user all of the bodies that have been added into the simulation
def display_list():
    error_label.config(text="")
    temp = ""
    for x in list_of_all_bodies:
        temp += body_to_string(x)

    display_list_label.config(text=temp)

#This is used to run the simualation by calling anum_orbit from Sim.py and inputing all of the list of bodys
#As well as all of the simulation values from the user
def run_sim():
    error_label.config(text="")
    display_list()
    sim_duration = cal_duration()
    if len(list_of_all_bodies) != 0 and sim_duration != -1:
        Sim.anim_orbit(list_of_all_bodies, sim_duration, time_step.get(), speed_for_sim.get())
    elif len(list_of_all_bodies) == 0:
        error_label.config(text = "Must add bodies before running simulation")

#This is the set the mass of the body using a textbox
size_of_body_label = tk.Label(root, text="Mass of the body (Must be 1 or greater)")
size_of_body = tk.Entry(root, width = 20)
size_of_body_label.grid(row=4, column=0)
size_of_body.grid(row=4, column=1)

#This is the set the starting x of the body using a textbox
starting_x_body_label = tk.Label(root, text="Starting X")
starting_x_body = tk.Entry(root, width = 20)
starting_x_body_label.grid(row=5, column=0)
starting_x_body.grid(row=5, column=1)

#This is the set the starting y of the body using a textbox
starting_y_body_label = tk.Label(root, text="Starting Y")
starting_y_body = tk.Entry(root, width = 20)
starting_y_body_label.grid(row=6, column=0)
starting_y_body.grid(row=6, column=1)

#This is the set the starting x velocity for body using a textbox
starting_xv_body_label = tk.Label(root, text="Starting X velocity")
starting_xv_body = tk.Entry(root, width = 20)
starting_xv_body_label.grid(row=7, column=0)
starting_xv_body.grid(row=7, column=1)

#This is the set the starting y velocity for the body using a textbox
starting_yv_body_label = tk.Label(root, text="Starting Y velocity")
starting_yv_body = tk.Entry(root, width = 20)
starting_yv_body_label.grid(row=8, column=0)
starting_yv_body.grid(row=8, column=1)

#This the textbox for the duration in years
duration_label = tk.Label(root, text="Enter the duration of the simulation (1 = one year, 2 = two year, etc...")
duration = tk.Entry(root, width = 20)
duration_label.grid(row=9, column=0)
duration.grid(row=9, column=1)

#add speed of sim radio buttons
speed_of_sim_label = tk.Label(root, text="Please select the speed of the simulation")
tk.Radiobutton(root, text = "normal", variable = speed_for_sim, value = "normal").grid(row=11, column=0)
tk.Radiobutton(root, text = "fast", variable = speed_for_sim, value = "fast").grid(row=11, column=1)
tk.Radiobutton(root, text = "very fast", variable = speed_for_sim, value = "vfast").grid(row=11, column=2)
tk.Radiobutton(root, text = "extremely fast", variable = speed_for_sim, value = "efast").grid(row=11, column=3)
speed_of_sim_label.grid(row=10, column=0)

#This allows the user to select the time step of the simulation
time_step_label = tk.Label(root, text = "Please select the time step")
tk.Radiobutton(root, text = "Hour", variable = time_step, value = 60*60).grid(row=13, column=0)
tk.Radiobutton(root, text = "Day", variable = time_step, value = 60 * 60 * 24).grid(row=13, column=1)
tk.Radiobutton(root, text = "Year", variable = time_step, value = 60 * 60 *24 * 365).grid(row=13, column=2)
time_step_label.grid(row=12, column=0)

#Add preset buttons right here
presets_here_label = tk.Label(root, text="Here are some presets")
presets_here_label.grid(row=14, column=0)

#-------------------------------------------------------------------------------------------------
#This is the present button for our solar system
our_solar_system = tk.Button(root, text="Our solar system preset", command=solar_preset)
our_solar_system.grid(row=15, column=0)

#This is the present button for our solar system with a black hole preset
our_solar_system_black_hole = tk.Button(root, text="Our solar system with a black hole preset", command=solar_preset_plus)
our_solar_system_black_hole.grid(row=15, column=1)

##This is the present button for earth and sun
earth_sun_button = tk.Button(root, text="Earth and Sun preset", command=earth_sun_preset)
earth_sun_button.grid(row=15, column=2)

##This is the present button for earth, sun, and jupter
our_solar_system_black_hole = tk.Button(root, text="Earth, Sun, and Jupter preset", command=earth_sun_jupter_preset)
our_solar_system_black_hole.grid(row=15, column=3)

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

#This is the add button, to add the body to the list
add_body_button = tk.Button(root, text="Add body", command=add_body)
add_body_button.grid(row=16, column=0)

#This is the display bodies button,just used for the testing for now
display_bodies_button = tk.Button(root, text="Display Bodies", command=display_list)
display_bodies_button.grid(row=17, column=0)

#This is the run button
run_sim_button = tk.Button(root, text="Run Simulation", command=run_sim)
run_sim_button.grid(row=18, column=0)

#This is the button to clear the list of bodies
clear_bodies_button = tk.Button(root, text="Clear Bodies", command=clear_bodies)
clear_bodies_button.grid(row=19, column=0)

#This is will display each of the bodies than have been add into the list
display_list_label = tk.Label(root, text="")
display_list_label.grid(row=20, column=0)

#This will be used to show any errors to the user
error_label = tk.Label(root, text="")
error_space = tk.Label(root, text="        ")
error_label.grid(row=1, column=1)
error_space.grid(row=1, column=0)

if __name__ == '__main__':
    root.mainloop()


# 216. Combination Sum III
# Medium

# Larry, https://www.youtube.com/watch?v=qnLeadJaM_Q
class Solution:
    def combinationSum3(self, k: int, n: int) -> List[List[int]]:
        ans = []

        def recurse(first, current, sumLeft, kLeft):
            if sumLeft == 0:
                if kLeft == 0:
                    ans.append(current[:])
                return
            if kLeft == 0:
                return
            if first == 10:
                return

            recurse(first + 1, current, sumLeft, kLeft)
            if sumLeft - first >= 0:
                current.append(first)
                recurse(first + 1, current, sumLeft - first, kLeft - 1)
                current.pop()

        recurse(1, [], n, k)
        return ans
# 05/10/2022 14:58


import os
import pyblish.api

class CollectWorkfileRepresentation(pyblish.api.InstancePlugin):
    """Create a publish representation for the current workfile instance."""

    order = pyblish.api.CollectorOrder
    label = "Workfile representation"
    hosts = ["substancepainter"]
    families = ["workfile"]

    def process(self, instance):

        context = instance.context
        current_file = context.data["currentFile"]

        folder, file = os.path.split(current_file)
        filename, ext = os.path.splitext(file)

        instance.data["representations"] = [{
            "name": ext.lstrip("."),
            "ext": ext.lstrip("."),
            "files": file,
            "stagingDir": folder,
        }]


import os
from glob import glob
from watchdog.observers import Observer
from watchdog.events import FileCreatedEvent, FileModifiedEvent, FileSystemEventHandler
import random

app_dir = os.path.dirname(os.path.realpath(__file__))
media_dir = "./pi/"

# filechages handler
media_files = []

import tkinter
app = tkinter.Tk()
app.geometry(newGeometry="600x600")

tk = tkinter.Frame(app)

from PIL import Image, ImageTk
import math

oldframe = None
def open_url(url):
    global oldframe, tk, app

    win = tkinter.Frame(tkinter.Toplevel(app))

    image=  Image.open(url)
    mw, mh = 800, 600
    w, h  = image.size
    wd = w - mw
    hd  = h - mh
    m = 1
    if wd <= 0 and hd <= 0:
        pass
    elif wd > hd:
        m = mw/ w
    else:
        m = mh / h
    w =  int(m * w)
    h = int(m * h)
    image = image.resize((w, h))
    photo = ImageTk.PhotoImage(image)
    x = tkinter.Label(win, image = photo)
    x.image = photo
    x.pack()

    win.pack()
    oldframe = win

def draw():
    global tk, media_files
    r =  math.ceil(len(media_files) / 6 )
    tk.destroy()
    # tk.pack()
    tk = tkinter.Frame(app)
    for i in range(r):
        for j in range(6):
            def do():
                try:
                    image = Image.open(media_files[i * 6 + j])
                except:
                    return False

                image=  image.resize((100, 100))
                photo = ImageTk.PhotoImage(image)
                x = tkinter.Label(tk, image = photo)
                x.grid(row = i, column = j)
                x.width = 100
                x.height  = 100
                x.image = photo
                path = media_files[i * 6 + j]
                x.bind("<Button-1>",lambda e,url=None:open_url(path))
                # x.pack()
                return True
            if not do():
                break
    tk.pack()

def handleChanges(event):
    global media_files, media_hash
    exts = ['*.png', '*.jpg', '*.jpeg']
    media_files = []
    for ext in exts:
        media_files.extend(glob(media_dir + ext))
    media_files.sort(key = os.path.getmtime)
    media_files.reverse()
    draw()

handleChanges(0)

handler = FileSystemEventHandler()
handler.on_created = handleChanges
handler.on_modified = handleChanges
observer = Observer()
observer.schedule(handler, media_dir)
observer.start()

# tk.pack()
app.mainloop()


import numpy as np
import matplotlib.pyplot as plt
from utilities import load_data, print_features, print_predictions

# you may use these colours to produce the scatter plots
CLASS_1_C = r'#3366ff'
CLASS_2_C = r'#cc3300'
CLASS_3_C = r'#ffc34d'
CLASS_COLOURS = [CLASS_1_C,CLASS_2_C,CLASS_3_C]

train_set, train_labels, test_set, test_labels = load_data()

def calculate_accuracy(gt_labels, pred_labels):
    return np.sum(gt_labels==pred_labels)/float(len(gt_labels))

def feature_extract(feature1,feature2):
    reduced_train = train_set[:,[feature1,feature2]]
    reduced_test  = test_set [:,[feature1,feature2]]
    return reduced_train,reduced_test

def knn(train_set, train_labels, test_set, k, **kwargs):
    # write your code here and make sure you return the predictions at the end of
    # the function

    #I think this is correct. I need to refactor it anyway.
    dist = lambda x, y: np.sqrt(np.sum((x-y)**2))
    k_nearest_points = lambda x: sorted([(dist(x,point[0]),point[1]) for point in zip(train_set,train_labels)], key = lambda x: x[0])
    k_nearest_neighbours = lambda x,k: [m[1] for m in k_nearest_points(x)[:k]]
    classification = lambda x,k: int(max(set(k_nearest_neighbours(x,k)),key=k_nearest_neighbours(x,k).count))
    return [classification(p,k) for p in test_set]

def plot_matrix(matrix, ax=None):
    """
    Displays a given matrix as an image.

    Args:
        - matrix: the matrix to be displayed
        - ax: the matplotlib axis where to overlay the plot.
          If you create the figure with `fig, fig_ax = plt.subplots()` simply pass `ax=fig_ax`.
          If you do not explicitily create a figure, then pass no extra argument.
          In this case the  current axis (i.e. `plt.gca())` will be used
    """
    if ax is None:
        ax = plt.gca()

    # write your code here
    handle = ax.imshow(matrix,cmap=plt.get_cmap('summer'))
    plt.colorbar(handle)
    plt.show()

plt.subplots_adjust(0.125,0.1,0.9,0.9,0.2)
accuracy_mat = np.zeros((13,13))
for i in range(13):
    for j in range(13):
        r_tr, r_te = feature_extract(i,j)
        accuracy_mat[i,j] = calculate_accuracy(knn(r_tr,train_labels,r_te,7),test_labels)

plot_matrix(accuracy_mat)


#!/usr/bin/python3

"""Define the add_item() function"""

import sys
save_to_json = __import__("5-save_to_json_file").save_to_json_file
load_from_json = __import__("6-load_from_json_file").load_from_json_file

def add_item(args, filename):
    try:
        list_args = load_from_json(filename)
    except Exception:
        list_args = []

    for item in args:
        list_args.append(item)

    save_to_json(list_args, filename)

if __name__ == "__main__":
    args = sys.argv[1:]
    filename = "add_item.json"
    add_item(args, filename)


import pygame
import sys
import time
from pygame.locals import *
import random
import pygame.freetype

pygame.init()
font = pygame.font.Font(pygame.font.get_default_font(), 56)
screen = pygame.display.set_mode((800,600 ), 0, 32)
red = (255, 0, 0)
purple = (255, 0, 255)
green = (0, 255, 0)
blue = (0, 0, 255)
black = (0, 0, 0)
clock = pygame.time.Clock()
frequencies = {'left': 0.1, 'right': 0.05, 'up': 0.03333, 'down': 0.025}

class rectangle():
    def __init__(self, x, y, width, height, color, frequency,direction):
        self.x = x
        self.y = y
        self.width = width
        self.height = height
        self.color = color
        self.frequency = frequency
        self.text = font.render(direction, True,(255,255, 255))
    def blinking(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        pygame.display.update()
        time.sleep(self.frequency)
        pygame.draw.rect(screen, black, (self.x, self.y, self.width, self.height))
        pygame.display.update()
        time.sleep(self.frequency)
    def draw_rect(self):
        pygame.draw.rect(screen, self.color, (self.x, self.y, self.width, self.height))
        pygame.display.update()
    def draw_text(self):
        screen.blit(self.text, (self.x+150, self.y+125))
        pygame.display.update()
    def draw(self):
        self.draw_rect()
        self.draw_text()

def random_blinking(rect):
    nums = 0
    rounds = 2.5 / rect.frequency
    while nums<=rounds:
        rect.blinking()
        nums += 1

trials = 4
red_rec = rectangle(0, 0, 400, 300, red, frequencies['left'],'left')
purple_rec = rectangle(400, 0, 400, 300, purple, frequencies['right'],'right')
green_rec = rectangle(0, 300, 400, 300, green, frequencies['up'],'up')
blue_rec = rectangle(400, 300, 400, 300, blue, frequencies['down'],'down')
rectangles = {red_rec: 0, purple_rec: 0, green_rec: 0, blue_rec: 0}

def main():

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
        red_rec.draw()
        purple_rec.draw()
        green_rec.draw()
        blue_rec.draw()
        time.sleep(1)

        if(len(rectangles)!=0):
            random_rectangle = random.choice(list(rectangles.keys()))
            rectangles[random_rectangle] += 1
            if rectangles[random_rectangle] == trials:
                del rectangles[random_rectangle]
            random_blinking(random_rectangle)

main()


from ann import ANN
from data_handler import DataHandler
import matplotlib.pyplot as plt
import numpy as np
from sklearn.metrics import roc_curve, auc
import collections

TRAIN_FILENAME = "../data/train.json"
TEST_FILENAME  = "../data/test.json"

# generate result for online evaluation
def online_eval():
    # evaluation code for online test
    handler = DataHandler()
    data = handler.generate_data(TRAIN_FILENAME)
    testing_data = handler.generate_data(TEST_FILENAME, 'test')
    ann = ANN(9,10,1)
    for i in range(80):
        print(i+1)
        ann.train(data, 5000)

    result = ann.test_without_true_label(testing_data, 0.23)
    handler.write_to_result(TEST_FILENAME, result)

# my evaluation
# add in cross validation
def my_eval(ann, training_data, testing_data, iter_num=60):
    for i in range(iter_num):
        ann.train(training_data, 5000)
    result = ann.test(testing_data, 0.34)

    return result

# for each test, use data with 100 true label and 300 false label.
def split_data(data, offset):
    train_data = []
    test_data  = []

    zero_count = 0
    one_count = 0
    for i in range(len(data)):
        if i < offset:
            train_data.append(data[i])
        else:
            if (data[i][1][0] == 1 and one_count < 100):
                test_data.append(data[i])
                one_count += 1
            else:
                train_data.append(data[i])

            if (data[i][1][0] == 0 and zero_count < 300):
                test_data.append(data[i])
                zero_count += 1
            else:
                train_data.append(data[i])

    y=collections.Counter([val[1][0] for val in test_data])
    print(y)

    return train_data, test_data

def iteration_test(data):
    train_data, test_data = split_data(data, 0)
    vals = []
    for i in range(10, 101, 10):
        print(i)
        ann = ANN(9,7,1)
        vals.append(my_eval(ann, train_data, test_data, i))

    plot_iter(vals)

def node_test(data):

    train_data, test_data = split_data(data, 0)
    result = []

    for i in range(1, 11):
        array = [9]
        array.append(i)
        array.append(1)
        print("Testing...")
        print(array)
        vals = []
        for i in range(5):
            ann = ANN(*array)
            vals.append(my_eval(ann, train_data, test_data))
        print(max(vals))
        result.append(max(vals))

    plot_node(result)

def layer_test(data):

    train_data, test_data = split_data(data, 0)
    result = []

    array = [9, 1]
    for i in range(1, 4):
        array.pop()
        array.append(10)
        array.append(1)
        print("Testing...")
        print(array)
        vals = []
        ann = ANN(*array)
        vals.append(my_eval(ann, train_data, test_data))
        print(max(vals))
        result.append((array, max(vals)))

    print(result)

def cross_validation(fold, offset, data):
    for i in range(fold):
        train_data, test_data = split_data(data, offset*i)
        ann = ANN(9,7,1)
        my_eval(ann, train_data, test_data)

# plots iteration number figure
def plot_iter(result):
    width = 10
    x = np.arange(10, 101, 10);
    plt.ylim(0.6, 0.68)
    plt.ylabel('Precision')
    plt.xlabel('Iteration')
    plt.bar(x, [val for val in result], width, color='#ababab')
    plt.show()

# plot node number in hidden layer figure
def plot_node(result):
    width = 0.5
    x = np.arange(1, 11, 1);
    plt.ylim(0.62, 0.66)
    plt.ylabel('Precision')
    plt.xlabel('Hidden Layer Node Number')
    plt.bar(x, [val for val in result], width, color="#ababab")
    plt.show()

if __name__ == "__main__":

    handler = DataHandler()
    data = handler.generate_data(TRAIN_FILENAME)
    iteration_test(data)
    node_test(data)
    layer_test(data)
    cross_validation(5, 500, data)
    online_eval()


import streamlit as st
from helper import describe, data, display

st.set_page_config(
     page_title="Data Analysis Web App",
     page_icon="ðŸ§Š",
     layout="wide",
     initial_sidebar_state="expanded",
     menu_items={
         'Get Help': 'https://github.com/everydaycodings/Data-Analysis-Web-App',
         'Report a bug': "https://github.com/everydaycodings/Data-Analysis-Web-App/issues/new",
         'About': "# This is a header. This is an *extremely* cool app!"
     }
)

file_format_type = ["csv"]

st.sidebar.title("Data Analysis Web App")

uploaded_file = st.sidebar.file_uploader("Upload Your file", type=file_format_type)

if uploaded_file is not None:

    data = data(uploaded_file)

    describe, shape, columns, num_category, str_category, null_values, dtypes, unique, str_category, column_with_null_values = describe(data)

    max_nan_hold = st.slider(label="Enter the Percentage of the max NaN Value acceptance", help="Enter The Percentage at which you can replace the NaN value if it exceeds the number you select that perticular column will be droped", min_value=1, max_value=100)
    ignore_outliers_col = st.multiselect(label="Ignored Numeric Column for Outliers", help="Only Select those columns in which you dont want outliers to be applied.", options=num_category, default=None)

    if st.checkbox("Machine Learning", help="Weather you want to prepare the data for Machine Learning"):

        ml_cat = st.selectbox(label="Enter The ML Category: ", options=["Supervised", "Unsupervised"])

        if ml_cat == "Supervised":

            #ml_algo_cat = st.selectbox(label="Enter your ML problem type.", options=["Regression", "Classification"])
            y = st.selectbox(label="Select your dependent Column.", options=columns)

    if st.button("Analysis Data"):

        null_data, log_text_null, outliers_data, log_text_outliers = display(data, max_nan_hold, ignore_outliers_col, num_category)

        st.header("Overview")
        col1, col2, col3, col4 = st.columns(4)
        with col1:
            st.text("Basic Information")
            st.write("Dataset Name")
            st.text(uploaded_file.name)

            st.write("Dataset Size(MB)")
            number = round((uploaded_file.size*0.000977)*0.000977,2)
            st.write(number)

            st.write("Dataset Shape")
            st.write(shape)

        with col2:
            st.text("Dataset Columns")
            st.write(columns)

        with col3:
            st.text("Numeric Columns")
            st.dataframe(num_category)

        with col4:
            st.text("String Columns")
            st.dataframe(str_category)

        col5, col6, col7, col8= st.columns(4)

        with col6:
            st.text("Columns Data-Type")
            st.dataframe(dtypes)

        with col7:
            st.text("Counted Unique Values")
            st.write(unique)

        with col5:
            st.write("Counted Null Values")
            st.dataframe(null_values)

        st.header("Analysis Result")

        col1, col2  = st.columns(2)

        with col1:
            st.text("Percentage of NaN Value in each column")
            st.dataframe(null_data)

        with col2:
            st.text("Outliers Caping in Numeric Columns")
            st.dataframe(outliers_data)

        st.code(body=log_text_null+log_text_outliers)


class NewCampaign(GlobalCondition):
    def mod_new_game_mode(self):
        """Defining this method allows us to specify a new game mode we'd like to add to Slipways."""
        return {
            # the name to display on the mode list
            "label": LStr("mode.example-campaign.title"),
            # the package for running our new game mode - this should be a separate package from your mod.pkg.py
            # this package will be loaded when the player selects your mode from the mode menu
            "package": "mods/example-campaign/menu",
            # the 'type' of play, ie. which of the base game modes your new mode resembles the most
            # should be "standard", "campaign" (for new campaigns) or "sandbox" (for endless-based modes)
            "mode_type": "campaign"
        }


def falling(n, k):
    """Compute the falling factorial of n to depth k.

    >>> falling(6, 3)  # 6 * 5 * 4
    120
    >>> falling(4, 3)  # 4 * 3 * 2
    24
    >>> falling(4, 1)  # 4
    4
    >>> falling(4, 0)
    1
    """
    "*** YOUR CODE HERE ***"
    if k == 0: return 1

    return n * falling(n-1, k-1)

def sum_digits(y):
    """Sum all the digits of y.

    >>> sum_digits(10) # 1 + 0 = 1
    1
    >>> sum_digits(4224) # 4 + 2 + 2 + 4 = 12
    12
    >>> sum_digits(1234567890)
    45
    >>> a = sum_digits(123) # make sure that you are using return rather than print
    >>> a
    6
    """
    "*** YOUR CODE HERE ***"
    temp = 0

    for ele in str(y):
        temp += int(ele)

    return temp

def double_eights(n):
    """Return true if n has two eights in a row.
    >>> double_eights(8)
    False
    >>> double_eights(88)
    True
    >>> double_eights(2882)
    True
    >>> double_eights(880088)
    True
    >>> double_eights(12345)
    False
    >>> double_eights(80808080)
    False
    """
    "*** YOUR CODE HERE ***"
    i = 0

    if len(str(n)) == 2 and str(n) == '88': return True

    while i + 2 <= len(str(n)):
        strs = str(n)
        # print(strs[i:i+2])
        if strs[i:i+2] != '88':
            i += 1
        else:
            return True

    return False


from log.logger import logger
from utils.thread_local import (
    get_request_zone,
    set_request_zone,
)

import context
from resource_control.iaas.interface import get_all_zones

g_region_zones = None

def get_region_zones():
    """
    return dict, key is region id, value are zone_ids.
    :return:
    """

    global g_region_zones
    if g_region_zones:
        return g_region_zones

    zones = get_all_zones()  # type: dict

    if not zones:
        logger.error("get zones failed")
        return None
    logger.debug("get zones %s" % zones)

    g_region_zones = {}

    for zone_id, zone in zones.items():
        region_id = zone['region_id']
        if region_id not in g_region_zones:
            g_region_zones[region_id] = []
        g_region_zones[region_id].append(zone)

    return g_region_zones

def is_region_id(zone_id):

    region_zones = get_region_zones()
    if zone_id and region_zones and zone_id in region_zones:
        return True

    return False

def get_zones(region_id):
    """
    return list_dict, zone info
    :param region_id:
    :return:
    """
    region_zones = get_region_zones()

    if region_id not in region_zones:
        return None
    return region_zones[region_id]

def dispatch_region_request(req, sender):
    request_zone = None

    ctx = context.instance()
    # convert region id to zone id when needed
    if 'zone' in req:
        request_zone = get_request_zone()
        if request_zone and not is_region_id(req['zone']):
            # already dispatched
            req['request_zone'] = request_zone
            return request_zone

        zone_id = req['zone']
        request_zone = zone_id
        req['request_zone'] = request_zone

        if is_region_id(zone_id):
            if ctx.region_default_zone:
                req['zone'] = ctx.region_default_zone[zone_id]
            logger.debug("dispatch region [%s] request to zone [%s] with "
                         "ctx.region_default_zone [%s]",
                         request_zone, req['zone'], ctx.region_default_zone)

    set_request_zone(request_zone)

    return request_zone


from flask import Flask, request, redirect, url_for, Blueprint, render_template, flash, jsonify
from db.tecnicos.tecnicos import Tecnico, nuevo_tecnico
from db import db

tecnicos = Blueprint('tecnicos', __name__)

@tecnicos.route('/tecnico', methods=['GET', 'POST', 'PUT', 'DELETE'])
def tecnico():
    tecnicos = Tecnico.query.all()
    if request.method == 'GET':
        tecnicos = Tecnico.query.all()
        print([a.__asdict__() for a in tecnicos])
        response = jsonify({
            'tecnicos': [a.__asdict__() for a in tecnicos],
            })
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    if request.method == 'POST':
        id = request.json['id']
        nombre = request.json['nombre']
        apellido = request.json['apellido']
        dni = request.json['dni']
        nacimiento = request.json['nacimiento']
        sexo = request.json['sexo']
        equipo = request.json['equipo']

        dni_existe = Tecnico.query.filter_by(dni=dni).first()

        if dni_existe:
            print('tecnico ya existe')
        else:
            nuevo_tecnico(id, nombre, apellido, dni, nacimiento, sexo, equipo)
            print(f'tecnico {nombre} {apellido}, creado')
            tecnicos = Tecnico.query.all()
            response = jsonify({
                'tecnicos': [a.__asdict__() for a in tecnicos],
                })
            response.headers.add('Access-Control-Allow-Origin', '*')
            return response

    if request.method == 'PUT':
        print('PUT')
        valores = request.get_json()
        id = valores['id']
        print(valores)
        tecnico = Tecnico.query.filter_by(id=id).first()
        print(tecnico.nombre, tecnico.apellido, tecnico.nacimiento)
        tecnico.id = valores['id']
        tecnico.nombre = valores['nombre']
        tecnico.apellido = valores['apellido']
        tecnico.dni = valores['dni']
        tecnico.nacimiento = valores['nacimiento']
        tecnico.sexo = valores['sexo']
        tecnico.equipo = valores['equipo']
        db.session.commit()
        print('tecnico ', id, ' editado')
        tecnicos = Tecnico.query.all()
        print([a.__asdict__() for a in tecnicos])
        response = jsonify({
            'tecnicos': [a.__asdict__() for a in tecnicos],
            })
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response

    if request.method == 'DELETE':
        print('delete')
        id = request.get_json()
        print(id)
        tecnico = Tecnico.query.filter_by(id=id)
        tecnico.delete()
        db.session.commit()
        print('tecnico ', id, ' eliminado')
        tecnicos = Tecnico.query.all()
        print([a.__asdict__() for a in tecnicos])
        response = jsonify({
            'tecnicos': [a.__asdict__() for a in tecnicos],
            })
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response


from collections import Counter
def solution1(words)->int:
    count = Counter(words)
    ans = 0
    central = False
    for word, word_count in count.items():
        # Palindrome word
        if word[0] == word[1]:
            if word_count % 2 == 0:
                ans += word_count
            else:
                ans += word_count - 1
                central = True
        elif word[0] < word[1]:
            ans += 2 * min(word_count , count[word[1] + word[0]])
    if central:
        ans += 1
    return 2 * ans

def solution2(words)->int:
    ans = 0
    alphabet_size = 26
    central = False
    count = [[0 for j in range(alphabet_size)] for i in range(alphabet_size)]
    for word in words:
        count[ord(word[0]) - ord('a')][ord(word[1]) - ord('a')] += 1
    for i in range(alphabet_size):
        if count[i][i] % 2 == 0:
            ans += count[i][i]
        else:
            ans += count[i][i] - 1
            central = True
        for j in range(i+1,alphabet_size):
            ans += 2 * min(count[i][j] , count[j][i])

    if central:
        ans += 1
    return 2 * ans

print(solution2(["ab","ty","yt","lc","cl","ab"]))


from .mdl_reader import extract_bracket_content, chunkifier, get_between
from .parse_geometry import parse_geometry
from ..classes.WarCraft3Geoset import WarCraft3Geoset

def parse_geosets(data: str) -> WarCraft3Geoset:
    geoset_data_internal = extract_bracket_content(data)
    geoset_data_chunks = chunkifier(geoset_data_internal)

    geoset: WarCraft3Geoset = parse_geometry(geoset_data_chunks)

    if data.find("MaterialID") > -1:
        geoset.material_id = int(get_between(data, "MaterialID ", ","))

    # for chunk in geoset_data_chunks:
    #     label = chunk.split(" ", 1)[0]
    #     if label == "Anim":
    #         print("Anim!")
    #         parse_geoset_animations(chunk, model)

    return geoset


import random
from bs4 import BeautifulSoup
import requests

source = requests.get('https://www.ef.edu/english-resources/english-vocabulary/top-1000-words/').text
soup = BeautifulSoup(source, 'lxml')
match = soup.find('div', class_='field-item even')
wordlist = match.text.split()[95:]
WORDLIST = [x.upper() for x in wordlist]

def main():
    print("Welcome to Hangman!")
    Word = random.choice(WORDLIST)
    print("The word you will be guessing will have {} letters!".format(len(Word)))
    guesses = 7
    guessedCorrect = []
    guessedRight = ['_'] * len(Word)
    lettersGuessed = []
    print(guessedRight)
    while guesses > 0 and '_' in guessedRight:
        answer = input("Enter your letter guess: ")
        answer = str(answer)
        while not answer.isalpha() or len(answer) != 1 or answer.upper() in lettersGuessed:
            answer = input("You need to enter a single letter/you have already guessed that letter: ")
            answer = str(answer)
        if answer.upper() in Word:
            guessedCorrect.append(answer.upper())
            lettersGuessed.append(answer.upper())
            guessedRight = [x if x in guessedCorrect else '_' for x in Word]
            print("\nYou guessed a letter correctly!")
            print("Here is the word: ", guessedRight)
            print("Letter(s) guessed: {} \n".format(lettersGuessed))
        else:
            lettersGuessed.append(answer.upper())
            guesses -= 1
            print("\nYour letter guess isn't in the word!")
            print("Letter(s) guessed: ", lettersGuessed)
            print("Guesses remaining: {}\n".format(guesses))
            print("Here is the word: ", guessedRight)
    if guesses == 0:
        print("The man is hanged! You have no more guesses.")
        print("The word was: {}".format(Word))
    else:
        print("Congratulations! You guessed all the letters correctly!: ", guessedRight)
        print("The word is, indeed, {}!".format(Word))

main()


import argparse

parser = argparse.ArgumentParser(description='inference program to predict using trained model to new files')
parser.add_argument('--trained_model', type=str, default='data/processed/training/unzipped',
help='path of trained_model')
parser.add_argument('--classes', type=str, default='data/processed/training/unzipped',
help='path of classes csv file')
parser.add_argument('--threshold', type=int, default='data/processed/training/unzipped',
help='threshold to classify at')
parser.add_argument('--inpath', type=str, default='data/processed/training/unzipped',
help='directory of new image data to be inferred on')
parser.add_argument('--outpath', type=str, default='data/processed/training/unzipped',
help='directory to save files from inference output')
args = parser.parse_args()

# doesn't work, but intention is here
import inference
import subprocess

"""
 install data and model files
!pip install keras_retinanet

inference.configure_keras()
args = (args.trained_model, args.classes, args.threshold, args.inpath)
model_object = inference.model_object(import_from_drive = True, args = args)
list(map(in, inference.img_inference))
subprocess.call(F'mv {inpath} {outpath}')
# run inference

"""


import sys
class Solution(object):
    def calculateMinimumHP(self, l):
        m = len(l)
        n = len(l[0])
        r = [ [sys.maxint] * (n + 1) for _ in range(0, m + 1) ]
        r[m][n-1] = 1
        r[m-1][n] = 1
        for i in range(m-1, -1,-1):
            for j in range(n-1, -1,-1):
                r[i][j] = min(r[i+1][j], r[i][j+1]) - l[i][j]
                if r[i][j] <= 0:
                    r[i][j] = 1
        return r[0][0]


# Definition for singly-linked list.
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def partition(self, head, x):
        """
        :type head: ListNode
        :type x: int
        :rtype: ListNode
        """
        if head == None:
            return None

        # l是最后一个小于x的节点
        dump = ListNode(0)
        dump.next = head
        l = dump

        while head.next != None:
            if head.val < x:
                l = head
                head = head.next
            elif head.next.val >= x:
                    head = head.next
            else: # 出现了逆序，前一个大于等于x，后一个小于x
                tmp = head.next
                head.next = tmp.next
                tmp.next = l.next
                l.next = tmp
                l = l.next

        return dump.next

if __name__ == '__main__':
    head = ListNode(1)
    head.next = ListNode(4)
    head.next.next = ListNode(2)
    head.next.next.next = ListNode(3)
    head.next.next.next.next = ListNode(5)
    head.next.next.next.next.next = ListNode(2.5)

    head = Solution().partition(head, 3)

    while head:
        print("{} -> ".format(head.val), end="")
        head = head.next
        if head == None:
            print(head)


#!/usr/bin/python3
import logger
from logger import log
import yaml
import sys
from token_distribute import Distribute
from settings import load_user_param, user_param

def run(config_file: str):
    with open(config_file, "r", encoding="utf8") as file:
        user: dict = yaml.load(file, Loader=yaml.FullLoader)
        file.close()
    load_user_param(user)
    logger.init_loger(user_param.wax_account)
    distribute = Distribute()
    distribute.start()

def main():
    try:
        user_yml = "user.yml"
        if len(sys.argv) == 2:
            user_yml = sys.argv[1]
        run(user_yml)
    except Exception:
        log.exception("distribute error")

if __name__ == '__main__':
    main()


from lxml import etree

### Ejercicio 1
def usuarios(arbol):
	nombres=arbol.xpath("//user/firstname/text()")
	apellidos=arbol.xpath("//user/lastname/text()")
	for indice in range(len(nombres)):
		nombres[indice]=nombres[indice]+" "+apellidos[indice]
	return nombres

### Ejercicio2
def avatar(arbol):
	nombres=arbol.xpath('//user[picture="1"]/firstname/text()')
	apellidos=arbol.xpath('//user[picture="1"]/lastname/text()')
	for indice in range(len(nombres)):
		nombres[indice]=nombres[indice]+" "+apellidos[indice]
	return nombres

### Ejercicio3
def acceso_desde_fuera(arbol):
	usuarios=arbol.xpath('//user[contains(lastip,"172.22")=false]/email/text()')
	return usuarios

### Ejercicio4
def buscar(cadena,arbol):
	nombres=arbol.xpath('//user[starts-with(firstname,"A")]/firstname/text()')
	apellidos=arbol.xpath('//user[starts-with(firstname,"A")]/lastname/text()')
	for indice in range(len(nombres)):
		nombres[indice]=nombres[indice]+" "+apellidos[indice]
	return nombres

### Ejercicio 5
### Voy a hacer un diccionario, cada elemento del diccionario tendrá como clave el nombre de la localidad y como valor
### tendrá una lista con los usuarios

def lista_por_localidad(arbol):
	dic_usuarios={}
	lista_localidades=list(set(arbol.xpath('//user/city/text()')))
	for loc in lista_localidades:
		# Voy creando el diccionario, creo un elemento con la key igual a la localidad y como valor una lista vacia
		nombres=arbol.xpath('//user[city="%s"]/firstname/text()'%loc)
		apellidos=arbol.xpath('//user[city="%s"]/lastname/text()'%loc)
		dic_usuarios[loc]=[]
		for indice in range(len(nombres)):
			dic_usuarios[loc].append(nombres[indice]+" "+apellidos[indice])
	return dic_usuarios

### Ejercicio 6
def ultimo_acceso(arbol):
	lista=[]
	lua=sorted(list(map(int,arbol.xpath("//user/lastaccess/text()"))),reverse=True)
	for ua in lua:
		nombre=arbol.xpath('//user[lastaccess="%s"]/firstname/text()'%ua)
		apellido=arbol.xpath('//user[lastaccess="%s"]/lastname/text()'%ua)
		lista.append(nombre[0]+" "+apellido[0])

	return lista

arbol = etree.parse('users.xml')

### Ejercicio 1
print(usuarios(arbol))

### Ejercicio 2
print(avatar(arbol))

### Ejercicio 3
print(acceso_desde_fuera(arbol))

### Ejercicio 4
cad=input("Dame el nombre:")
print(buscar(cad,arbol))

### Ejercicio 5
dic=lista_por_localidad(arbol)
for key,value in dic.items():
	print(key)
	print("="*len(key))
	for user in value:
		print(user)

### Ejercicio 6
print(ultimo_acceso(arbol))


#from skills.basic_commands.basic_commands_skills import RecordingSkill
import tempfile
#from transcription.process_pipeline import DeepspeechTranscription, Transcription, Wav2LetterTranscription, process_pipeline_entry
from skills.general_classifier.general_classifier import GeneralClassifierSkill
from skills.shopping_classifier.shopping_skill import ShoppingSkill
import click
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # cleanup error message items
# humanfriendly, click, padatious, psutil, memory_profiler, gdown, paramiko

skills = [GeneralClassifierSkill(), ShoppingSkill()]

def classify_text(skills, text):
    print("Classifying phrase: ", text)
    for skill in skills:
        print("Running classification for skill: ", skill.skill_name)
        print(skill.classify(text))
        if isinstance(skill, ShoppingSkill):
            print("Possible shopping item", skill.find_shopping_item(text))

def classify_file(skills, file):
    with open(file) as f:
        for text in f.readlines():
            if text:
                classify_text(skills, text)

# def classify_audio_file(skills, audio_file, transcription_model: Transcription):
#     with tempfile.TemporaryDirectory() as dirpath:
#         transcript_file = process_pipeline_entry(
#             audio_file,
#             dirpath,
#             transcription_model,
#         )
#         classify_file(skills, transcript_file)

@click.command()
@click.option("--text", default=None, help="Run classification on provided text")
@click.option("--audio_path", default=None, help="Transcribe audio then provide classification")
@click.pass_context
def cli(ctx, text, audio_path):
    if not text and not audio_path:
        click.echo(ctx.get_help())

    if text:
        classify_text(skills, text)
    # if audio_path:
    #     classify_audio_file(skills, audio_path, DeepspeechTranscription())

if __name__ == "__main__":
    # cli()
    skills = [ShoppingSkill(), GeneralClassifierSkill()]
    classify_text(skills, "We ran out of watermelons")
    # classify_audio_file(skills, "save_audio/savewav_2020-09-09_19-04-59_750112.wav", Wav2LetterTranscription())
    # general_classifier = GeneralClassifierSkill()
    # print(general_classifier.classify("Weather is nice outside"))


import socket

ip = 'localhost'
port = 9999
message = "hello"

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(("localhost", 9998))
#sock.setblocking(0)
print("Trying to connect...")
sock.connect((ip, port))
print("connected")
try:
    sock.sendall(bytes(message, 'ascii'))
    response = str(sock.recv(4096), 'ascii')
    print("Received: {}".format(response))
finally:
    sock.close()


import matplotlib
import matplotlib.pyplot as plt
import numpy as np

def plot_confusions(image, mask, pred, coords, show=True, save=False, filename='confusion_plot.png'):
    axis0, axis1, axis2 = coords

    image_0 = np.rot90(image[axis0, :, :])
    image_1 = np.rot90(image[:, axis1, :])
    image_2 = np.rot90(image[:, :, axis2])

    mask_0 = np.rot90(mask[axis0, :, :])
    mask_1 = np.rot90(mask[:, axis1, :])
    mask_2 = np.rot90(mask[:, :, axis2])

    pred_0 = np.rot90(pred[axis0, :, :])
    pred_1 = np.rot90(pred[:, axis1, :])
    pred_2 = np.rot90(pred[:, :, axis2])

    combined_0 = mask_0 * 2 + pred_0
    combined_1 = mask_1 * 2 + pred_1
    combined_2 = mask_2 * 2 + pred_2

    fig, ax = plt.subplots(5, 3, figsize=(20, 20))

    ax[0][0].set_title('Scan images')
    ax[0][0].imshow(image_0, cmap='gray')
    ax[0][1].imshow(image_1, cmap='gray')
    ax[0][2].imshow(image_2, cmap='gray')

    ax[1][0].set_title('Original masks')
    ax[1][0].imshow(mask_0, cmap='gray')
    ax[1][1].imshow(mask_1, cmap='gray')
    ax[1][2].imshow(mask_2, cmap='gray')

    ax[2][0].set_title('Predicted masks')
    ax[2][0].imshow(pred_0, cmap='gray')
    ax[2][1].imshow(pred_1, cmap='gray')
    ax[2][2].imshow(pred_2, cmap='gray')

    cmap = matplotlib.colors.ListedColormap(['black', 'red', 'yellow', 'green'])
    norm = matplotlib.colors.Normalize(vmin=0, vmax=3)

    ax[3][0].set_title('Combined masks')
    ax[3][0].imshow(combined_0, cmap=cmap, norm=norm)
    ax[3][1].imshow(combined_1, cmap=cmap, norm=norm)
    ax[3][2].imshow(combined_2, cmap=cmap, norm=norm)

    ax[4][0].set_title('Overlayed scan')
    ax[4][0].imshow(image_0, cmap='gray')
    ax[4][0].imshow(combined_0, cmap=cmap, norm=norm, alpha=0.2)
    ax[4][1].imshow(image_1, cmap='gray')
    ax[4][1].imshow(combined_1, cmap=cmap, norm=norm, alpha=0.2)
    ax[4][2].imshow(image_2, cmap='gray')
    ax[4][2].imshow(combined_2, cmap=cmap, norm=norm, alpha=0.2)

    if show:
        plt.show()

    if save:
        fig.savefig(filename)

    plt.close('close')


#! python

import shutil, os, re

datePattern = re.compile(r"""^(.*?) # all text before the date
    ((0|1)?\d)-                     # one or two digits for the month
    ((0|1|2|3)?\d)-                 # one or two digits for the day
    ((19|20)\d\d)                   # four digits for the year
    (.*?)$                          # all text after the date
    """, re.VERBOSE)

PATH = './P2C83-RegexSearch'

for fileName in os.listdir(PATH):

    date = re.search(datePattern, fileName)

    if not os.path.isfile(os.path.join(PATH,fileName)) or date == None:
        continue

    beforePart = date.group(1)
    monthPart = date.group(2)
    dayPart = date.group(4)
    yearPart = date.group(6)
    afterPart = date.group(8)

    eurDate = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart

    absWorkingDir = os.path.abspath(PATH)
    usDate = os.path.join(absWorkingDir, fileName)
    eurDate = os.path.join(absWorkingDir, eurDate)

    print('Renaming "%s" to "%s"...' % (usDate, eurDate))
    #shutil.move(usDate, eurDate)


import sys

class Dots:
	def __init__(self, a, b):
		self.x1 = float(a)
		self.x2 = float(b)

	def __str__(self):
		return ("{} {}".format(self.x1, self.x2))

	def __getitem__(self, key):
		if isinstance(key, int):
			return [self.x1+i*(self.x2-self.x1)/(key-1) for i in range(key)]

		start, stop, qua = key.start or 0, key.stop or key.step, key.step
		# print(start, stop, qua)
		extra = 0
		st = 0

		if start >= stop:
			extra += start - stop + 1

		if start < 0:
			st = start
			extra -= start
			start = 0

		if qua == None:
			qua = stop
			sl = [self.x1+i*(self.x2-self.x1)/(qua-1) for i in range(st, qua+extra)]
			return sl[start]

		if stop > qua:
			extra += stop - qua

		sl = [self.x1+i*(self.x2-self.x1)/(qua-1) for i in range(st, qua+extra)]
		return [sl[i] for i in range(start, stop-st)]

# a = Dots(-1,1)
# print(*a[7])
# print(a[0:7])
# print(a[2:7])
# print(a[4:7])
# print(a[7:7])
# print(a[-7:7])
# print(*a[1:3:7])
# print(*a[:3:7])
# print(*a[2::7])
# print(*a[::7])
# print(*a[-2:8:7])

# a = Dots(0,40)
# print(*a[5])
# print(a[0:5])
# print(a[2:5])
# print(a[4:5])
# print(a[7:5])
# print(a[-7:5])
# print(*a[1:3:5])
# print(*a[:3:5])
# print(*a[2::5])
# print(*a[::5])
# print(*a[-2:6:5])