# -*- coding: utf-8 -*-
"""JJCM Practica 3 LC.ipynb

1) Implementar,	usando NLTK	 y	 Python,	 el	 algoritmo	 de	 Lesk	 simplificado	 para
desambiguar	el	 sentido	 de	las	 palabras	 (WSD).	 La	 función	 recibirá	 una	 palabra	 y
una	 frase	que	la	contenga	y	decidirá	el	mejor	sentido	para	esa	palabra.	Las	 frases
serán	en	inglés	 y	 se	 deberá	eliminar	de	la	 frase, de	la	glosa	 y de	los ejemplos	 de
cada	sentido	las	‘stopwords’
"""

# Imports
#!pip install nltk
import nltk
from nltk.corpus import wordnet as wn
from nltk.corpus import stopwords as sw
nltk.download('omw')
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')

# Obtain English Stop Words
sw_english=sw.words('english')

def compute_overlap(contexto, sign):
  return len(contexto.intersection(sign))

def lematizacion(frase):
    sentence_lematized = []
    for w in frase:
      sentence_lematized.append(wn.morphy(w))
    return sentence_lematized

def simplified_lesk(word, sentence):

  overlap = 0
  max_overlap = 0

  # Senses
  senses=wn.synsets(word)
  best_sense = senses

  # Tokenizado
  sentence_tokenized = nltk.word_tokenize(sentence)

  # lematizacion
  sentence_tokenized_lematized = lematizacion(sentence_tokenized)
  context = set(sentence_tokenized_lematized)

  # Quitamos Stop Words
  context = context.difference(sw_english)

  for sense in senses[1:]:
    signature = set(lematizacion(nltk.word_tokenize(sense.definition().join(sense.examples()))))
    signature = signature.difference(sw_english)
    overlap = compute_overlap(context, signature)
    if overlap > max_overlap:
      max_overlap = overlap
      best_sense = sense

  return best_sense

#simplified_lesk('bank', 'Hi, mi name is Jose Javier and i want go to bank')
simplified_lesk('bank', 'Yesterday	I	went to	the	bank to withdraw the	money and the	credit	card did	not	work')

"""2)	Implementar un	algoritmo	similar	para	la	desambiguación	semántica	utilizando
Word Embeddings	y	una	distancia	de	similitud	semántica como	la	distancia	coseno
"""

#Imports
# Word embeddings
import gensim
from nltk.data import find
import nltk
import numpy as np

nltk.download('word2vec_sample')
word2vec_sample = str(find('models/word2vec_sample/pruned.word2vec.txt'))
model = gensim.models.KeyedVectors.load_word2vec_format(word2vec_sample, binary=False)

def lematizacion(frase):
    sentence_lematized = []
    for w in frase:
      sentence_lematized.append(wn.morphy(w))
    return sentence_lematized

def computeDistance(contexto, sentido):
  res = 0.0
  for token_c in contexto:
    for token_s in sentido:
      #print(token_c)
      #print(token_s)
      res += model.similarity(token_c,token_s)
  return res

def desambiguar(word, sentence):

  # Senses
  senses=wn.synsets(word)
  best_sense = []
  max_similitud = 0.0

  # Tokenizado
  sentence_tokenized_con_sw = set(nltk.word_tokenize(sentence))
  sentence_tokenized_sin_sw = sentence_tokenized_con_sw.difference(sw_english)

  # lematizacion
  sentence_tokenized_lematized = lematizacion(sentence_tokenized_sin_sw)
  context = set(sentence_tokenized_lematized)

  if len(context.intersection({None})) > 0:
    context.remove(None)

  for sense in senses[1:]:

    signature_con_sw = set(nltk.word_tokenize(sense.definition().join(sense.examples())))
    signature_sin_sw = signature_con_sw.difference(sw_english)
    signature = set(lematizacion(signature_sin_sw))

    if len(signature.intersection({None})) > 0:
      signature.remove(None)

    similitud = computeDistance(context, signature)
    if similitud > max_similitud:
      max_similitud = similitud
      best_sense = sense

  return best_sense

desambiguar('bank', 'Yesterday	I	went to	the	bank to withdraw the	money and the	credit	card did	not	work')


import os
import datetime
import numpy as np
import tensorflow as tf
import tensorflow.keras as keras
from tensorflow.keras.layers import (
    Concatenate,
    Dense,
    Embedding,
    Flatten,
    Input,
    Multiply,
)
from tensorflow.keras import Model
from tensorflow.keras.regularizers import l2
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.utils import to_categorical
from typing import List

__author__ = 'linhthi'

class NeuMF:
    def __init__(self,
                 number_of_users: int,
                 number_of_items: int,
                 latent_dim_mf: int = 4,
                 latent_dim_mlp: int = 32,
                 reg_mf: float = 0,
                 reg_mlp: float = 0.01,
                 dense_layers: List[int] = [8, 4],
                 reg_layers: List[int] = [0.01, 0.01],
                 activation_dense: str = "relu"
                 ) -> keras.Model:
        """ Init class NeuMF """

        self.activation_dense = activation_dense
        self.reg_layers = reg_layers
        self.dense_layers = dense_layers
        self.reg_mlp = reg_mlp
        self.reg_mf = reg_mf
        self.latent_dim_mlp = latent_dim_mlp
        self.latent_dim_mf = latent_dim_mf
        self.number_of_items = number_of_items
        self.number_of_users = number_of_users

    def get_model(self) -> object:
        # input layer
        user = Input(shape=(1), dtype="int32", name="user_id")
        item = Input(shape=(1), dtype="int32", name="item_id")

        # embedding layer
        mf_user_embedding = Embedding(
            input_dim=self.number_of_items,
            output_dim=self.latent_dim_mf,
            name="mf_user_embedding",
            embeddings_initializer="RandomNormal",
            embeddings_regularizer=l2(self.reg_mf),
            input_length=1,
        )
        mf_item_embedding = Embedding(
            input_dim=self.number_of_items,
            output_dim=self.latent_dim_mf,
            name="mf_item_embedding",
            embeddings_initializer="RandomNormal",
            embeddings_regularizer=l2(self.reg_mf),
            input_length=1,
        )
        mlp_user_embedding = Embedding(
            input_dim=self.number_of_users,
            output_dim=self.latent_dim_mlp,
            name="mlp_user_embedding",
            embeddings_initializer="RandomNormal",
            embeddings_regularizer=l2(self.reg_mlp),
            input_length=1,
        )
        mlp_item_embedding = Embedding(
            input_dim=self.number_of_items,
            output_dim=self.latent_dim_mlp,
            name="mlp_item_embedding",
            embeddings_initializer="RandomNormal",
            embeddings_regularizer=l2(self.reg_mlp),
            input_length=1,
        )

        # MF vector
        mf_user_latent = Flatten()(mf_user_embedding(user))
        mf_item_latent = Flatten()(mf_item_embedding(item))
        mf_cat_latent = Multiply()([mf_user_latent, mf_item_latent])

        # MLP vector
        mlp_user_latent = Flatten()(mlp_user_embedding(user))
        mlp_item_latent = Flatten()(mlp_item_embedding(item))
        mlp_cat_latent = Concatenate()([mlp_user_latent, mlp_item_latent])

        mlp_vector = mlp_cat_latent

        # build dense layers for model
        for i in range(len(self.dense_layers)):
            layer = Dense(
                self.dense_layers[i],
                activity_regularizer=l2(self.reg_layers[i]),
                activation=self.activation_dense,
                name="layer%d" % i,
            )
            mlp_vector = layer(mlp_vector)

        predict_layer = Concatenate()([mf_cat_latent, mlp_vector])
        result = Dense(1, name="predict_rating")
        output = result(predict_layer)

        model = Model(
            inputs=[user, item],
            outputs=output
        )

        return model

    def train(self, train, valid, n_epochs):
        N_EPOCHS = n_epochs
        self.neuMF_model = self.get_model()

        self.neuMF_model.compile(
            optimizer=SGD(lr=0.001),
            loss = tf.keras.losses.MSE,
            metrics=[
                tf.keras.metrics.mae,
                tf.keras.metrics.RootMeanSquaredError(),
            ]
        )

        self.neuMF_model._name = "neural_matrix_factorization"
        self.neuMF_model.summary()

        user_train, item_train, rating_train = [], [], []
        for data in train:
            user_train.append(data[0])
            item_train.append(data[1])
            rating_train.append(data[3])
        # print(user_train.reshape())
        # print(ds_train.shape)

        user_valid, item_valid, rating_valid = [], [], []
        for data in valid:
            user_valid.append(data[0])
            item_valid.append(data[1])
            rating_valid.append(data[3])

        # define logs and callbacks
        logdir = os.path.join("logs", datetime.datetime.now().strftime("%Y%m%d-%H%M%S"))
        tensorboard_callback = tf.keras.callbacks.TensorBoard(logdir, histogram_freq=1)
        early_stopping_callback = tf.keras.callbacks.EarlyStopping(patience=6)

        self.neuMF_model.fit(
            x=[np.array(user_train), np.array(item_train)],  # input
            y = np.array(rating_train).astype(float),  # label rating
            validation_data=([np.array(user_valid), np.array(item_valid)], np.array(rating_valid).astype(float)),
            epochs=N_EPOCHS,
            callbacks=[tensorboard_callback, early_stopping_callback],
            verbose=1,
        )
        self.neuMF_model.save("my_neuMF_h5_model.h5")

    def test(self, test):
        user_test, item_test, rating_test = [], [], []
        for data in test:
            user_test.append(data[0])
            item_test.append(data[1])
            rating_test.append(data[3])
        self.neuMF_model.evaluate([np.array(user_test), np.array(item_test)], np.array(rating_test))


import sqlite3

from app.core.pathutils import get_database_root
from app.database.tables import users_table, shopping_list_table

class DatabaseCreator:
    def __init__(self) -> None:
        self._database_path = get_database_root()
        self._connector = sqlite3.connect(self._database_path)

    def create_tables(self) -> None:
        cursor = self._connector.cursor()
        cursor.execute(shopping_list_table)
        cursor.execute(users_table)
        self._connector.commit()

if __name__ == "__main__":
    DatabaseCreator().create_tables()


from django.contrib import admin
from django import forms

from .models import *

# Register your models here.

# class PersonForm(forms.ModelForm):
#     some_field = forms.ModelMultipleChoiceField(Person.objects.all(), widget=FilteredSelectMultiple("Person", False, attrs={'rows':'2'}))
#     class Meta:
#         model = CategoriaNoticia

class NoticiaForm(forms.ModelForm):
    class Meta:
        model = Noticia
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        forms.ModelForm.__init__(self, *args, **kwargs)
        self.fields['categoria'].queryset = CategoriaNoticia.objects.filter(estado=True)
        self.fields['empresa'].queryset = Empresa.objects.filter(estado=True,categoria__nombre='periodico')

class FotoNoticiaInline(admin.StackedInline):
    model = FotoNoticia
    # form = HorarioForm
    fields = ('foto', 'descripcion','autor','localidad')
    can_delete = False
    extra = 1

class NoticiaAdmin(admin.ModelAdmin):
    model = Noticia
    form = NoticiaForm
    # list_display = ('id','titulo', 'sub_titulo', 'descripcion', 'link_fuente', 'estado', 'creado', 'empresa','categoria')
    # list_filter = ('username', 'is_staff', 'is_active', 'groups')
    # fieldsets = (
    #     ('Informacion Personal', {'fields': ('username', 'password', 'nombres', 'apellidos','email','foto','ciudad')}),
    #     ('Permisos', {'fields': ('is_staff', 'is_active','groups', 'user_permissions')}),
    # )
    # add_fieldsets =(
    #     (None, {
    #         'classes': ('wide',),
    #         'fields': ('username', 'password1', 'password2', 'nombres',  'apellidos', 'foto','email', 'is_staff', 'is_active')}
    #     ),
    # )
    inlines = (FotoNoticiaInline,)
    filter_horizontal = ('categoria',)
    # search_fields = ('username',)
    ordering = ('creado',)
    actions = ["activar_noticia"]

    def get_actions(self, request):#eliminar la accion de eliminar
        actions = super().get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

    def activar_noticia(self, request, queryset):#acciones masivas
        queryset.update(is_active=True)

admin.site.register(CategoriaNoticia)
admin.site.register(Noticia,NoticiaAdmin)
# admin.site.register(FotoNoticia)


#!/usr/bin/env python
# encoding: utf-8
r"""
Routines for reading and writing a NetCDF output file

Routines for reading and writing a NetCDF output file via either
    - netcdf4-python - http://code.google.com/p/netcdf4-python/
    - pupynere - http://pypi.python.org/pypi/pupynere/

These interfaces are very similar so if a different module needs to be used,
it can more than likely be inserted with a minimal of effort.

This module will first try to import the netcdf4-python module which is based
on the compiled libraries and failing that will attempt to import the pure
python interface pupynere which requires no libraries.

To install the netCDF 4 library, please see:
    http://www.unidata.ucar.edu/software/netcdf/

:Authors:
    Kyle T. Mandli (2009-02-17) Initial version
"""
# ============================================================================
#      Copyright (C) 2009 Kyle T. Mandli <mandli@amath.washington.edu>
#
#  Distributed under the terms of the Berkeley Software Distribution (BSD)
#  license
#                     http://www.opensource.org/licenses/
# ============================================================================

import os,sys
import logging

import clawpack.pyclaw.solution

logger = logging.getLogger('pyclaw.fileio')

# Import appropriate netcdf package
use_netcdf4 = False
use_pupynere = False
try:
    import netCDF4
    use_netcdf4 = True
except:
    pass
if not use_netcdf4:
    try:
        import pupynere
        use_pupynere = True
    except:
        error_msg = ("Could not import netCDF4 or Pupynere, please install " +
            "one of the available modules for netcdf files.  Refer to this " +
            "modules doc_string for more information.")
        #raise Exception(error_msg)
        print(error_msg)

def write(solution,frame,path,file_prefix='claw',write_aux=False,
                    options={},write_p=False):
    r"""
    Write out a NetCDF data file representation of solution

    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Pyclaw object to be
       output
     - *frame* - (int) Frame number
     - *path* - (string) Root path
     - *file_prefix* - (string) Prefix for the file name. ``default = 'claw'``
     - *write_aux* - (bool) Boolean controlling whether the associated
       auxiliary array should be written out. ``default = False``
     - *options* - (dict) Optional argument dictionary, see
       `NetCDF Option Table`_

    .. _`NetCDF Option Table`:

    +-------------------------+----------------------------------------------+
    | Key                     | Value                                        |
    +=========================+==============================================+
    | description             | Dictionary of key/value pairs that will be   |
    |                         | attached to the root group as attributes,    |
    |                         | i.e. {'time':3}                              |
    +-------------------------+----------------------------------------------+
    | format                  | Can be one of the following netCDF flavors:  |
    |                         | NETCDF3_CLASSIC, NETCDF3_64BIT,              |
    |                         | NETCDF4_CLASSIC, and NETCDF4                 |
    |                         | ``default = NETCDF4``                        |
    +-------------------------+----------------------------------------------+
    | clobber                 | if True (Default), file will be overwritten, |
    |                         | if False an exception will be raised         |
    +-------------------------+----------------------------------------------+
    | zlib                    | if True, data assigned to the Variable       |
    |                         | instance is compressed on disk.              |
    |                         | ``default = False``                          |
    +-------------------------+----------------------------------------------+
    | complevel               | the level of zlib compression to use (1 is   |
    |                         | the fastest, but poorest compression, 9 is   |
    |                         | the slowest but best compression).  Ignored  |
    |                         | if zlib=False.  ``default = 6``              |
    +-------------------------+----------------------------------------------+
    | shuffle                 | if True, the HDF5 shuffle filter is applied  |
    |                         | to improve compression. Ignored if           |
    |                         | zlib=False. ``default = True``               |
    +-------------------------+----------------------------------------------+
    | fletcher32              | if True (default False), the Fletcher32      |
    |                         | checksum algorithm is used for error         |
    |                         | detection.                                   |
    +-------------------------+----------------------------------------------+
    | contiguous              | if True (default False), the variable data   |
    |                         | is stored contiguously on disk.  Setting to  |
    |                         | True for a variable with an unlimited        |
    |                         | dimension will trigger an error.             |
    |                         | ``default = False``                          |
    +-------------------------+----------------------------------------------+
    | chunksizes              | Can be used to specify the HDF5 chunksizes   |
    |                         | for each dimension of the variable. A        |
    |                         | detailed discussion of HDF chunking and I/O  |
    |                         | performance is available here. Basically,    |
    |                         | you want the chunk size for each dimension   |
    |                         | to match as closely as possible the size of  |
    |                         | the data block that users will read from the |
    |                         | file. chunksizes cannot be set if            |
    |                         | contiguous=True.                             |
    +-------------------------+----------------------------------------------+
    | least_significant_digit | If specified, variable data will be          |
    |                         | truncated (quantized). In conjunction with   |
    |                         | zlib=True this produces 'lossy', but         |
    |                         | significantly more efficient compression.    |
    |                         | For example, if least_significant_digit=1,   |
    |                         | data will be quantized using around          |
    |                         | (scale*data)/scale, where scale = 2**bits,   |
    |                         | and bits is determined so that a precision   |
    |                         | of 0.1 is retained (in this case bits=4).    |
    |                         | ``default = None``, or no quantization.      |
    +-------------------------+----------------------------------------------+
    | endian                  | Can be used to control whether the data is   |
    |                         | stored in little or big endian format on     |
    |                         | disk. Possible values are little, big or     |
    |                         | native (default). The library will           |
    |                         | automatically handle endian conversions when |
    |                         | the data is read, but if the data is always  |
    |                         | going to be read on a computer with the      |
    |                         | opposite format as the one used to create    |
    |                         | the file, there may be some performance      |
    |                         | advantage to be gained by setting the        |
    |                         | endian-ness.                                 |
    +-------------------------+----------------------------------------------+
    | fill_value              | If specified, the default netCDF _FillValue  |
    |                         | (the value that the variable gets filled     |
    |                         | with before any data is written to it) is    |
    |                         | replaced with this value. If fill_value is   |
    |                         | set to False, then the variable is not       |
    |                         | pre-filled.                                  |
    +-------------------------+----------------------------------------------+

    .. note::
        The zlib, complevel, shuffle, fletcher32, contiguous, chunksizes and
        endian keywords are silently ignored for netCDF 3 files that do not
        use HDF5.

    """

    # Option parsing
    option_defaults = {'format':'NETCDF4','zlib':False,'complevel':6,
                       'shuffle':True,'fletcher32':False,'contiguous':False,
                       'chunksizes':None,'endian':'native',
                       'least_significant_digit':None,'fill_value':None,
                       'clobber':True,'description':{}}
    for (k,v) in option_defaults.items():
        if k in options:
            exec("%s = options['%s']" % (k,k))
        else:
            exec('%s = v' % k)

    # Filename
    filename = os.path.join(path,"%s%s.nc" % (file_prefix,str(frame).zfill(4)))

    if use_netcdf4:
        # Open new file
        f = netCDF4.Dataset(filename,'w',clobber=clobber,format=format)

        # Loop through description dictionary and add the attributes to the
        # root group
        for (k,v) in description.items():
            exec('f.%s = %s' % (k,v))

        # For each patch, write out attributes
        for state in solution.states:
            patch = solution.patch
            # Create group for this patch
            subgroup = f.createGroup('patch%s' % patch.patch_index)

            # General patch properties
            for attr in ['t','num_eqn']:
                setattr(subgroup,attr,getattr(state,attr))
            for attr in ['patch_index','level']:
                setattr(subgroup,attr,getattr(patch,attr))

            # Write out dimension names
            setattr(subgroup,'dim_names',patch.name)

            # Create dimensions for q (and aux)
            for dim in patch.dimensions:
                subgroup.createDimension(dim.name,dim.num_cells)
                # Write other dimension attributes
                for attr in ['num_cells','lower','delta','upper','bc_lower',
                             'bc_upper','units']:
                    if hasattr(dim,attr):
                        if getattr(dim,attr) is not None:
                            attr_name = '%s.%s' % (dim.name,attr)
                            setattr(subgroup,attr_name,getattr(dim,attr))
            subgroup.createDimension('num_eqn',state.num_eqn)

            # Write q array
            from copy import copy
            dim_names = copy(patch.name)
            dim_names.append('num_eqn')
            index_str = ','.join( [':' for name in dim_names] )
            q = subgroup.createVariable('q','f8',dim_names,zlib,
                                            complevel,shuffle,fletcher32,
                                            contiguous,chunksizes,endian,
                                            least_significant_digit,fill_value)
            exec("q[%s] = state.q" % index_str)

            # Write out aux
            if state.num_aux > 0 and write_aux:
                dim_names[-1] = 'num_aux'
                subgroup.createDimension('num_aux',state.num_aux)
                aux = subgroup.createVariable('aux','f8',dim_names,
                                            zlib,complevel,shuffle,fletcher32,
                                            contiguous,chunksizes,endian,
                                            least_significant_digit,fill_value)
                exec("aux[%s] = state.aux" % index_str)

        f.close()
    elif use_pupynere:
        logging.critical("Pupynere support has not been implemented yet.")
        raise IOError("Pupynere support has not been implemented yet.")
    else:
        err_msg = "No netcdf python modules available."
        logging.critical(err_msg)
        raise Exception(err_msg)

def read(solution,frame,path='./',file_prefix='claw',read_aux=True,
                options={}):
    r"""
    Read in a NetCDF data files into solution

    :Input:
     - *solution* - (:class:`~pyclaw.solution.Solution`) Pyclaw object to be
       output
     - *frame* - (int) Frame number
     - *path* - (string) Root path
     - *file_prefix* - (string) Prefix for the file name.  ``default = 'claw'``
     - *write_aux* - (bool) Boolean controlling whether the associated
       auxiliary array should be written out.  ``default = False``
     - *options* - (dict) Optional argument dictionary, unused for reading.
    """

    # Option parsing
    option_defaults = {}
    for (k,v) in option_defaults.items():
        if k in options:
            exec("%s = options['%s']" % (k,k))
        else:
            exec('%s = v' % k)

    # Filename
    filename = os.path.join(path,"%s%s.nc" % (file_prefix,str(frame).zfill(4)))

    if use_netcdf4:
        # Open file
        f = netCDF4.Dataset(filename,'r')

        # We only expect subgroups of patches, otherwise we need to put some
        # sort of conditional here
        for subgroup in f.groups.values():
            # Construct each dimension
            dimensions = []

            # Read in dimension attribute to keep dimension order
            dim_names = getattr(subgroup,'dim_names')
            for dim_name in dim_names:
                dim = pyclaw.solution.Dimension(
                                      getattr(subgroup,'%s.lower' % dim_name),
                                      getattr(subgroup,'%s.upper' % dim_name),
                                      getattr(subgroup,'%s.n' % dim_name),
                                      name = dim_name)
                 # Optional attributes
                for attr in ['bc_lower','bc_upper','units']:
                    attr_name = "%s.%s" % (dim_name,attr)
                    if hasattr(subgroup,attr_name):
                        setattr(dim,attr,getattr(subgroup, "%s.%s" % (dim_name,attr)))
                dimensions.append(dim)

            # Create patch
            patch = pyclaw.solution.Patch(dimensions)

            # General patch properties
            for attr in ['t','num_eqn','patch_index','level']:
                setattr(patch,attr,getattr(subgroup,attr))

            # Read in q
            index_str = ','.join( [':' for i in range(patch.num_dim+1)] )
            exec("patch.q = subgroup.variables['q'][%s]" % index_str)

            # Read in aux if applicable
            if read_aux and 'num_aux' in subgroup.dimensions:
                exec("patch.aux = subgroup.variables['aux'][%s]" % index_str)

            solution.patches.append(patch)

        f.close()
    elif use_pupynere:
        logging.critical("Pupynere support has not been implemented yet.")
        raise IOError("Pupynere support has not been implemented yet.")
    else:
        err_msg = "No netcdf python modules available."
        logging.critical(err_msg)
        raise Exception(err_msg)


from django.urls import path
from core import views as v

urlpatterns = [
    path('', v.home, name='core_home'),
    path('pessoas/', v.lista_pessoas, name='core_lista_pessoas'),
    path('pessoas/criar', v.criar_pessoas, name='core_criar_pessoas'),
    path('pessoas/update/<int:id>', v.update_pessoa, name='core_update_pessoa'),
    path('pessoas/delete/<int:id>', v.delete_pessoa, name='core_delete_pessoa'),

    path('veiculos/', v.lista_veiculos, name='core_lista_veiculos'),
    path('veiculos/criar', v.criar_veiculos, name='core_criar_veiculos'),
    path('veiculos/update/<int:id>', v.update_veiculo, name='core_update_veiculo'),
    path('veiculos/delete/<int:id>', v.delete_veiculo, name='core_delete_veiculo'),

    path('mov-rot/', v.lista_movrotativo, name='core_lista_movrotativo'),
    path('mov-rot/criar', v.criar_movrotativo, name='core_criar_movrotativo'),
    path('mov-rot/update/<int:id>', v.update_movrotativo, name='core_update_movrotativo'),
    path('mov-rot/delete/<int:id>', v.delete_movrotativo, name='core_delete_movrotativo'),

    path('mensalistas/', v.lista_mensalista, name='core_lista_mensalista'),
    path('mensalistas/criar', v.criar_mensalista, name='core_criar_mensalista'),
    path('mensalistas/update/<int:id>', v.update_mensalista, name='core_update_mensalista'),
    path('mensalistas/delete/<int:id>', v.delete_mensalista, name='core_delete_mensalista'),

    path('mov-mens/', v.lista_movmensalista, name='core_lista_movmensalista'),
    path('mov-mens/criar', v.criar_movmensalista, name='core_criar_movmensalista'),
    path('mov-mens/update/<int:id>', v.update_movmensalista, name='core_update_movmensalista'),
    path('mov-mens/delete/<int:id>', v.delete_movmensalista, name='core_delete_movmensalista')
]


import json
import requests
from collections import Counter

def numberOfDates(data):
	counter = 0
	for key in data:
		counter += 1
	return counter

def findTop5Highest(data):
	num = numberOfDates(data)
	k = Counter(data)
	printCounter = num

	if num < 5:
		high = k.most_common(num)
	else:
		high = k.most_common(5)
		printCounter = 5

	highDict = {}

	for i in high:
		highDict[i[0]] = i[1]

	return highDict

def feelingNumber(feeling):

	if feeling == 'Fantastic':
		return 100

	elif feeling == 'Ok':
		return 50

	elif feeling == 'Frustrated':
		return 0

def getFinalValues(feelingsCompare, dataDict):

	num = numberOfDates(feelingsCompare)
	tempAverage = 0
	noiseAverage = 0
	humiAverage = 0
	brightAverage = 0

	for key in feelingsCompare:
		tempAverage += dataDict[key]['tempAverage']
		noiseAverage += dataDict[key]['noiseAverage']
		humiAverage += dataDict[key]['humiAverage']
		brightAverage += dataDict[key]['brightAverage']

	tempAverage /= num
	noiseAverage /= num
	humiAverage /= num
	brightAverage /= num

	tempAverage = round(tempAverage, 2)
	noiseAverage = round(noiseAverage, 2)
	humiAverage = round(humiAverage, 2)
	brightAverage = round(brightAverage, 2)

	finalDict = {
		"tempAverage": tempAverage,
		"humiAverage": humiAverage,
		"noiseAverage": noiseAverage,
		"brightAverage":brightAverage
	}

	return finalDict

def calculate_function(feelings, data):

	feelingsDict = {}
	feelingsTop = {}
	dataDict = {}

	for line in feelings:
		jsonTemp = line
		keyTemp = jsonTemp['time']['date']
		if keyTemp in feelingsDict.keys():
			feelingsDict[keyTemp]['value'] += feelingNumber(jsonTemp['feeling'])
			feelingsDict[keyTemp]['people'] += 1
		else:
			feelingsDict[keyTemp] = {}
			feelingsDict[keyTemp]['value'] = feelingNumber(jsonTemp['feeling'])
			feelingsDict[keyTemp]['people'] = 1

	for key in feelingsDict:
		feelingsTop[key] = feelingsDict[key]['value']/feelingsDict[key]['people']

	for line in data:
		jsonTemp = line
		keyTemp = jsonTemp['time']['date']
		if keyTemp in dataDict.keys():
			dataDict[keyTemp]['counter'] += 1
			dataDict[keyTemp]['temperature'] += jsonTemp['temperature']
			dataDict[keyTemp]['humidity'] += jsonTemp['humidity']
			dataDict[keyTemp]['noise'] += jsonTemp['noise']
			dataDict[keyTemp]['brightness'] += jsonTemp['brightness']
		else:
			dataDict[keyTemp] = {}
			dataDict[keyTemp]['counter'] = 1
			dataDict[keyTemp]['temperature'] = jsonTemp['temperature']
			dataDict[keyTemp]['humidity'] = jsonTemp['humidity']
			dataDict[keyTemp]['noise'] = jsonTemp['noise']
			dataDict[keyTemp]['brightness'] = jsonTemp['brightness']

	for key in dataDict:
		dataDict[key]['tempAverage'] = dataDict[key]['temperature']/dataDict[key]['counter']
		dataDict[key]['humiAverage'] = dataDict[key]['humidity']/dataDict[key]['counter']
		dataDict[key]['noiseAverage'] = dataDict[key]['noise']/dataDict[key]['counter']
		dataDict[key]['brightAverage'] = dataDict[key]['brightness']/dataDict[keyTemp]['counter']

	feelingsCompare = findTop5Highest(feelingsTop)

	print(json.dumps(getFinalValues(feelingsCompare, dataDict)))

feelings = requests.post('http://192.168.1.27:3000/feeling/getAll')
feelingsJSON = feelings.json()

data = requests.post('http://192.168.1.27:3000/data/getData')
dataJSON = data.json()

calculate_function(feelingsJSON, dataJSON)


"""Adds edges between family members at the same address."""

import six

from . import entity_tools
from . import graph_tools
from . import utils

# Edges between neighbours are added only if the number of entities
# at a particular address is at most `MAX_NEIGHBOUR_GROUP_SIZE`:
MAX_NEIGHBOUR_GROUP_SIZE = 2

# String to prefix log messages with:
LOG_PREFIX = '[post_process_neighbours] '

def _are_surnames_similar(surname1, surname2):
    """Decides if two surnames are similar enough to be family."""

    if (not surname1) or (not surname2):
        return False

    # TODO(matejbalog): Consider normalising by removing accents and
    # capitalisation.

    if surname1 == surname2:
        return True

    # Decide based on the length of the longest common prefix:
    lcp = utils.longest_common_prefix(surname1, surname2)
    if (lcp >= 3 and lcp >= len(surname1) - 3 and
            lcp >= len(surname2) - 1 and surname1[-1] in ['a', '\xe1']):
        return True
    if (lcp >= 3 and lcp >= len(surname1) - 1 and
            lcp >= len(surname2) - 3 and surname2[-1] in ['a', '\xe1']):
        return True

    return False

def add_family_and_neighbour_edges(db, test_mode):
    """Adds edges between family members and close neighbours.

    Creates two new edge types and adds the corresponding edges:
    (1) "family": Links any two entities at the same address with
        "sufficiently" similar surnames (as determined by the function
        `_are_surnames_similar` above).
    (2) "neighbours": Links any two entities at the same address, as
        long as there are at most MAX_NEIGHBOUR_GROUP_SIZE entities at
        that address.
    """

    # Load surnames and academic titles:
    surnames = entity_tools.get_surnames()
    titles_parser = entity_tools.get_academic_titles_parser()

    # Compute mapping from eids to parsed entity names:
    parsed_name = {}
    suffix = ' LIMIT 50000;' if test_mode else ';'
    query = 'SELECT id, name FROM entities' + suffix
    with db.get_server_side_cursor(query) as cur:
        for eid, name in cur:
            parsed = entity_tools.parse_entity_name(
                name, titles_parser, surnames, verbose=False)
            if parsed:
                parsed_name[eid] = parsed

    # Initialise edges:
    edges_family = []
    edges_neighbours = []

    # Iterate through entity groups sharing the same Address:
    suffix = " LIMIT 50000;" if test_mode else ";"
    cur = db.get_server_side_cursor("""
        SELECT array_agg(id) as eids
        FROM entities
        GROUP BY address_id
        """ + suffix, buffer_size=10000)

    # Iterate through entity groups sharing the same Address:
    for row in cur:
        eids = row[0]

        # Iterate through distinct pairs of entities in this group:
        group_size = len(eids)
        for i in six.moves.range(group_size):
            # Add family edges:
            if eids[i] in parsed_name:
                for j in six.moves.range(i + 1, group_size):
                    if eids[j] in parsed_name:
                        if _are_surnames_similar(
                                parsed_name[eids[i]].surname,
                                parsed_name[eids[j]].surname):
                            edges_family.append((eids[i], eids[j]))
                            edges_family.append((eids[j], eids[i]))

            # Add neighbour edges:
            if group_size <= MAX_NEIGHBOUR_GROUP_SIZE:
                for j in range(i + 1, group_size):
                    edges_neighbours.append((eids[i], eids[j]))
                    edges_neighbours.append((eids[j], eids[i]))

    cur.close()
    print('%sAccumulated %d family edges and %d neighbour edges' % (LOG_PREFIX, len(edges_family), len(edges_neighbours)))

    # Get edge type indices for the new edge types:
    edge_type_family = graph_tools.add_or_get_edge_type(
        db, "Zhoda v priezvisku a adrese", LOG_PREFIX)
    edge_type_neighbour = graph_tools.add_or_get_edge_type(
        db, "Susedia", LOG_PREFIX)

    # Remove any existing edges of these edge types:
    q_data = [edge_type_family, edge_type_neighbour]
    db.execute("""
        DELETE FROM related
        WHERE stakeholder_type_id=%s OR stakeholder_type_id=%s;
        """, q_data)
    print("%sRemoved any existing edges of types %s" % (LOG_PREFIX, q_data))

    # Insert the new edges:
    with db.cursor() as cur:
        q = """
        INSERT INTO related(eid, eid_relation, stakeholder_type_id)
        VALUES (%s, %s, %s);
        """
        q_data = [(source, target, edge_type_family)
                  for source, target in edges_family]
        cur.executemany(q, q_data)
        q_data = [(source, target, edge_type_neighbour)
                  for source, target in edges_neighbours]
        cur.executemany(q, q_data)


import folium

def map_creation(df_static,geo_json_data):
    #json file with the coordinates of each commune in France imported as dataframe
    #capitalized everything because it is case sensitive
    geo_json_data['libgeo'] = geo_json_data['libgeo'].str.upper()

    commune_avg = df_static.groupby('Nom de la commune', as_index=False)['Consommation annuelle moyenne de la commune (MWh)'].mean()
    commune_avg['Nom de la commune'] = commune_avg['Nom de la commune'].str.upper()

    #creating the dataframe that only contains the communes in both dataframes with their coordinates and consumption rates
    geo_json_data=geo_json_data.loc[:,('libgeo','geometry')]
    df_final = geo_json_data.merge(commune_avg, left_on='libgeo', right_on='Nom de la commune',how='outer')
    df_final = df_final.dropna()

    #adding our data to the map
    mymap = folium.Map(location=[46.2276,2.2137], zoom_start=5.5)
    mymap.choropleth(
        geo_data=geo_json_data,
        name='Communes',
        data=commune_avg,
        columns=['Nom de la commune','Consommation annuelle moyenne de la commune (MWh)'],
        key_on="feature.properties.libgeo",
        fill_color='YlGnBu', nan_fill_color="#FF000000",
        fill_opacity=1,
        line_opacity=0.2,
        legend_name='Consommation moyenne des 4 dernières années (MWh)',
        smooth_factor=0
        )

    #designing our interactive map
    style_function = lambda x: {'fillColor': '#ffffff',
                            'color':'#000000',
                            'fillOpacity': 0.1,
                            'weight': 0.1}
    highlight_function = lambda x: {'fillColor': '#000000',
                                'color':'#000000',
                                'fillOpacity': 0.50,
                                'weight': 0.1}

    #adding our interactive features
    folium.features.GeoJson(
        data=df_final,
        style_function=style_function,
        control=False,
        highlight_function=highlight_function,
        tooltip=folium.features.GeoJsonTooltip(
            fields=['Nom de la commune','Consommation annuelle moyenne de la commune (MWh)'],
            aliases=['Neighborhood: ','Resident foreign population in %: '],
            style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;"),
            localize=True,
            sticky=True,
            labels=True,
            )
        ).add_to(mymap)
    folium.LayerControl().add_to(mymap)
    return(mymap)


import argparse
import os
import sys

from . import client, message_variables

DEFAULT_RUN_MESSAGE = "Run triggered by `tfc` command line tool"

class MessageVariableMapping:
    """
    Wrapper for the tfc.message_variables module

    Wraps the tfc.message_variables module in a mapping (dictionary like) interface. The name of
    each function in tfc.message_variables becomes a key in the mapping and the value is the result
    of running that function with no arguments.

    This wrapper effectively allows us to lazily pass all of the results from the functions in
    tfc.message_variables into str.format() (i.e. without running functions which are not used by
    the format string)
    """

    def __getitem__(self, key):
        func = getattr(message_variables, key)
        if getattr(func, "is_message_variable", False):
            return func()
        else:
            raise KeyError(key)

def trigger_run_with_variables(organization, workspace, message, assignments):
    token = os.environ["TERRAFORM_CLOUD_TOKEN"]
    terraform = client.TerraformClient(token, organization, workspace)
    vars = terraform.get_variables()

    for (variable_name, new_value) in assignments.items():
        variable = vars[variable_name]
        terraform.update_variable(variable.id, new_value)
        old_value = variable.value
        print(f"Updated {variable_name!r} from {old_value!r} to {new_value!r}")

    run = terraform.create_run(message)
    print(f"Created run {run.id} - check status at: {run.url}")

def variable_assignment(value):
    if "=" not in value:
        raise argparse.ArgumentTypeError(
            f"Expected an assignment with an equals sign, got {value!r}"
        )
    return value

def get_command_line_arguments(argv):
    parser = argparse.ArgumentParser(
        description="Trigger a Terraform Cloud run",
        epilog="Put your API token in the TERRAFORM_CLOUD_TOKEN environment variable",
    )
    parser.add_argument("organization", help="The name of your organization in Terraform Cloud")
    parser.add_argument("workspace", help="The name of your workspace in Terraform Cloud")
    parser.add_argument(
        "variables",
        metavar="name=value",
        type=variable_assignment,
        nargs="*",
        help="Set terraform variable NAME to VALUE before creating the run",
    )
    parser.add_argument(
        "--message",
        "-m",
        help="The message to be associated with this run",
        default=DEFAULT_RUN_MESSAGE,
    )

    args = parser.parse_args(argv[1:])
    args.variables = dict([v.split("=", 1) for v in args.variables])
    return args

def main(argv=sys.argv):
    """The entry point when running `tfc` as a script"""
    args = get_command_line_arguments(argv)
    message = args.message.format_map(MessageVariableMapping())
    trigger_run_with_variables(args.organization, args.workspace, message, args.variables)
    return 0


from functools import reduce
from typing import Any, List, Mapping, Optional, Set

import dpath.util
import pendulum

class CatalogField:
    """Field class to represent cursor/pk fields"""

    def __init__(self, schema: Mapping[str, Any], path: List[str]):
        self.schema = schema
        self.path = path
        self.formats = self._detect_formats()

    def _detect_formats(self) -> Set[str]:
        """Extract set of formats/types for this field"""
        format_ = []
        try:
            format_ = self.schema.get("format", self.schema["type"])
            if not isinstance(format_, List):
                format_ = [format_]
        except KeyError:
            pass
        return set(format_)

    def _parse_value(self, value: Any) -> Any:
        """Do actual parsing of the serialized value"""
        if self.formats.intersection({"datetime", "date-time", "date"}):
            if value is None and "null" not in self.formats:
                raise ValueError(f"Invalid field format. Value: {value}. Format: {self.formats}")
            # handle beautiful MySQL datetime, i.e. NULL datetime
            if value.startswith("0000-00-00"):
                value = value.replace("0000-00-00", "0001-01-01")
            return pendulum.parse(value)
        return value

    def parse(self, record: Mapping[str, Any], path: Optional[List[str]] = None) -> Any:
        """Extract field value from the record and cast it to native type"""
        path = path or self.path
        value = reduce(lambda data, key: data[key], path, record)
        return self._parse_value(value)

class JsonSchemaHelper:
    def __init__(self, schema):
        self._schema = schema

    def get_ref(self, path: List[str]):
        node = self._schema
        for segment in path.split("/")[1:]:
            node = node[segment]
        return node

    def get_property(self, path: List[str]) -> Mapping[str, Any]:
        node = self._schema
        for segment in path:
            if "$ref" in node:
                node = self.get_ref(node["$ref"])
            node = node["properties"][segment]
        return node

    def field(self, path: List[str]) -> CatalogField:
        return CatalogField(schema=self.get_property(path), path=path)

    def find_variant_paths(self) -> List[List[str]]:
        """
        return list of json object paths for oneOf or anyOf attributes
        """
        variant_paths = []

        def traverse_schema(_schema, path=[]):
            if path and path[-1] in ["oneOf", "anyOf"]:
                variant_paths.append(path)
            for item in _schema:
                next_obj = _schema[item] if isinstance(_schema, dict) else item
                if isinstance(next_obj, (list, dict)):
                    traverse_schema(next_obj, [*path, item])

        traverse_schema(self._schema)
        return variant_paths

    def validate_variant_paths(self, variant_paths: List[List[str]]):
        """
        Validate oneOf paths according to reference
        https://docs.airbyte.io/connector-development/connector-specification-reference
        """

        def get_top_level_item(variant_path: List[str]):
            # valid path should contain at least 3 items
            path_to_schema_obj = variant_path[:-1]
            return dpath.util.get(self._schema, "/".join(path_to_schema_obj))

        for variant_path in variant_paths:
            top_level_obj = get_top_level_item(variant_path)
            if "$ref" in top_level_obj:
                obj_def = top_level_obj["$ref"].split("/")[-1]
                top_level_obj = self._schema["definitions"][obj_def]
            """
            1. The top-level item containing the oneOf must have type: object
            """
            assert (
                top_level_obj.get("type") == "object"
            ), f"The top-level definition in a `oneOf` block should have type: object. misconfigured object: {top_level_obj}. See specification reference at https://docs.airbyte.io/connector-development/connector-specification-reference"
            """

            2. Each item in the oneOf array must be a property with type: object
            """
            variants = dpath.util.get(self._schema, "/".join(variant_path))
            for variant in variants:
                assert (
                    "properties" in variant
                ), "Each item in the oneOf array should be a property with type object. See specification reference at https://docs.airbyte.io/connector-development/connector-specification-reference"

            """
             3. One string field with the same property name must be
             consistently present throughout each object inside the oneOf
             array. It is required to add a const value unique to that oneOf
             option.
            """
            variant_props = [set(list(v["properties"].keys())) for v in variants]
            common_props = set.intersection(*variant_props)
            assert common_props, "There should be at least one common property for oneOf subojects"
            assert any(
                [all(["const" in var["properties"][prop] for var in variants]) for prop in common_props]
            ), f"Any of {common_props} properties in {'.'.join(variant_path)} has no const keyword. See specification reference at https://docs.airbyte.io/connector-development/connector-specification-reference"


import os
import glob
import torch.utils.data
import numpy as np

class RGBImageSet(torch.utils.data.Dataset):
    def __init__(self, path, centered=False):
        super().__init__()
        self.centered = centered
        self.add_string = lambda a, b: a + b

        assert os.path.exists(path)
        self.base_path = path

        self.mean_image = self.get_mean_image()

        cur_file_paths = glob.glob(self.base_path + '/*.npy')
        cur_file_paths.sort()
        self.file_paths = cur_file_paths

    def __len__(self):
        return len(self.file_paths)

    def __getitem__(self, item):
        data = np.load(self.file_paths[item])
        data = np.transpose(data, (2, 0, 1))
        # (h w c) => (c h w)

        if data.dtype.name == 'uint8':
            data = data.astype(float)

        if self.centered:
            data = torch.FloatTensor(data)
        else:
            data = torch.FloatTensor(data)
            data = data - self.mean_image
            data.div_(255)
        return data

    def get_decenterd_data(self, centered_data):
        result = centered_data.mul_(255) + self.mean_image
        result = result.byte()
        return result

    def get_mean_image(self):
        mean_image = np.load(os.path.join(os.path.dirname(self.base_path), "mean_image.npy"))
        mean_image = np.transpose(mean_image, (2, 0, 1))
        mean_image = torch.from_numpy(mean_image).float()
        return mean_image


import autokeras as ak
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler, RobustScaler
##
# Load and preprocess the data
train_csv = pd.read_csv('d:/study/_data/dacon_diabetes/train.csv', index_col=0)
train_csv = train_csv.dropna()
x = train_csv.drop(['Outcome'], axis=1)
y = train_csv['Outcome']
scaler = MinMaxScaler()
x = scaler.fit_transform(x)
x_train, x_test, y_train, y_test = train_test_split(x, y, shuffle=True, train_size=0.7, random_state=777)
scaler = RobustScaler()
x_train = scaler.fit_transform(x_train)
x_test = scaler.transform(x_test)

# Train the model
model = ak.StructuredDataClassifier(overwrite=False, max_trials=2)
model.fit(x_train, y_train, epochs=10, validation_split=0.15)

# Export and save the best model
best_model = model.export_model()
best_model.save('path_to_save_model', save_format='tf')

# Evaluate the model
y_predict = model.predict(x_test)
results = model.evaluate(x_test, y_test)
print('Model results:', results)


import math, random, sys, pygame, os, time, argparse
from pygame.locals import *
from agent import Agent
from part import Part
from objects import Object
from network_collection import NetworkCollection
from tab import Tab
from options import Options
from log import Log
from random import *

# Main Class. This runs the application and updates the UI
class Main():

	def __init__(self):
		# Initialise variables and randomly generate ane nvironment
		self.initialize_variables()
		self.generate_world()
		# Update display
		self.update_display = True

		# main loop
		while True:
			# Check for inputs
			self.check_inputs()
			# If not paused
			if not self.paused:
				# If a run is ongoing
				if self.running:
					# Different modes
					if self.training:
						self.training_mode()
					else:
						self.free_mode()
				# Update environment objects positions
				self.move_environment()
				# Update the display if the user chooses too
				# Program runs faster when it is off
				if self.update_display:
					self.draw_sprites()

	def initialize_variables(self):
		# define display surface
		self.dimensions = (1080, 600)
		# Initial parameters
		self.subsumption = True
		self.episode_num = 0
		self.extra = False
		self.agent_num = 0
		self.placing_object = False
		self.rotate_unplaced = 0
		self.continuous = True
		self.draw_goal = False
		self.wolf = True
		self.randomness = 5
		self.reference = 20
		self.draw_scaleable = False
		self.display = [False, False, False]
		self.training = False
		self.running = False
		self.custom_build = False
		self.paused = False
		self.agents_to_be_added = []

		# Backgrounds colour
		self.background = (0, 153, 255, 221)

		# Keeps track of the winrate across training stages
		self.win_counter = 0
		self.network_collection = NetworkCollection()
		# Place window in the center of the screen
		os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (150,80)
		# initialise display
		pygame.init()
		self.clock = pygame.time.Clock()
		self.canvas = pygame.display.set_mode(self.dimensions)
		pygame.display.set_caption("Intelligent Agent Structures")
		# Create a font used to write on the screen
		pygame.font.init()
		self.font = pygame.font.SysFont('arial', 12)
		self.font.set_bold(True)

		# Get the image resources for the world
		self.pointers = [None, None]
		self.pointers[0] = pygame.image.load("image_resources/pointer_alt.png").convert_alpha()
		self.pointers[1] = pygame.image.load("image_resources/pointer.png").convert_alpha()

		# array containing the environments current blocks and agents
		self.blocks, self.agents = [],[]
		# Adds agents into the world
		self.floor = Object(0, (0, 400))
		self.floor.load_image("image_resources/flat_floor.png")

		# File paths for the block images
		self.block_images = ["300x200","200x600","400x400","200x200","goal","goal_flipped"]

		# UI Tabs for environment modification, output log and controls
		self.tabs = []
		self.tabs.append(Options(0, self))
		self.tabs.append(Log(1, self.font, self))
		self.tabs.append(Tab(2))

		# Static agents used in the final training stage
		self.scaleable_agents = []
		preset_rotations = [44,0,270,90,90,90,0,0,0,90,90,90,0,0,0]
		self.scaleable_agents.append(Agent((582,339), self.network_collection, 0, None, 25, False, self.randomness, self.subsumption))
		self.scaleable_agents.append(Agent((667,339), self.network_collection, 0, None, 25, False, self.randomness, self.subsumption))
		self.scaleable_agents.append(Agent((667,304), self.network_collection, 0, None, 25, False, self.randomness, self.subsumption))
		for i in range(3):
			self.scaleable_agents[i].parts.set_rotations(preset_rotations)
		# Rounds won/lost
		self.won = 0
		self.lost = 0

	# Check computer inputs
	def check_inputs(self):
		# Event Listener
		for event in pygame.event.get():
			# On quit event quit game
			if event.type == QUIT:
				pygame.quit()
				sys.exit()
			elif event.type == KEYDOWN:
				# Start run
				if event.key == K_RETURN:
					self.running = True
				# End run / Reset environment
				elif event.key == K_ESCAPE:
					self.reset_environment()
				# Rotate block clockwise and anti clockwise
				elif event.key == K_q:
					self.rotate_unplaced += 1
				elif event.key == K_e:
					self.rotate_unplaced += -1
				# Update display
				elif event.key == K_u:
					self.update_display = not self.update_display
				# Play / Pause
				elif event.key == K_p:
					self.paused = not self.paused
			elif event.type == KEYUP:
				# Stop rotating block
				if event.key == K_e:
					self.rotate_unplaced += 1
				elif event.key == K_q:
					self.rotate_unplaced += -1
			# On mouse click check which button was pressed
			elif event.type == pygame.MOUSEBUTTONDOWN and not self.paused:
				self.pos = pygame.mouse.get_pos()
				# If an object is being held by the user place it
				if self.placing_object:
					self.place_object()
				# Check buttons
				for i in range(3):
					self.tabs[i].click(self.pos)

	# Draw sprites
	def draw_sprites(self):
		# Draw background
		self.canvas.fill(self.background)
		# Draw the goal if there is one
		if self.draw_goal:
			self.canvas.blit(self.goal.get_image(), self.goal.get_position())
		# Draw sensors if user chooses
		if self.display[1]:
			for i in range(len(self.agents)):
				self.agents[i].sensors.run(self.canvas)
		# Draw any blocks within the environment including any the user is holding
		if self.placing_object:
			self.canvas.blit(self.unplaced.get_image(), self.unplaced.get_position())
		for i in range(len(self.blocks)):
			self.canvas.blit(self.blocks[i].get_image(), self.blocks[i].get_position())
		# Draw the agents used in the final training stage
		if self.draw_scaleable:
			for i in range(len(self.scaleable_agents)):
				self.scaleable_agents[i].parts.run(self.canvas)
		# Draw the agents
		for i in range(len(self.agents)):
			self.agents[i].parts.run(self.canvas)
		# Draw the floor
		self.canvas.blit(self.floor.get_image(), self.floor.get_position())
		# Draw the agents collision points with the environment if the request it
		if self.display[0]:
			for i in range(len(self.agents)):
				markers = self.agents[i].get_box()
				for j in range(len(markers)):
					self.canvas.blit(self.pointers[1], (int(markers[j][0]), int(markers[j][1])))
		# Draw the agents center of gravity if the request it
		if self.display[2]:
			for i in range(len(self.agents)):
				cog = self.agents[i].cog
				self.canvas.blit(self.pointers[0], (int(cog[0]), int(cog[1])))
		# Draw tabs
		for i in range(3):
			self.tabs[i].run(self.canvas)
		pygame.display.update()
		# Max FPS
		self.clock.tick(120)

	# Place an object the user is holding
	def place_object(self):
		# It must overlap with the environment (No freefloating structures)
		if (self.check_environmental_overlap()):
			# Place new goal
			if self.unplaced_goal:
					self.goal = self.unplaced
					self.draw_goal = True
			# Place block
			else:
				self.blocks.append(self.unplaced)
		self.placing_object = False

	# Check if a block is overlapping with the environment (No free floating structures)
	def check_environmental_overlap(self, goal=False):
		# Compare either the goal or the block the user is currently holding
		checking = self.unplaced
		if goal:
			checking = self.goal
		# Compare against every block including the floor
		for k in range(len(self.blocks) + 1):
			comparison = None
			if k == len(self.blocks):
				comparison = [self.floor.get_position(), self.floor.get_mask()]
			else:
				comparison = [self.blocks[k].get_position(), self.blocks[k].get_mask()]

			# Find the position difference between the agent part and the external object
			offset = (int(comparison[0][0] - checking.get_position()[0]), int(comparison[0][1] - checking.get_position()[1]))
			result = checking.get_mask().overlap(comparison[1], offset)
			# If there was a collision return the collision position
			if result:
				return result[1]
		# Else return false
		return False

	# Randomly generate a new environment
	def generate_world(self):
		# Reset environment
		self.blocks = []
		self.agents = []
		self.agent_num = 0
		# Randomly place 3 blocks.
		while len(self.blocks) < 3:
			self.unplaced = Object(0, (randint(500,800), randint(0,200)))
			self.unplaced.load_image("image_resources/"+self.block_images[randint(0,3)]+".png")
			self.unplaced.rotate(randint(0,180))
			# Only keep the block if it touches the environment
			if self.check_environmental_overlap():
				self.blocks.append(self.unplaced)
		# Place goal
		self.set_goal()

	# Move an item in the environment. Either what the user it holding or a tab
	def move_environment(self):
		# User holding item
		if self.placing_object:
			self.pos = pygame.mouse.get_pos()
			if self.unplaced_goal:
				self.unplaced.set_position((self.pos[0] - 25, self.pos[1] - 25))
			else:
				self.unplaced.set_position((self.pos[0] - 200, self.pos[1] - 200))
				self.unplaced.rotate(self.rotate_unplaced)
		# Update tabs
		for i in range(3):
			self.tabs[i].move()

	# Automatically place goal in the environment
	def set_goal(self):
		# Goal is shapped like a flag. Keep trying to place goal until the attaches to the ground by the flag pole
		for i in range(10):
			# Randomly position
			x_pos = randint(850,900)
			self.goal = Object(0, (x_pos, 0))
			# Pick a direction for the goal to face. When placing on a slope means it can attach to the ground by the pole
			flipped = False
			if randint(0, 100) > 50:
				self.goal.load_image("image_resources/goal.png")
			else:
				self.goal.load_image("image_resources/goal_flipped.png")
				flipped = True
			counter = 0
			# Start the goal in the air. Keep lowering until it touches the ground
			while(not self.check_environmental_overlap(True)):
				counter += 1
				self.goal.set_position((x_pos,counter))
			# Lower the goal by 2 pixels to plant it firmly in the ground
			self.goal.set_position((x_pos,counter + 2))
			# If planted by the flag pole break otherwise try a maximum of 10 times
			if self.check_environmental_overlap(True) > 40:
				break
		self.draw_goal = True

	# Reset environment
	def reset_environment(self,  clear_world=False):
		# Reset variables
		self.running = False
		self.placing_object = False
		self.network_collection.reset_training()
		# Clear blocks and agents
		self.agents = []
		self.agent_num = 0
		self.episode_num = 0
		self.draw_scaleable = False
		if not clear_world:
			self.blocks = []
			self.draw_goal = False
		# If not custom built environments generate a new one
		if not self.custom_build:
			self.generate_world()
		self.tabs[1].write_message("Environment Reset")

	# When the user requests a block give them one
	def world_building(self, object_num):
		if not self.running and (object_num < 4 or self.draw_goal == False):
			if self.custom_build or object_num > 3:
				self.placing_object = True
				# Centered so cursor is in the middle of the image
				self.unplaced = Object(0, (self.pos[0] - 200, self.pos[1] - 200))
				self.unplaced.load_image("image_resources/"+self.block_images[object_num]+".png")
				self.unplaced_goal = (object_num > 3)

	# Training mode. Here the user performs several subtasks to train the neural network
	def training_mode(self):
		# If no agents exist create one
		if len(self.agents) == 0:
			if self.reference > 0:
				self.create_agent(290, True, True)
			else:
				self.create_agent(290, True, False)

		# Get agent
		agent = self.agents[0]
		# Get collection of neural networks
		network_collection = self.network_collection
		# Move agent
		agent.move()

		# If the agent finishes its run reset environment
		if agent.restart:
			# Did the agent win
			if agent.won:
				self.won += 1
				if self.extra:
					self.tabs[1].write_message("WON")
			else:
				self.lost += 1
				if self.extra:
					self.tabs[1].write_message("LOST")

			# Run the first 2 training stages until the networks have 20000 pieces of data.
			# Run the last 2 training stages until the networks have 50000 pieces of data.
			comparator = 50000
			if network_collection.get_turn() < 2:
				comparator = 20000

			difference = (network_collection.get_length() - (comparator * self.reference / 100))

			# If the network has enough data
			if network_collection.get_length() > comparator:
				# Move to the next step
				self.tabs[1].write_message("Training Stage " + str(network_collection.get_turn() + 1) + "/4 Complete")
				network_collection.increment_turn()
				# Generate new environment
				self.generate_world()
				# Average of the averages from each stage of training
				self.win_counter += (self.won/(self.won + self.lost))/4
				# Finish episode
				if network_collection.get_turn() == 0:
					self.tabs[1].write_message("Episode " + str(self.episode_num + 1) + " Finished")
					self.tabs[1].write_message("Training, This may take a while")
					self.draw_scaleable = False
					self.draw_sprites()
					# If using Win or Learn Fast update the learning rate
					learn_rate = network_collection.get_learn_rate()
					if self.wolf:
						learn_rate = 0.1 - (self.win_counter * 0.099)
						network_collection.update_learn_rate(learn_rate)
					# Finish episode and save network
					network_collection.finish_episode()
					network_collection.save_checkpoint()
					self.tabs[1].write_message("Network Trained With LR: " + str("%.3f" % learn_rate))

					# Reset variables
					self.episode_num += 1
					self.win_counter = 0
					preset = False

					# End run
					self.run_ended()

				# Empty environment except on the 3rd stage
				elif network_collection.get_turn() == 3:
					self.blocks = []
					self.draw_goal = False
				# Reset win/loss count
				self.won = 0
				self.lost = 0
			elif self.extra:
				self.tabs[1].write_message(str(network_collection.get_length()) + " / " + str(comparator))

			# Reset agent
			self.agents = []
			self.create_agent(290, True, (network_collection.get_length() < (comparator * self.reference / 100)))

			# On the 3rd training step spawn static training agents
			if network_collection.get_turn() == 3:
				for j in range(len(self.scaleable_agents)):
					self.agents[self.agent_num].add_other_agent(self.scaleable_agents[j])
				self.draw_scaleable = True

	# Free mode. Environment are built and agents attempt to work together to scale them
	def free_mode(self):
		# If no agents currently exist create one
		if len(self.agents) == 0:
			# If there is no goal make one
			if not self.draw_goal:
				self.set_goal()
			self.create_agent(390, False)

		# Move all the agents
		for i in range(self.agent_num + 1):
			self.agents[i].move()
			# Once an agent is confirmed to be finished add its mask to the next agent
			if self.agents[i].finished_completely:
				self.agents[i].finished_completely = False
				self.agents[self.agent_num].add_other_agent(self.agents[i])
		# If an agent requests another then spawn another agent
		if self.agents[self.agent_num].finished == 1:
			self.agents_to_be_added = [self.agent_num]
			self.agent_num += 1
			self.create_agent(100, False)
		# If the agent declares a run finished, end run
		elif self.agents[self.agent_num].finished == -1:
			if self.agents[self.agent_num].won:
				self.tabs[1].write_message("Run Finished Successfully")
			else:
				self.tabs[1].write_message("Run Failed")
			self.run_ended()

	# Run ended.
	def run_ended(self):
		# If it's in continuous create a new run otherwise reset environment and wait for user input
		if self.continuous:
			self.agents = []
			# If the environment is custom keep it otherwise reset the environment
			if self.custom_build:
				self.agent_num = 0
			else:
				self.reset_environment()
				self.running = True
		else:
			self.reset_environment(self.custom_build)

	# Create a new agent
	def create_agent(self, x_pos, training, reference=False):
		# Append to agent array
		if self.training:
			# Choose if the run is a reference of the neural network
			if self.extra:
				if reference:
					self.tabs[1].write_message("Reference")
				else:
					self.tabs[1].write_message("Neural Network")
			self.agents.append(Agent((x_pos,200), self.network_collection, 0, None, 25, True, self.randomness, reference))
		else:
			self.agents.append(Agent((x_pos,200), self.network_collection, 0, self.goal, 25, False, self.randomness, self.subsumption))
		if self.extra:
			self.tabs[1].write_message("New Agent Created")
		# Inform agent of the other agents positions
		for j in range(len(self.agents) - 2):
			self.agents[self.agent_num].add_other_agent(self.agents[j])
		self.agents[self.agent_num].add_object((self.floor.get_mask(), self.floor.get_position()[0], self.floor.get_position()[1]))
		# Inform agent of the environmental objects positions
		for j in range(len(self.blocks)):
			self.agents[self.agent_num].add_object((self.blocks[j].get_mask(), self.blocks[j].get_position()[0], self.blocks[j].get_position()[1]))

Main()


import PIL.Image
import argparse, os

ascii_chars = "`^\",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"

def dir_path(string):
    if os.path.isdir(string):
        return string
    else:
        raise NotADirectoryError(string)

parser = argparse.ArgumentParser(
                    prog='Pic2ASCII',
                    description='Converts the images located in a specified directory to ASCII art',
                    epilog='Text at the bottom of help')

parser = argparse.ArgumentParser()
parser.add_argument('--src_path', type=dir_path, help="Already Existing directory of files to convert")
parser.add_argument('--dest_path', type=dir_path, help="Not-yet existing directory of destination of converted files")

def main():

    parsed_args = parser.parse_args()
    print(parsed_args.src_path)
    # print(len(parsed_args))
    # for arg in parsed_args:
    #     print(arg)
    # print('test')
    # path = input("Enter a pathname to an image:\n")

    # try:
    #     image = Image.open(path)
    # except:
    #     print(path, "is not a valid path.\n")

if __name__ == "__main__":
    main()

from PIL import Image

ascii_characters_by_surface = "`^\",:;Il!i~+_-?][}{1)(|\\/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$"

def main():
    image = Image.open('image.jpg')
    # you can first resize the image if needed
    # image = image.resize((width, height))
    ascii_art = convert_to_ascii_art(image)
    save_as_text(ascii_art)

def convert_to_ascii_art(image):
    ascii_art = []
    (width, height) = image.size
    for y in range(0, height - 1):
        line = ''
        for x in range(0, width - 1):
            px = image.getpixel((x, y))
            line += convert_pixel_to_character(px)
        ascii_art.append(line)
    return ascii_art

def convert_pixel_to_character(pixel):
    (r, g, b) = pixel
    pixel_brightness = r + g + b
    max_brightness = 255 * 3
    brightness_weight = len(ascii_characters_by_surface) / max_brightness
    index = int(pixel_brightness * brightness_weight) - 1
    return ascii_characters_by_surface[index]

def save_as_text(ascii_art):
    with open("image.txt", "w") as file:
        for line in ascii_art:
            file.write(line)
            file.write('\n')
        file.close()

if __name__ == '__main__':
    main()


from django.urls import path, include
from watchlist_app.api import views
from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register('streams', views.streamPlatformVS, basename='streamplatform')

urlpatterns = [
    path('list/', views.WatchListAV.as_view(), name='movie-list'),
    path('<int:pk>/', views.WatchDetailAV.as_view(), name="movie-detail"),
    path('list2/', views.WatchListGV.as_view(), name="watch-list"),

    path("", include(router.urls)),

    path('stream/', views.StreamPlatformAV.as_view(), name='platform-list'),
    # path('stream/<int:pk>', views.StreamPlatformDetailAV.as_view(), name="streamplatform-detail"),

    # path('review/', views.ReviewList.as_view(), name="review-list"),
    # path('review/<int:pk>', views.ReviewDetail.as_view(), name="review-detail")

    path('<int:pk>/review-create/', views.ReviewCreate.as_view(), name="streamplatform-detail"),
    path('<int:pk>/reviews/', views.ReviewList.as_view(), name="review-list"),
    path('review/<int:pk>/', views.ReviewDetail.as_view(), name='review-detail'),

    path('reviews/', views.UserReview.as_view(), name="user-review-detail"),
]


import cv2
import numpy as np
import os

# Create the directory structure
paths=["data","data/train","data/test","data/train/okay","data/train/peace","data/train/Clenched_fist","data/train/ILY","data/train/Thumb_up","data/test/okay","data/test/peace","data/test/Clenched_fist","data/test/ILY","data/test/Thumb_up"]

for p in paths:
    if not os.path.exists(p):
        os.makedirs(p)

# Train or test
mode = 'train'
directory = 'data/'+mode+'/'

cap = cv2.VideoCapture(0)

print("Press 1 to save OKAY")
print("Press 2 to save PEACE")
print("Press 3 to save CLENCHED_FIST")
print("Press 4 to save ILY")
print("Press 5 to save for THUMB_UP")

while True:
    _, frame = cap.read()
    # Simulating mirror image
    #frame = cv2.flip(frame, 1)

    # Getting count of existing images
    count = {'okay': len(os.listdir(directory+"/okay")),
             'peace': len(os.listdir(directory+"/peace")),
             'Clenched_fist': len(os.listdir(directory+"/Clenched_fist")),
             'ILY': len(os.listdir(directory+"/ILY")),
             'Thumb_up': len(os.listdir(directory+"/Thumb_up")),
             }

    # Printing the count in each set to the screen
    cv2.putText(frame, "MODE : "+mode, (int(0.5*frame.shape[1])+20, 50), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)
    cv2.putText(frame, "IMAGE COUNT", (int(0.5*frame.shape[1])+20, 100), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)
    cv2.putText(frame, "OKAY : "+str(count['okay']), (int(0.5*frame.shape[1])+20, 120), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)
    cv2.putText(frame, "PEACE : "+str(count['peace']), (int(0.5*frame.shape[1])+20, 140), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)
    cv2.putText(frame, "Clenched Fist : "+str(count['Clenched_fist']), (int(0.5*frame.shape[1])+20, 160), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)
    cv2.putText(frame, "ILY : "+str(count['ILY']), (int(0.5*frame.shape[1])+20, 180), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)
    cv2.putText(frame, "Thumb Up : "+str(count['Thumb_up']), (int(0.5*frame.shape[1])+20, 200), cv2.FONT_HERSHEY_PLAIN, 1, (0,0,0), 1)

    # Coordinates of the ROI (Region Of Interest)
    x1 = 10
    y1 = 10
    x2 = int(0.5*frame.shape[1])
    y2 = int(0.5*frame.shape[1])
    # Drawing the ROI
    # The increment/decrement by 1 is to compensate for the bounding box
    cv2.rectangle(frame, (x1-1, y1-1), (x2+1, y2+1), (255,0,0) ,1)
    #ROI
    roi = frame[y1:y2, x1:x2]
    roi = cv2.resize(roi, (64, 64))

    cv2.imshow("Frame", frame)

    roi = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
    _, roi = cv2.threshold(roi, 120, 255, cv2.THRESH_BINARY)
    cv2.imshow("ROI", roi)

    interrupt = cv2.waitKey(10)
    if interrupt & 0xFF == 27: # escape key
        break
    if interrupt & 0xFF == ord('1'):
        cv2.imwrite(directory+'okay/'+str(count['okay'])+'.jpg', roi)
    if interrupt & 0xFF == ord('2'):
        cv2.imwrite(directory+'peace/'+str(count['peace'])+'.jpg', roi)
    if interrupt & 0xFF == ord('3'):
        cv2.imwrite(directory+'Clenched_fist/'+str(count['Clenched_fist'])+'.jpg', roi)
    if interrupt & 0xFF == ord('4'):
        cv2.imwrite(directory+'ILY/'+str(count['ILY'])+'.jpg', roi)
    if interrupt & 0xFF == ord('5'):
        cv2.imwrite(directory+'Thumb_up/'+str(count['Thumb_up'])+'.jpg', roi)

cap.release()
cv2.destroyAllWindows()


from flask import Flask, request, render_template, jsonify, redirect, url_for
from values import customers, services, drinks, snacks, other
app = Flask(__name__)

@app.route('/')
@app.route('/index')
def boilerplate():
    return render_template('passenger.html')

@app.route('/crew')
def crew_view():
    return render_template('crew.html')

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

#product name
#customer name
#row number
#seat
@app.route('/get_orders', methods=['GET'])
def get_orders():
    ret = []
    for order in services:
        p_id = int(order['product_id'])
        p_type = order['product_type']
        c_id = int(order['customer_id'])
        if p_type == 'drinks':
            p_name = drinks[p_id]['name']
        elif p_type == 'snacks':
            p_name = snacks[p_id]['name']
        elif p_type == 'other':
            p_name = other[p_id]['name']
        ret.append({'customer_name' : customers[c_id]['name'],
                    'row_number' : customers[c_id]['row_number'],
                    'seat_letter' : customers[c_id]['seat_letter'],
                    'product_name' : p_name,
                    'product_id' : p_id,
                    'customer_id' : c_id,
                    'product_type' : p_type,
        })
    return jsonify(ret)

@app.route('/get_products', methods=['GET'])
def get_products():
    return jsonify({'drinks' : drinks, 'snacks' : snacks, 'other' : other})

# params: customer-id
@app.route('/get_customer', methods=['GET'])
def get_customer():
    if 'customer-id' in request.args:
        c_id = request.args.get('customer-id')
        try:
            return jsonify({'customer': customers[int(c_id)]})
        except IndexError:
            return jsonify({'error' : 'customer id not exist'})
    else:
        return jsonify({'error' : 'please give in integer variable customer-id'})

@app.route('/get_customer_id_from_name', methods=['GET'])
def get_customer_id_name():
    if 'name' in request.args:
        name = request.args.get('name')
        for c in range(len(customers)):
            if (customers[c]['name'].lower() == name.lower()):
                return jsonify({'id' : c});
        return jsonify({'error': 'no such customer'})
    return jsonify({'error': 'please give a name'})

# params: product-type - [drinks/snacks/other]
#         product-id integer
@app.route('/get_product_by_id', methods=['GET'])
def get_product_by_id():
    if 'product-id' in request.args and 'product-type' in request.args:
        p_id = request.args.get('product-id')
        p_type = request.args.get('product-type')
        try:
            if p_type == 'drinks':
                return jsonify(drinks[int(p_id)])
            elif p_type == 'snacks':
                return jsonify(snacks[int(p_id)])
            elif p_type == 'other':
                return jsonify(other[int(p_id)])
            else:
                return jsonify({'error' : 'product type doesn\'t exist'})
        except IndexError:
            return jsonify({'error' : 'product id not exist'})
    else:
        return jsonify({'error' : 'please give product-id and product-type'})

# params: row-number, seat-letter, customer-id
@app.route('/update_seat', methods=['GET'])
def update_seat():
    if 'row-number' in request.args and 'seat-letter' in request.args and 'customer-id' in request.args:
        row = request.args.get('row-number')
        seat = request.args.get('seat-letter')
        c_id = request.args.get('customer-id')
        try:
            customers[int(c_id)]['row_number'] = int(row)
            customers[int(c_id)]['seat_letter'] = seat
            return jsonify({'return': 'success'})
        except IndexError:
            return jsonify({'error' : 'customer id not exist'})
    else:
        return jsonify({'error' : 'please give valid row-number, seat-letter, '
                        + 'customer-id'})

# params: product-id, customer-id
#         product-type [drinks/snacks/other]
@app.route('/add_order', methods=['GET'])
def add_order():
    if 'product-id' in request.args and 'customer-id' in request.args and 'product-type' in request.args:
        p_id = request.args.get('product-id')
        u_id = request.args.get('customer-id')
        p_type = request.args.get('product-type')
        if p_type == 'drinks' or p_type == 'snacks' or p_type == 'other':
            services.append({
                'product_id' : int(p_id),
                'product_type' : p_type,
                'customer_id' : int(u_id)
            })
            return jsonify({'response': 'order added'})
        else:
            return jsonify({'response' : 'use a valid product type'})
    else:
        return jsonify({'response': 'some issue with input. make sure include'
                        + 'variables product-id and customer-id'})

# params: product-id, customer-id
#         product-type [drinks/snacks/other]
@app.route('/remove_order', methods=['GET'])
def remove_order():
    if 'product-id' in request.args and 'customer-id' in request.args and 'product-type' in request.args:
        p_id = int(request.args.get('product-id'))
        u_id = int(request.args.get('customer-id'))
        p_type = request.args.get('product-type')
        index = -1
        for order in services:
            if order['product_id'] == p_id and order['product_type'] == p_type and order['customer_id'] == u_id:
                index = services.index(order)
                break
        if index != -1:
            print(services)
            print(services.pop(index))
            print(index)
            return jsonify({'response': 'order removed'})
        else:
            return jsonify({'response' : 'FAILURE order not removed'})
    else:
        return jsonify({'response': 'some issue with input. make sure include'
                        + 'variables product-id and customer-id'})

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


import datetime
from contextlib import contextmanager
from logging import getLogger

LOG = getLogger(__name__)

class RecordDetail(object):

    def __init__(self, name):
        self.name = name
        self.status = None
        self.start_time = datetime.datetime.now()
        self.stop_time = None
        self.number_of_records = None
        self.other_details = None
        LOG.info('___INIT__')

    def save(self,):
        # Do stuff to write to database
        LOG.info('saving %s ', self)

    def __str__(self):
        return ('name: %s start: %s stop : %s' % (self.name, self.start_time, self.stop_time))

    def stop(self, status):
        LOG.info('stopping')
        self.status = status
        self.stop_time = datetime.datetime.now()
        self.save()

    def __enter__(self,):
        LOG.info('__ENTER__')
        self.save()
        # Return value is used if you with ... as VAR
        return self

    def __exit__(self, etype, evalue, etrace):
        self.stop(0)
        # rethrow any exception (set to True to swallow it ...)
        return False

@contextmanager
def record_detail(name):
    detail = RecordDetail(name)
    detail.save()
    yield detail
    detail.stop(0)


from django.urls import path
from Paytm import PaymentViews, views

urlpatterns = [
    # Payments urls

    # Creating Order
    path('create-order/',views.CreateOrder,name='create-order'),

    # First Step
    path('ReactNativeCustomPayment/',views.ReactNativeCustomPayment,name='ReactNativeCustomPayment'),

    # Second Step When ReactNativeCustomPayment Form Will Be Submited.
    path('pay/', PaymentViews.start_payment, name="start_payment"),

    # If Second Step Succed It Will Push To THis URL Which Will Send To Paytm Payment GateWay.
    path('handlepayment/', PaymentViews.handlepayment, name="handlepayment"),

]


import tensorflow as tf
import json
import keras
from keras.models import Model
from keras.applications import ResNet50
from keras.layers import Input, Dense, Lambda, LeakyReLU, Reshape
#from pix3d_dataset import Pix3DDataset, Pix3DSequence
from loss import batch_cd_loss
from shapenet_dataset import ShapenetDataset
import numpy
import math

config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
sesson = tf.compat.v1.Session(config=config)

# Create ResNet-50 Model for 2D feature extraction.
resnet50 = ResNet50(include_top=False, input_shape=(128,128,3), pooling='avg')

# Encode the 2D features extracted by RestNet-50.
def sample(args):
    mean, var = args
    epsilon = keras.backend.random_normal(shape=keras.backend.shape(mean), mean=0.0, stddev=1.0)
    return mean + keras.backend.exp(0.5 * var) * epsilon

encoder_inputs = Input(shape=(100,), name='input')
mean = Dense(100, name='mean')(encoder_inputs)
sigma = Dense(100, name='sigma')(encoder_inputs)
z_prime = Lambda(sample, (100,), name='z_prime')([mean, sigma])

encoder = Model(inputs=encoder_inputs, outputs=z_prime, name='encoder')

# Decode and generate a Point Cloud.
NUM_POINTS = 1024
decoder_inputs = Input(shape=(100,), name='input')
x = Dense(512, name='hidden_layer1')(decoder_inputs)
x = LeakyReLU(alpha=0.5)(x)
x = Dense(1024, name='hidden_layer2')(x)
x = LeakyReLU(alpha=0.5)(x)
x = Dense(NUM_POINTS*3, activation='tanh', name='output')(x)
output = Reshape((NUM_POINTS,3))(x)
point_cloud_generation = Model(inputs=decoder_inputs, outputs=output, name='point_cloud_generation')

reconstnet = keras.Sequential()
reconstnet.add(resnet50)
reconstnet.add(Dense(100))
reconstnet.add(encoder)
reconstnet.add(point_cloud_generation)

# Define optimizer and loss function.
def loss_function(x, y):
    return batch_cd_loss(x,y)

reconstnet.compile(optimizer='adam', loss=loss_function, run_eagerly=True)
#reconstnet.compile(optimizer='adam', loss='mse', run_eagerly=True)

# Open the training/validation data split files.
with open('data/splits/train_models.json', 'r') as f:
    train_models_dict = json.load(f)

with open('data/splits/val_models.json', 'r') as f:
    val_models_dict = json.load(f)

data_dir_imgs = 'data/shapenet/ShapeNetRendering/'
data_dir_pcl = 'data/shapenet/ShapeNet_pointclouds/'

# Create our ShapenetDataset instance, which will help the model iterate over the dataset.
cats = []
cats.append('02691156')
shapenet_dataset = ShapenetDataset(data_dir_imgs, data_dir_pcl, train_models_dict, cats)

# Train the model.
reconstnet.fit(shapenet_dataset)

reconstnet.save('model')


"""Main file"""
import importlib

import click
import pyspark.pandas as ps
from hamilton import driver
from hamilton.experimental import h_spark

from utils.constants import (CLINICAL_TRIALS_MAPPING, DRUG_TITLE_COL,
                             DRUGS_MAPPING, OUTPUT_DF_COLS, P_DATE_COL,
                             PUBMED_MAPPING, PUBMED_TITLE_COL, PUBMED_WORD_COL,
                             SPARK_CONF, T_DATE_COL, TRIALS_TITLE_COL,
                             TRIALS_WORD_COL)
from utils.spark import SparkProvider

@click.command()
@click.option('-s', '--source-paths', type=(str, str, str))
@click.option('-o', '--output-path', type=str)
def main(source_paths: (str, str, str), output_path: str):
    # Reading parameters
    clinical_trials_path, drugs_path, pubmed_path = source_paths
    # Initialising spark
    spark = SparkProvider("MedTest", conf=SPARK_CONF).spark
    ps.set_option('compute.ops_on_diff_frames', True)

    skga = h_spark.SparkKoalasGraphAdapter(
        spark_session=spark,
        result_builder=h_spark.base.DictResult(),
        # KoalasDataFrameResult(),
        spine_column=None,
    )
    module_names = [
        "jobs.data_loader",
        "jobs.drugs_mentions"
    ]
    initial_config = {
        'clinical_trials_path': clinical_trials_path,
        'drugs_path': drugs_path,
        'pubmed_path': pubmed_path,
        'drugs_mapping': DRUGS_MAPPING,
        'clinical_trials_mapping': CLINICAL_TRIALS_MAPPING,
        'pubmed_mapping': PUBMED_MAPPING,
        'drug_title_col': DRUG_TITLE_COL,
        'trials_title_col': TRIALS_TITLE_COL,
        'trials_word_col': TRIALS_WORD_COL,
        'pubmed_title_col': PUBMED_TITLE_COL,
        'pubmed_word_col': PUBMED_WORD_COL,
        'output_df_cols': OUTPUT_DF_COLS,
        'p_date_col': P_DATE_COL,
        't_date_col': T_DATE_COL
    }
    modules = [importlib.import_module(m) for m in module_names]

    dr = driver.Driver(initial_config, *modules, adapter=skga)
    outputs = ['df_stats_cleaned_df']
    df = dr.execute(outputs)
    dr.display_all_functions('./output/graph.dot')
    df["df_stats_cleaned_df"].to_spark().write.format('json').mode("overwrite")\
        .save(output_path)
    SparkProvider.tear_down_spark(spark)

if __name__ == "__main__":
    main()


from django.shortcuts import render
from django.http import JsonResponse, HttpResponseNotFound
from django.contrib.auth.models import User, Group

from topicyeucau.models import Topic, MyTopic, Rating
from django.db.models import Count, Q

import datetime, numpy as np

# Create your views here.
def index(request):

    year = request.GET.get('year') or datetime.datetime.now().year
    topic_total = [0] * 12
    topic_done = [0] * 12

    query = Topic.objects.filter(start_time__year=year).values('start_time__month').annotate(total=Count('id'))
    for report in query:
        month = report.get('start_time__month')
        count = report.get('total')
        topic_total[month - 1] = count

    query = MyTopic.objects.filter(start_time__year=year).values('start_time__month').annotate(total=Count('id', filter=Q(status="Hoàn thành")))
    for report in query:
        month = report.get('start_time__month')
        count = report.get('total')
        topic_done[month - 1] = count

    return JsonResponse(data={
        'topic_total_set': topic_total,
        'topic_done_set': topic_done,
    })

def employee_ranking(request):

    year = request.GET.get('year') or datetime.datetime.now().year
    query = MyTopic.objects.filter(start_time__year=year).values('employee').annotate(count=Count('id', filter=Q(status="Hoàn thành")))
    ranking = []
    for report in query:
        employee_id = report.get('employee')
        if employee_id is None: continue
        employee_name = User.objects.get(pk=employee_id).userprofile.name
        employee_avatar = User.objects.get(pk=employee_id).userprofile.avatar.url
        count = report.get('count')
        record = dict(
            id=employee_id,
            name=employee_name,
            avatar=employee_avatar,
            count=count,
            rank=0,
        )
        ranking.append(record)

    ranking.sort(key=lambda record: record.get('count'), reverse=True)
    rank = 0
    last_count = None
    for r in ranking:
        if last_count is None or r.get('count') < last_count:
            rank +=1
            last_count = r.get('count')

        r['rank'] = rank

    return JsonResponse(ranking, safe=False)

def get_employee_report(request):

    year = request.GET.get('year') or datetime.datetime.now().year
    emp_id = request.GET.get('emp_id')

    if emp_id is None: return HttpResponseNotFound()
    employee = User.objects.get(pk=emp_id)
    if employee is None or not employee.groups.filter(pk=3).first(): return HttpResponseNotFound()

    query = MyTopic.objects.filter(start_time__year=year, status="Hoàn thành", employee=emp_id).values('start_time__month').annotate(count=Count('id'))
    dataset = [0] * 12

    for report in query:
        month = report.get('start_time__month')
        dataset[month - 1] = report.get('count')

    return JsonResponse(data=dict(
        employee=dict(name=employee.userprofile.name),
        dataset=dataset,
    ))

def get_member_ranking(request):

    year = request.GET.get('year') or datetime.datetime.now().year
    month = request.GET.get('month') or datetime.datetime.now().month

    query = Topic.objects.filter(start_time__year=year, start_time__month=month).values('author').annotate(count=Count('id'))
    ranking = []
    for report in query:
        author_id = report.get('author')
        if author_id is None: continue
        _name = User.objects.get(pk=author_id).userprofile.name
        _avatar = User.objects.get(pk=author_id).userprofile.avatar.url
        count = report.get('count')
        record = dict(
            id=author_id,
            name=_name,
            avatar=_avatar,
            count=count,
            rank=0,
        )
        ranking.append(record)

    ranking.sort(key=lambda record: record.get('count'), reverse=True)
    rank = 0
    last_count = None
    for r in ranking:
        if last_count is None or r.get('count') < last_count:
            rank +=1
            last_count = r.get('count')

        r['rank'] = rank

    return JsonResponse(ranking, safe=False)

def get_rating_on_month(request):

    year = request.GET.get('year') or datetime.datetime.now().year
    month = request.GET.get('month') or datetime.datetime.now().month

    query = Rating.objects.filter(
        topic__start_time__year=year,
        topic__start_time__month=month,
    ).values('score').annotate(count=Count('id'))

    converted = [0] * 6
    for v in query:
        score = int(v.get('score'))
        subcount = v.get('count')
        if score != 0: converted[score] = subcount

    # Chưa đánh giá bao gồm các topic đã hoàn thành nhưng chưa có rating
    total_done_count = MyTopic.objects.filter(
        topic__start_time__year=year,
        topic__start_time__month=month,
        status='Hoàn thành',
    ).count()
    converted[0] = total_done_count - sum(converted)

    data_in_month = converted

    return JsonResponse(data=data_in_month, safe=False)

def get_rating_on_year(request):

    year = request.GET.get('year') or datetime.datetime.now().year

    stars = dict()
    stars[0] = [0] * 12
    stars[1] = [0] * 12
    stars[2] = [0] * 12
    stars[3] = [0] * 12
    stars[4] = [0] * 12
    stars[5] = [0] * 12

    query = Rating.objects.filter(
        topic__start_time__year=year,
    ).values('topic__start_time__month', 'score').annotate(count=Count('id'))
    total = 0
    for v in query:
        score = v.get('score')
        month = v.get('topic__start_time__month')
        subcount = v.get('count')
        if score != 0:
            stars[score][month - 1] = subcount
            total += subcount

    # Chưa đánh giá bao gồm các topic đã hoàn thành nhưng chưa có rating
    query = MyTopic.objects.filter(
        topic__start_time__year=year,
        status='Hoàn thành',
    ).values('topic__start_time__month').annotate(count=Count('id'))
    stars = np.asarray([row for row in stars.values()], dtype=np.int32)
    for v in query:
        month = v.get('topic__start_time__month')
        subcount = v.get('count')
        stars[0, month - 1] = subcount - sum(stars[1:, month - 1])

    return JsonResponse(data=dict(data=stars.tolist(), total=total), safe=False)


import jax.numpy as jnp
from jax import device_put
from bench.core.executer import Executer

def yolo_encode(bboxes, gt_bboxes, stride, eps=1e-6):
    x_center_gt = (gt_bboxes[..., 0] + gt_bboxes[..., 2]) * 0.5
    y_center_gt = (gt_bboxes[..., 1] + gt_bboxes[..., 3]) * 0.5
    w_gt = gt_bboxes[..., 2] - gt_bboxes[..., 0]
    h_gt = gt_bboxes[..., 3] - gt_bboxes[..., 1]
    x_center = (bboxes[..., 0] + bboxes[..., 2]) * 0.5
    y_center = (bboxes[..., 1] + bboxes[..., 3]) * 0.5
    w = bboxes[..., 2] - bboxes[..., 0]
    h = bboxes[..., 3] - bboxes[..., 1]
    w_target = jnp.log(w_gt / w)
    w_target = jnp.clip(eps, w_target)
    h_target = jnp.log(h_gt / h)
    h_target = jnp.clip(eps, h_target)
    x_center_target = ((x_center_gt - x_center) / stride + 0.5)
    y_center_target = ((y_center_gt - y_center) / stride + 0.5)
    x_center_target = jnp.clip(x_center_target, eps, 1 - eps)
    y_center_target = jnp.clip(y_center_target, eps, 1 - eps)
    encoded_bboxes = jnp.stack(
        [x_center_target, y_center_target, w_target, h_target], axis=-1)
    return encoded_bboxes

def args_adaptor(np_args):
    bboxes = device_put(np_args[0])
    gt_bboxes = device_put(np_args[1])
    stride = device_put(np_args[2])
    eps = 1e-6

    return [bboxes, gt_bboxes, stride, eps]

def executer_creator():
    return Executer(yolo_encode, args_adaptor)


from pathlib import Path

import pytest

from src.utils import LineReader

def test_LineReader_lines_ok():
    """
    Tests if correct lines are returned, empty lines are skipped and StopIteration is reached
    :return: None
    """

    line_reader = LineReader(Path("tests/test_fiels_text.txt"))
    line_generator = line_reader.next_line_generator()
    line1 = next(line_generator)
    line2 = next(line_generator)

    assert line1 == "this is a test line1"
    assert line2 == "this is a test line2"

    with pytest.raises(StopIteration) as ex_info:
        next(line_generator)
    assert ex_info.type is StopIteration


import os
import configparser
from irods.meta import iRODSMeta, AVUOperation
from git import Repo

def configReader():
    """
    ConfigParser function
    Reads configuration variables inside a file and returns a reader object.
    Returns
    -------
    config : object
    """

    config_file = os.path.expandvars('$HOME/.config/gitirods.conf')
    config = config = configparser.ConfigParser()
    config.read(config_file)
    return config

def getRepo(repository_path=None):
    """
    Object function:
    It instantiate the Repo object and returns it together with
    the repository path.
    Parameters
    ----------
    repository_path : None
    Returns
    -------
    repo : object
    repository_path : str
    """

    if repository_path is None:
        repository_path = os.getcwd()
    repo = Repo(repository_path)
    return repo, repository_path

def addAtomicMetadata(
        obj, keys, values,
        external_repos=None, func=None):
    """
    Metadata add function:
    It adds metadata (keys and values) atomically - transactionally in a single call - on
    an irods object
    Parameters
    ----------
    obj : an iRODS object (col=session.collections.get('path/to/collection'))
    keys : python list of attributes
    values : python list of values for attributes
    external_repos : python string for .repos path (default is None)
    func : python function that will return metedata keys and values
    from external repositories - defineExternalReposMetadata(path) (default is None)
    """

    if external_repos is None:
        avus = list(zip(keys, values))
        obj.metadata.apply_atomic_operations(*[AVUOperation(operation='add', \
                                             avu=iRODSMeta(meta[0], meta[1])) for meta in avus])
    else:
        if os.path.exists(external_repos):
            try:
                repository_path = os.path.dirname(external_repos)
                metadata = func(repository_path)
                external_attrs = list(metadata.keys())
                external_vals = list(metadata.values())
                all_attrs = keys + external_attrs
                all_values = values + external_vals
                avus = list(zip(all_attrs, all_values))
                obj.metadata.apply_atomic_operations(*[AVUOperation(operation='add', \
                                                     avu=iRODSMeta(meta[0], meta[1])) for meta in avus])
            except Exception as error:
                print(error)
        else:
            avus = list(zip(keys, values))
            obj.metadata.apply_atomic_operations(*[AVUOperation(operation='add', \
                                             avu=iRODSMeta(meta[0], meta[1])) for meta in avus])

def projectExists(object):
    """
    Check function:
    Based on a specific commit message it will determine whether
    the project in question exists or not.
    Parameters
    ----------
    object : instantiation of Repo
    Returns
    -------
    True : shows this is a nonempty repository
    """

    project_message = 'iRODS:Trigger project workflow'
    commits_list = list(object.iter_commits())
    commit_messages_list = []
    for item in range(len(commits_list)):
        commit = commits_list[item]
        commit_message = commit.message.strip()
        commit_messages_list.append(commit_message)
    del commit_messages_list[0]
    if project_message not in commit_messages_list:
        return True

def resetCommit(obj):
    """
    Reset function:
    It removes the last commit softly. An equivalant of 'git reset --soft HEAD~1'
    If working_tree=True; removes hardly.
    Parameters
    ----------
    object : instantiation of Repo
    """

    obj.head.reset('HEAD~1', index=False, working_tree=False)

def ignoreKeystrokes(callSession):
    """
    Flush function:
    It calls iRODS session renewal function and
    while waiting for it to finish, ignores any keystrokes.
    Parameters
    ----------
    callSession : function - renewIrodsSession()
    """

    while (1):
        import sys
        from termios import tcflush, TCIOFLUSH
        callSession()
        sys.stdout.flush()
        tcflush(sys.stdin, TCIOFLUSH)
        break