import codecs, itertools, random, sys

# ---- Main runnable demo ----

def main():
	if sys.version_info[0] >= 3:
		# Monkey-patch stdout to accept Unicode strings
		sys.stdout = codecs.getwriter("UTF-8")(sys.stdout.buffer)

	for i in itertools.count(4):
		# Choose a random positive number that is exactly 'bits' bits long
		bits = int(round(2 ** (i / 2.0)))
		n = random.randrange(1 << (bits - 1), 1 << bits)
		numdigits = len(str(n))  # Number of digits in base 10, i.e. floor(log10(n))+1
		if numdigits > 8192:
			break
		print("({} bits, {} digits) {}".format(n.bit_length(), numdigits, n))

		# Print the number in various notations
		if numdigits <= 69:
			print(ConventionalEnglishNotation.to_string_with_commas(n))
			print(ConventionalEnglishNotation.number_to_words(n))
		if numdigits <= 8192:
			print(YllionEnglishNotation.to_string_with_separators(n))
			print(YllionEnglishNotation.number_to_words(n))
			chinese = YllionChineseNotation.number_to_words(n)
			if sys.version_info[0] < 3:
				chinese = chinese.encode("UTF-8")
			print(chinese)
		print("")

# ---- Submodules for different number formats ----

# See https://en.wikipedia.org/wiki/English_numerals .
class ConventionalEnglishNotation(object):

	# For example: number_to_words(1234567) -> "one million two hundred thirty-four thousand five hundred sixty-seven".
	@staticmethod
	def number_to_words(n):
		# Simple cases
		if n < 0:
			return "negative " + ConventionalEnglishNotation.number_to_words(-n)
		elif n == 0:
			return "zero"

		# 1 <= n <= 999
		elif n < 1000:
			s = ""
			if n >= 100:
				s += ConventionalEnglishNotation._ONES[n // 100] + " hundred"
				if n % 100 != 0:
					s += " "
				n %= 100
			s += ConventionalEnglishNotation._TENS[n // 10]
			if n < 20:
				s += ConventionalEnglishNotation._ONES[n]
			elif n % 10 != 0:
				s += "-" + ConventionalEnglishNotation._ONES[n % 10]
			return s

		else:  # n >= 1000
			parts = []
			for illion in ConventionalEnglishNotation._ILLIONS:
				if n == 0:
					break
				rem = n % 1000
				if rem > 0:
					s0 = ConventionalEnglishNotation.number_to_words(rem)
					s1 = (" " + illion) if (illion is not None) else ""
					parts.append(s0 + s1)
				n //= 1000
			if n != 0:
				raise ValueError("Number too large")
			return " ".join(reversed(parts))

	# For example: to_string_with_commas(-123456789) -> "-123,456,798".
	@staticmethod
	def to_string_with_commas(n):
		if n < 0:
			return "-" + ConventionalEnglishNotation.to_string_with_commas(-n)
		else:
			s = str(n)
			for i in range(len(s) - 3, 0, -3):
				s = s[ : i] + "," + s[i : ]
			return s

	_ONES = [
		"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
		"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"]

	_TENS = [
		"", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]

	_ILLIONS = [
		None, "thousand", "million", "billion", "trillion", "quadrillion",
		"quintillion", "sextillion", "septillion", "octillion", "nonillion",
		"decillion", "undecillion", "duodecillion", "tredecillion", "quattuordecillion",
		"quindecillion", "sexdecillion", "septendecillion", "octodecillion", "novemdecillion",
		"vigintillion"]

# Donald Knuth's system; see https://en.wikipedia.org/wiki/-yllion .
class YllionEnglishNotation(object):

	@staticmethod
	def number_to_words(n):
		if n < 0:
			return "negative " + YllionEnglishNotation.number_to_words(-n)
		elif n < 100:  # 0 <= n <= 99, borrow functionality from another class
			return ConventionalEnglishNotation.number_to_words(n)

		else:  # n >= 100
			temp = str(n)
			yllionslen = len(YllionEnglishNotation._YLLIONS)
			if len(temp) > (1 << yllionslen):
				raise ValueError("Number too large")
			for i in reversed(range(1, yllionslen)):
				negsplit = 1 << i
				if len(temp) > negsplit:
					high = int(temp[ : -negsplit])
					low  = int(temp[-negsplit : ])
					return ((YllionEnglishNotation.number_to_words(high) + " " + YllionEnglishNotation._YLLIONS[i]) if (high > 0) else "") \
						+ (" " if (high > 0 and low > 0) else "") \
						+ (YllionEnglishNotation.number_to_words(low) if low > 0 else "")
			raise AssertionError()

	# For example: to_string_with_separators(12345678901234567890) -> "1234:5678,9012;3456,7890".
	@staticmethod
	def to_string_with_separators(n):
		if n < 0:
			return "-" + YllionEnglishNotation.to_string_with_separators(-n)
		else:
			s = str(n)
			for (i, j) in zip(range(len(s) - 4, 0, -4), itertools.count(1)):
				temp = bin(j)
				k = len(temp) - len(temp.rstrip("0"))  # Number of trailing zeros in j
				k = min(len(YllionEnglishNotation._SEPARATORS) - 1, k)
				s = s[ : i] + YllionEnglishNotation._SEPARATORS[k] + s[i : ]
			return s

	_YLLIONS = [
		None, "hundred", "myriad", "myllion", "byllion", "tryllion", "quadryllion",
		"quintyllion", "sextyllion", "septyllion", "octyllion", "nonyllion", "decyllion"]

	_SEPARATORS = [",", ";", ":", "'"]

# Donald Knuth's system; see https://en.wikipedia.org/wiki/-yllion .
class YllionChineseNotation(object):

	@staticmethod
	def number_to_words(n):
		if n < 0:
			return u"\u8CA0" + YllionChineseNotation.number_to_words(-n)
		elif n == 0:
			return u"\u96F6"
		elif n < 100:
			return (((YllionChineseNotation._ONES[n // 10] if (n >= 20) else u"") + u"\u5341") if (n >= 10) else u"") \
				+ YllionChineseNotation._ONES[n % 10]
		else:
			temp = str(n)
			yllionslen = len(YllionChineseNotation._YLLIONS)
			if len(temp) > (1 << yllionslen):
				raise ValueError("Number too large")
			for i in reversed(range(1, yllionslen)):
				negsplit = 1 << i
				if len(temp) > negsplit:
					high = int(temp[ : -negsplit])
					low  = int(temp[-negsplit : ])
					return ((YllionChineseNotation.number_to_words(high) + YllionChineseNotation._YLLIONS[i]) if (high > 0) else u"") \
						+ (YllionChineseNotation.number_to_words(low) if (low > 0) else u"")
			raise AssertionError()

	_ONES = [u"", u"\u4E00", u"\u4E8C", u"\u4E09", u"\u56DB", u"\u4E94", u"\u516D", u"\u4E03", u"\u516B", u"\u4E5D"]

	_YLLIONS = [None, u"\u767E", u"\u842C", u"\u5104", u"\u5146", u"\u4EAC", u"\u5793", u"\u79ED", u"\u7A70", u"\u6E9D", u"\u6F97", u"\u6B63", u"\u8F09"]

# ---- Application launcher ----

if __name__ == "__main__":
	main()


import os
import sys
import json
import argparse
import numpy as np
import pandas as pd
import distutils.util
import seaborn as sns
import matplotlib.pyplot as plt

from azureml.core.run import Run, _OfflineRun
from sklearn.decomposition import PCA
from pandas_profiling import ProfileReport
from sklearn.manifold import TSNE
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.preprocessing import StandardScaler, MinMaxScaler, normalize
from sklearn.model_selection import train_test_split
from azureml.core import Workspace, Datastore, Dataset, Experiment
from sklearn.feature_selection import mutual_info_classif, SelectKBest, SelectPercentile

class ExploratoryAnalysis():

    def __init__(self):
        self.__parser = argparse.ArgumentParser("preprocessing")
        self.__parser.add_argument("--datastore", type=str,
                                   help="Name of the datastore",
                                   default="workspaceblobstore")
        self.__parser.add_argument("--dataset_name", type=str,
                                   help="Name of the dataset")
        self.__parser.add_argument("--dataset_preprocessed_name", type=str,
                                   help="Standard preprocessed dataset")
        self.__parser.add_argument("--output_preprocess_dataset", type=str,
                                   help="Name of the PipelineData reference")

        self.__args = self.__parser.parse_args()
        self.__run = Run.get_context()
        self.__local_run = type(self.__run) == _OfflineRun

        if self.__local_run:
            self.__ws = Workspace.from_config('../../notebooks-settings')
            self.__exp = Experiment(self.__ws, 'exploratory_analysis')
            self.__run = self.__exp.start_logging()
        else:
            self.__ws = self.__run.experiment.workspace
            self.__exp = self.__run.experiment

        self.__datastore = Datastore.get(
            self.__ws, datastore_name=self.__args.datastore)

    def main(self):
        df, df_eda = self.__preprocess_dataset(schema_path="./schema_dataset.json")
        self.__make_exploratory_analysis(df_eda)
        self.__upload_datasets(df, df.columns)

    def __preprocess_dataset(self, schema_path):
        with open(schema_path) as f:
            schema = json.load(f)

        df, df_eda = self.__get_dataset(self.__args.dataset_name)
        columns_names = schema.keys()
        df.columns = columns_names

        return df, df_eda

    def __make_exploratory_analysis(self, df):
        self.__frequency_tremor(df)
        self.__tremor_acceleration_energy(df)
        self.__execute_tsne(df)

    def __get_dataset(self, dataset_name):
        acc0 = self.__ws.datasets.get(f"{dataset_name}0_dataset").to_pandas_dataframe()
        acc1 = self.__ws.datasets.get(f"{dataset_name}1_dataset").to_pandas_dataframe()
        acc2 = self.__ws.datasets.get(f"{dataset_name}2_dataset").to_pandas_dataframe()
        acc3 = self.__ws.datasets.get(f"{dataset_name}3_dataset").to_pandas_dataframe()

        df_eda = pd.concat([acc0,acc1,acc2,acc3],axis=0)
        df_eda['Tremor'] = df_eda['Tremor'].replace(2,1)

        df = pd.concat([acc0,acc1,acc2,acc3],axis=0)
        df['Tremor'] = df['Tremor'].replace(2,1)

        return df, df_eda

    def __upload_datasets(self, df, columns):
            dataset_name, preprocess_filepath, datastore_path = self.__get_dataset_metadata(
                df, "train")
            self.__upload_dataset(self.__ws, self.__datastore, dataset_name,
                                  datastore_path, preprocess_filepath,
                                  use_datadrift=False, type_dataset="standard")

    def __get_dataset_metadata(self, df, extension):
        dataset_name = f'{self.__args.dataset_preprocessed_name}_{extension}'
        output_preprocessed_directory = self.__args.output_preprocess_dataset if extension == "train" else f'{self.__args.output_preprocess_dataset}_{extension}'
        preprocess_filepath = os.path.join(output_preprocessed_directory,
                                           f'{dataset_name}.csv')
        datastore_path = f"parkinson/{dataset_name}.csv"

        os.makedirs(output_preprocessed_directory, exist_ok=True)
        df.to_csv(preprocess_filepath, index=False)

        return dataset_name, preprocess_filepath, datastore_path

    def __upload_dataset(self, ws, def_blob_store, dataset_name, datastore_path, filepath, use_datadrift, type_dataset):
        def_blob_store.upload_files(
            [filepath], target_path="parkinson", overwrite=True)
        tab_data_set = Dataset.Tabular.from_delimited_files(
            path=(def_blob_store, datastore_path))
        try:
            tab_data_set.register(workspace=ws,
                                  name=f'{dataset_name}',
                                  description=f'{dataset_name} data',
                                  tags={'format': 'CSV',
                                        'use_datadrift': use_datadrift,
                                        'type_dataset': type_dataset},
                                  create_new_version=True)
        except Exception as ex:
            print(ex)

    def __frequency_tremor(self, df):
        axis = ["accZ_mean", "accX_mean"]
        for axi in axis:
            sns.set_style('whitegrid')
            plt.rcParams['font.family'] = 'Dejavu Sans'
            plt.figure(figsize=(16,8))

            sns.set_palette("Set1", desat=0.80)
            facetgrid = sns.FacetGrid(df, hue='Tremor', size=6,aspect=2)
            facetgrid.map(sns.distplot, f"{axi}", hist=False)\
                .add_legend()
            self.__run.log_image(f"Parkinson Tremor - {axi}", plot=plt)

    def __tremor_acceleration_energy(self, df):
        plt.figure(figsize=(6,8))
        sns.boxplot(x='Tremor', y='accX_energy',data=df, showfliers=False, saturation=1)
        plt.ylabel('Acceleration Energy X')
        self.__run.log_image(f"Parkinson Tremor - Acceleration Energy X", plot=plt)

    def __perform_tsne(self, X_data, y_data, perplexities, n_iter=1000, img_name_prefix='t-sne'):
        for index,perplexity in enumerate(perplexities):
            print('\nperforming tsne with perplexity {} and with {} iterations at max'.format(perplexity, n_iter))
            X_reduced = TSNE(verbose=2, perplexity=perplexity).fit_transform(X_data)
            print('Done..')

            print('Creating plot for this t-sne visualization..')
            df = pd.DataFrame({'x':X_reduced[:,0], 'y':X_reduced[:,1] ,'label':y_data})

            sns.lmplot(data=df, x='x', y='y', hue='label', fit_reg=False, size=8,\
                    palette="Set1",markers=['*', 'o'])
            plt.title("perplexity : {} and max_iter : {}".format(perplexity, n_iter))
            img_name = img_name_prefix + '_perp_{}_iter_{}.png'.format(perplexity, n_iter)
            print('saving this plot as image in present working directory...')
            self.__run.log_image(f"Parkinson Tremor - {img_name}", plot=plt)

    def __execute_tsne(self, df):
        X_norm= normalize(df.drop(['Tremor'], axis=1), norm='l2')
        X_new2 = MinMaxScaler().fit_transform(X_norm)
        X_pre_tsne = X_new2
        y_pre_tsne =df['Tremor']
        self.__perform_tsne(X_data = X_pre_tsne,y_data=y_pre_tsne, perplexities =[2,5,10,20,50])

if __name__ == '__main__':
    analysis = ExploratoryAnalysis()
    analysis.main()


"""1D advection operators.
2D/3D schemes can be built from 1D operators via dimension-splitting
"""

import numpy as np
from numba import jit

from . util import roll  # np.roll doesn't work with jit(nopython=True)
# roll is convenient for implementing periodic boundary condition
# An alternative is to use np.take(mode='wrap') instead of roll

@jit(nopython=True)
def upwind_tendency(c, u, dx, dt):
    '''
    Upwind tendency with periodic boundary

    Args:
      c: 1d numpy array, density field
      u: 1d numpy array, wind field
      dx: float, grid spacing (assume uniform)
      dt: float, time step

    Returns:
      1d numpy array with same shape as `c`
    '''

    nx = c.size

    flux = c*u
    flux_l = roll(flux, 1)  # so f_l[j] == f[j-1], with periodic boundary
    flux_r = roll(flux, -1)

    tendency = np.empty(nx)

    for i in range(nx):
        if u[i] > 0:
            tendency[i] = -flux[i] + flux_l[i]
        else:
            tendency[i] = -flux_r[i] + flux[i]

    return tendency*dt/dx

@jit(nopython=True)
def vanleer_tendency(c, u, dx, dt):
    """
    Second-order flux-limited (VanLeer) tendency with periodic boundary

    Args:
      c: 1d numpy array, density field
      u: 1d numpy array, wind field
      dx: float, grid spacing (assume uniform)
      dt: float, time step

    Returns:
      1d numpy array with same shape as `c`

    Reference: The "mono-5" limiter in
    Lin, S.-J., et al. (1994). "A class of the van Leer-type transport schemes and its application to the moisture transport in a general circulation model."
    """

    nx = c.size

    u = 0.5*(u+roll(u, 1))  # re-stagger to C-grid, pointing from box[i-1] to box[i]
    cfl = u*dt/dx

    c_l = roll(c, 1)  # so c_l[i] == c[i-1], with periodic boundary
    c_r = roll(c, -1)

    mismatch = np.empty(nx)  # left-right difference in piecewise-linear reconstruction
    flux = np.empty(nx)  # flux[i] is the flux from box[i-1] to box[i]

    delta = c - c_l
    delta_avg = (delta + roll(delta, -1))/2

    # compute slope (mismatch) in piecewise-linear reconstruction
    for i in range(nx):
        # compute local limiter
        c_max = max(c[i], c_l[i], c_r[i])  # upper boundary
        c_min = min(c[i], c_l[i], c_r[i])  # lower boundary
        mismatch[i] = np.sign(delta_avg[i])*min(abs(delta_avg[i]),
                                                2*(c[i]-c_min),
                                                2*(c_max-c[i]))

    # compute flux from slope
    mismatch_l = roll(mismatch, 1)
    for i in range(nx):
        if u[i] > 0:
            flux[i] = u[i]*(c_l[i]+mismatch_l[i]/2*(1-cfl[i]))
        else:
            flux[i] = u[i]*(c[i]-mismatch[i]/2*(1+cfl[i]))

    tendency = flux - roll(flux, -1)
    return tendency*dt/dx


from money_model import MoneyModel
from money_model import compute_gini
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from mesa.space import MultiGrid
from mesa.datacollection import DataCollector
from mesa.batchrunner import BatchRunner

fixed_params = {"width": 10,
               "height": 10}
variable_params = {"N": range(10, 500, 10)}

batch_run = BatchRunner(MoneyModel,
                        variable_params,
                        fixed_params,
                        iterations=5,
                        max_steps=100,
                        model_reporters={"Gini": compute_gini},
                       )
batch_run.run_all()

run_data = batch_run.get_model_vars_dataframe()
run_data.head()
plt.scatter(run_data.N, run_data.Gini)
plt.show()

data_collector_agents = batch_run.get_collector_agents()

print(data_collector_agents[(10,2)])

data_collector_model = batch_run.get_collector_model()

print(data_collector_model[(10,1)])


from three.A import Turtle, draw_star, draw_polygon
from math import sin, radians, atan, degrees, sqrt, cos, sin
from functools import partial
import svgwrite
from itertools import combinations

length = 100

def inscribed_polygram_rel(turtle, number_of_vertices=5, length=length):
    star_angle = 180 / number_of_vertices
    polygon_side_length = sin(radians(star_angle))/sin(radians(star_angle*2))*length #law of sines

    draw_star(turtle, number_of_vertices, length)
    turtle.right(star_angle*2)
    draw_polygon(turtle, number_of_vertices, length=polygon_side_length)

def inscribed_polygram_abs(turtle, number_of_vertices=5, x=35,y=5, length=length/2):
    vertices = get_polygon_points(number_of_vertices=5, x=x, y=y, length=length)
    for i in combinations(vertices, 2):
        turtle.image.add(turtle.line(i[0], i[1]))

def recursive_squares(turtle, rec_depth=200, offset = 0.2, length=length):
    angle =  degrees(atan(length*offset/(length-length*offset)))
    for i in range(rec_depth):
        for j in range(4): #draw square
            turtle.forward(length)
            turtle.right(90)
        turtle.penup()
        turtle.forward(length*offset)
        turtle.pendown()
        turtle.right(angle)
        _length = length*offset
        length = sqrt(_length**2+(length-_length)**2) #calculate length of inner square

def circle_grid(turtle, length=100, radius=50):
    g = svgwrite.container.Group(clip_path='url(#circle)') #grid
    for x in range(0, length, int(length/10)):
        g.add(turtle.line((0, x), (length, x)))
        g.add(turtle.line((x, 0), (x, length)))

    clip = svgwrite.masking.ClipPath(id='circle')
    clip.add(svgwrite.shapes.Circle((length/2, length/2), r=radius)) #clipping circle
    turtle.image.defs.add(clip)
    turtle.image.add(g)

def recursive_triangles(turtle, rec_depth=12, length=100):
    side = length
    step = 5
    for i in range(rec_depth):
        for i in range(3):
            turtle.forward(side)
            turtle.right(120)
        turtle.penup()
        turtle.right(30)
        turtle.forward(step)
        turtle.left(30)
        turtle.pendown()
        side -= 9 #magic

'''Calculates coordinates for regular polygons
'''
def get_polygon_points(number_of_vertices, start_angle=0, x=255, y=255, length=length, assign_angles=False):
    points =[]
    for i in range(1, number_of_vertices+1):
        angle = i*360/number_of_vertices+start_angle
        rad = radians(angle)
        new_x   = length * cos(rad)
        new_y   = length * sin(rad)
        if assign_angles:
            points.append(((x+new_x, y+new_y), angle))
        else:
            points.append((x+new_x, y+new_y))
        x += new_x
        y += new_y
    return points

def flower_polygon(turtle, number_of_vertices=16, number_of_polygons=16, length=7):
    angle = 360.0/number_of_polygons
    for i in range(0, number_of_polygons):
        turtle.image.add(svgwrite.shapes.Polygon(points=get_polygon_points(number_of_vertices, x=turtle.x+length*7, y=turtle.y+length*7, start_angle=angle*i, length=length), stroke='black', style="fill-opacity:0;"))

def draw_object(draw_func, length=length, start_x=65, start_y=65):
    turtle = Turtle(draw_func.__name__+'.svg', start_x=start_x, start_y=start_y)
    draw_func(turtle=turtle)
    turtle.save_image()

if __name__ == "__main__":
    draw_object(draw_func=recursive_triangles, start_x=5, start_y=5)
    draw_object(draw_func=flower_polygon, start_x=0, start_y=0)
    draw_object(draw_func=inscribed_polygram_rel, start_x=5, start_y=40)
    draw_object(draw_func=inscribed_polygram_abs)
    draw_object(draw_func=recursive_squares, start_x=5, start_y=5)
    draw_object(draw_func=circle_grid, start_x=10, start_y=10)


from typing import List

import torch
from PIL import Image

from transformers import (AutoTokenizer, VisionEncoderDecoderModel,
                          ViTFeatureExtractor)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# feature_extractor = ViTFeatureExtractor.from_pretrained("openai/clip-vit-large-patch14")
# tokenizer: GPT2TokenizerFast = GPT2TokenizerFast.from_pretrained("EleutherAI/gpt-neo-125M")
# tokenizer.pad_token = tokenizer.eos_token
feature_extractor = ViTFeatureExtractor.from_pretrained("nlpconnect/vit-gpt2-image-captioning")
tokenizer = AutoTokenizer.from_pretrained("nlpconnect/vit-gpt2-image-captioning")

def forward(model: VisionEncoderDecoderModel, images: List[Image.Image], texts: List[str]):
	pixel_values = feature_extractor(images, return_tensors="pt").pixel_values
	pixel_values = pixel_values.to(device)

	tokens = tokenizer(texts, padding=True, return_tensors="pt")
	input_ids = tokens['input_ids'].to(device)

	return model.forward(
		pixel_values=pixel_values,
		# Automatically figures out the decoder input_ids
		labels=input_ids,
	)

def generate(model: VisionEncoderDecoderModel, image: Image.Image, prompt: str, do_sample=True, temperature=0.1, **kwargs):
	pixel_values = feature_extractor(image, return_tensors="pt").pixel_values
	pixel_values = pixel_values.to(device)

	input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
	# `model.generate` for encoder-decoder models by default will only accept the encoder inputs.
	# to provide decoder inputs, use forced_decoder_ids.
	# forced_decoder_ids = [[i, input_ids[i]] for i in range(len(input_ids))]

	# Modified to accept decoder input ids
	outputs = model.generate(
		pixel_values=pixel_values,
		decoder_input_ids=input_ids,
		do_sample=do_sample,
		temperature=temperature,
		max_new_tokens=20,
		min_length=input_ids.shape[1] + 1,
		**kwargs,
	)
	prediction = tokenizer.batch_decode(outputs[:, input_ids.shape[1]:], skip_special_tokens=True)
	return prediction


# -*- coding: utf-8 -*-
import io
import sys
import datetime
import names
import csv
from gen_random_values import *

""" List of values for use in choices in models. """
person_list = []
address_list = []
repeat = 200

''' Lendo os dados de enderecos_.csv '''
with open('fixtures/enderecos_.csv', 'r') as f:
    r = csv.DictReader(f)
    for dct in r:
        address_list.append(dct)
    f.close()

with io.open('fixtures/clientes.csv', 'wt') as f:
    f.write(
        u'id,gender,first_name,last_name,cpf,birthday,email,phone,cell,address,district,city,uf,cep,created_at,modified_at\n')
    for i in range(repeat):
        g = random.choice(['M', 'F'])
        if g == 'M':
            first_name = names.get_first_name(gender='male')
        else:
            first_name = names.get_first_name(gender='female')
        last_name = names.get_last_name()
        cpf = gen_doc()
        birthday = gen_date()
        email = first_name[
            0].lower() + '.' + last_name.lower() + '@example.com'
        phone = gen_phone()
        cell = gen_phone()
        n = random.randint(1, 5)  # escolhe um id de enderecos_.csv
        address = '"' + address_list[n]['address'] + '"'
        district = address_list[n]['district']
        city = address_list[n]['city']
        uf = address_list[n]['uf']
        cep = address_list[n]['cep']
        date = datetime.datetime.now().isoformat(" ") + "+00"
        person_list.append(
            (i + 1, g, first_name, last_name, cpf, birthday, email, phone, cell, address, district, city, uf, cep, date, date))
    for l in person_list:
        s = str(l[0]) + "," + str(l[1]) + "," + str(l[2]) + \
            "," + str(l[3]) + "," + str(l[4]) + "," + str(l[5]) + \
            "," + str(l[6]) + "," + str(l[7]) + "," + str(l[8]) + \
            "," + str(l[9]) + "," + str(l[10]) + "," + str(l[11]) + \
            "," + str(l[12]) + "," + str(l[13]) + "," + str(l[14]) + \
            "," + str(l[15]) + "\n"
        f.write(str(s))


#!/usr/bin/env python3
from itertools import cycle
import os

# xors the two bytearrays byte1 and byte 2 and returns the result as bytearray
def xor_bytes(byte1, byte2):
	# cycle is to to repeat byte2 that it has the same length as byte1
	return bytearray(a ^ b for a, b in zip(byte1, cycle(byte2)))

with  open(".secret.pdf", "rb") as realpdf:
	# .secret.pdf contains the correct pdf header, from which the first 16 bytes are read
	pdfheader = bytearray(realpdf.read(16))

	with open("token.pdf.enc", "rb") as encryptedpdf:
		# open and read all bytes from the encrypted pdf "token.pdf.enc" to  a bytearray
		ciphertext = bytearray(encryptedpdf.read())

		# determine the constant roundkey by xoring the first bytes of the ciphertext with the pdfheader (the correct plaintext)
		roundkey = xor_bytes(ciphertext[:16], pdfheader)

		#decrypt the ciphertext, by xoring each block of 16 bytes with the constant roundkey
		solution = xor_bytes(ciphertext, roundkey)
		# save the decrypted bytes to token.pdf
		with open("token.pdf", 'wb') as d:
			d.write(solution)


from sqlalchemy import Column, Integer, JSON, ForeignKey, String

from cato_common.config.config_file_parser import JsonConfigParser
from cato_common.config.config_file_writer import ConfigFileWriter
from cato_common.domain.submission_info import SubmissionInfo
from cato_server.storage.abstract.submission_info_repository import (
    SubmissionInfoRepository,
)
from cato_server.storage.sqlalchemy.abstract_sqlalchemy_repository import (
    AbstractSqlAlchemyRepository,
    Base,
)

class _SubmissionInfoMapping(Base):
    __tablename__ = "submission_info_entity"

    id = Column(Integer, primary_key=True, autoincrement=True)
    config = Column(JSON, nullable=False)
    run_entity_id = Column(Integer, ForeignKey("run_entity.id"))
    resource_path = Column(String, nullable=False)
    executable = Column(String, nullable=False)

class SqlAlchemySubmissionInfoRepository(
    AbstractSqlAlchemyRepository, SubmissionInfoRepository
):
    def __init__(
        self,
        session_maker,
        json_config_parser: JsonConfigParser,
        config_file_writer: ConfigFileWriter,
    ):
        super(SqlAlchemySubmissionInfoRepository, self).__init__(session_maker)
        self._json_config_parser = json_config_parser
        self._config_file_writer = config_file_writer

    def to_entity(self, domain_object: SubmissionInfo) -> _SubmissionInfoMapping:
        return _SubmissionInfoMapping(
            id=domain_object.id if domain_object.id else None,
            config=self._config_file_writer.write_to_dict(domain_object.config),
            run_entity_id=domain_object.run_id,
            resource_path=domain_object.resource_path,
            executable=domain_object.executable,
        )

    def to_domain_object(self, entity: _SubmissionInfoMapping) -> SubmissionInfo:
        return SubmissionInfo(
            id=entity.id,
            config=self._json_config_parser.parse_dict(entity.config),
            run_id=entity.run_entity_id,
            resource_path=entity.resource_path,
            executable=entity.executable,
        )

    def mapping_cls(self):
        return _SubmissionInfoMapping


from notebook.utils import url_path_join
from notebook.base.handlers import IPythonHandler
import os
import json
from jinja2 import Template
import getpass
from . import config

SPARK_TEMPLATE = Template("""from sparkmanager import SparkSession
spark = (
SparkSession
.builder
{%- for key, value in conf.items() %}
.config("{{ key }}", "{{ value }}")
{%- endfor %}
.getOrCreate()
)
sc = spark.sparkContext
""")

class Config(IPythonHandler):
    def get(self,config_name):
        print(self.request)
        print("config_name")
        print(config_name)
        config_values = {}

        cluster_configs = config.get_cluster_configs()
        if config_name in cluster_configs:
            config_values = cluster_configs[config_name]
            print (config_values['conf'])
            username = getpass.getuser()
            self.finish({"status": "success"   , "username" : username ,'cluster_data': config_values ,"data": SPARK_TEMPLATE.render(conf=config_values['conf'])})
        else:
            self.finish({"status": "error"})

class UpdateConfig(IPythonHandler):
    def post(self):
        body = json.loads(self.request.body)
        print(body)
        self.finish({"status": "success_updated"   , 'cluster_data': body ,"data": SPARK_TEMPLATE.render(conf=body)})

class ConfigAdd(IPythonHandler):
    def get(self):
        key = json.loads(self.request.body)["id"]
        configObject = {}
        configObject[key] = json.loads(self.request.body)
        config.append(configObject)
        self.finish({"status": "Added successfully", "data": configObject})

class ConfigAll(IPythonHandler):
    def get(self):
        username = getpass.getuser()

        cluster_configs = config.get_cluster_configs()
        cluster_names  = list(cluster_configs.keys())

        self.finish({"status": "success", "username" : username , "data": cluster_names})

def load_jupyter_server_extension(nb_server_app):
    print("Hello world from backend")
    """
    Called when the extension is loaded.

    Args:
        nb_server_app (NotebookWebApplication): handle to the Notebook webserver instance.
    """
    # pass
    web_app = nb_server_app.web_app
    host_pattern = '.*$'
    show_config_route = url_path_join(
        web_app.settings['base_url'], '/api/show-config/([^/]+)?')
    add_config_route = url_path_join(
        web_app.settings['base_url'], '/add-config')
    get_all_config = url_path_join(
        web_app.settings['base_url'], '/api/all-config')
    update_existing_cluster = url_path_join(
        web_app.settings['base_url'], '/api/update-config')

    web_app.add_handlers(host_pattern, [(show_config_route, Config)])
    web_app.add_handlers(host_pattern, [(add_config_route, ConfigAdd)])
    web_app.add_handlers(host_pattern, [(get_all_config, ConfigAll)])
    web_app.add_handlers(host_pattern, [(update_existing_cluster, UpdateConfig)])


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

import time
import json
import urllib

import tornado.web
import tornado.gen
import tornado.httpclient

from . import BaseHandler

class DoubanLoginHandler(BaseHandler):
    def get(self):
        self.redirect(r'https://www.douban.com/service/auth2/auth?client_id=%s&redirect_uri=%s&response_type=code&scope=book_basic_r,book_basic_w,douban_basic_common' %
                      (self.settings['api_key'], self.settings['callback']))

class CallbackHandler(BaseHandler):
    @tornado.gen.coroutine
    def get(self):
        error = self.get_query_argument('error', None)
        code = self.get_query_argument('code', None)
        if error or not code:
            self.send_message('授权失败')
            self.redirect('/')
            return
        url = 'https://www.douban.com/service/auth2/token'
        data = {'client_id': self.settings['api_key'],
                'client_secret': self.settings['api_secret'],
                'redirect_uri': self.settings['callback'],
                'grant_type': 'authorization_code',
                'code': code}
        body = urllib.urlencode(data)
        http_client = tornado.httpclient.HTTPClient()
        response = http_client.fetch(url, method='POST', body=body)
        account_infor = json.loads(response.body)
        if not (yield self.async_db.members.find_one({'douban_user_id': account_infor['douban_user_id']})):
            yield self.async_db.members.insert({
                'douban_user_id': account_infor['douban_user_id'],
                'douban_user_name': account_infor['douban_user_name'],
                'access_token': account_infor['access_token'],
                'created': time.time()
            })
        else:
            yield self.async_db.members.update({'douban_user_id': account_infor['douban_user_id']}, {'$set': {'access_token': account_infor['access_token']}})
        self.set_secure_cookie('access_token', account_infor['access_token'], expires_days=7)
        self.redirect('/dashboard')

class LogoutHandler(BaseHandler):
    def get(self):
        self.clear_all_cookies()
        self.redirect('/')

handlers = [
    (r'/login', DoubanLoginHandler),
    (r'/login/callback', CallbackHandler),
    (r'/logout', LogoutHandler),
]


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

# # Visualise a trial raster using matplotlib
#
# ```bash
# jupyter nbconvert "D:\OneDrive - Nexus365\Private_Dropbox\Projects\trialexp\notebooks\noncanonical\nb20221101_115800_event_plotraster.ipynb" --to="python" --output-dir="D:\OneDrive - Nexus365\Private_Dropbox\Projects\trialexp\notebooks\noncanonical" --output="nb20221101_115800_event_plotraster"
# ```
#

# ### Imports

# In[1]:

# allow for automatic reloading of classes and function when updating the code
get_ipython().run_line_magic('load_ext', 'autoreload')
get_ipython().run_line_magic('autoreload', '2')

# Import Session and Experiment class with helper functions
from trialexp.process.data_import import *

# ### Variables

# In[2]:

import pandas as pd

trial_window = [-2000, 6000] # in ms

# time limit around trigger to perform an event
# determine successful trials
timelim = [0, 2000] # in ms

# Digital channel nb of the pyphotometry device
# on which rsync signal is sent (from pycontrol device)
rsync_chan = 2

basefolder, _ = os.path.split(os.path.split(os.getcwd())[0])

# These must be absolute paths
# use this to use within package tasks files (in params)
tasksfile = os.path.join(basefolder,'params\\tasks_params.csv')
# use this to put a local full path
#tasksfile = -r'C:/.../tasks_params.csv'

# photometry_dir = r'\\ettin\Magill_Lab\Julien\Data\head-fixed\test_folder\photometry'
photometry_dir = r'\\ettin\Magill_Lab\Julien\Data\head-fixed\kms_pyphotometry'
video_dir = r'\\ettin\Magill_Lab\Julien\Data\head-fixed\videos'

# ### Tasks
# - A tasks definition file (.csv) contains all the information to perform the extractions of behaviorally relevant information from **PyControl** files, for each **task** file. It includes what are the **triggers** of different trial types, what **events** to extract (with time data), and what are events or printed lines that could be relevant to determine the **conditions** (e.g: free reward, optogenetic stimulation type, etc.)
# - To analyze a new task you need to append task characteristics like **task** filename, **triggers**, **events** and **conditions**

# In[3]:

tasks = pd.read_csv(tasksfile, usecols = [1,2,3,4], index_col = False)
tasks

# ### Optional
#
# Transfer Files from hierarchical folders by tasks to flat folders, for photometry and behaviour files
#
# 2m 13.9s
#
# If we obtain list of files in source and dest at first and then only perform comparison on them,
# This should be much faster

# In[4]:

photo_root_dir = 'T:\\Data\\head-fixed\\pyphotometry\\data'
pycontrol_root_dir = 'T:\\Data\\head-fixed\\pycontrol'

root_folders = [photo_root_dir, pycontrol_root_dir]
horizontal_folder_pycontrol = 'T:\\Data\\head-fixed\\test_folder\\pycontrol'
horizontal_folder_photometry = 'T:\\Data\\head-fixed\\test_folder\\photometry'

copy_files_to_horizontal_folders(root_folders, horizontal_folder_pycontrol, horizontal_folder_photometry)

# ### Create an experiment object
#
# This will include all the pycontrol files present in the folder_path directory (do not include subdirectories)

# In[6]:

# Folder of a full experimental batch, all animals included

# Enter absolute path like this
# pycontrol_files_path = r'T:\Data\head-fixed\test_folder\pycontrol'

# or this if you want to use data from the sample_data folder within the package
pycontrol_files_path = os.path.join(basefolder,'sample_data/pycontrol')
pycontrol_files_path = r'T:\Data\head-fixed\kms_pycontrol'

# Load all raw text sessions in the indicated folder or a sessions.pkl file
# if already existing in folder_path
exp_cohort = Experiment(pycontrol_files_path)

# Only use if the Experiment cohort as been processed by trials before
# TODO: assess whether this can be removed or not
exp_cohort.by_trial = True

# ### Perform extraction of behavioural information by trial (SLOW)
#
# 5m55.4s

# In[7]:

# Process the whole experimental folder by trials
exp_cohort.process_exp_by_trial(trial_window, timelim, tasksfile, blank_spurious_event='spout', blank_timelim=[0, 65])

# Save the file as sessions.pkl in folder_path
# exp_cohort.save() # Do I need to save this???

# ### Match with photometry, videos, and DeepLabCut files (SLOW)
#
# The following Warning :
#
# KMeans is known to have a memory leak on Windows with MKL, when there are less chunks than available threads...
#
# is due to rsync function for photometry-pycontrol alignment
#
# 2m10.9s
#

# In[8]:

# Find if there is a matching photometry file and if it can be used:
# rsync synchronization pulses matching between behaviour and photometry
from copy import deepcopy

# Find if there is a matching photometry file:
exp_cohort.match_sessions_to_files(photometry_dir, ext='ppd')

# rsync synchronization pulses matching between behaviour and photometry
exp_cohort.sync_photometry_files(2)

# Find matching videos
exp_cohort.match_sessions_to_files(video_dir, ext='mp4')

# FInd matching DeepLabCut outputs files
exp_cohort.match_sessions_to_files(video_dir, ext='h5', verbose=True)

exp_cohort.save()

# In[9]:

# Many combinations possible
conditions_dict0 = {'trigger': 'cued', 'valid': True, 'reward spout cued': True, 'free_reward_timer': False, 'success': True}
conditions_dict1 = {'trigger': 'cued', 'valid': True, 'reward bar cued': True, 'free_reward_timer': False, 'success': True}
conditions_dict2 = {'trigger': 'cued', 'valid': True, 'reward free': True, 'success': True}
conditions_dict3 = {'trigger': 'cued', 'valid': True, 'success': False}
conditions_dict4 = {'trigger': 'uncued', 'valid': True, 'reward spout uncued': True, 'free_reward_timer': False, 'success': True}
conditions_dict5 = {'trigger': 'uncued', 'valid': True, 'reward bar uncued': True, 'free_reward_timer': False, 'success': True}
conditions_dict6 = {'trigger': 'uncued', 'valid': True, 'reward free_uncued': True} # reward after [20, 30] s

# Aggregate all condition dictionaries in a list
condition_list = [conditions_dict0, conditions_dict1, conditions_dict2, conditions_dict3, \
                  conditions_dict4, conditions_dict5, conditions_dict6]
# Aliases for conditions
cond_aliases = [
    'Cued, reward at spout, hit',
    'Cued, reward at bar release, hit',
    'Cued, Pavlovian, hit',
    'Cued, miss', \
    'Uncued, reward at spout, hit',
    'Uncued, reward at bar release, hit',
    'Uncued, miss']

# Groups as a list of lists
groups = None

# right_handed = [281]
# groups = [[280, 282, 299, 300, 301],\
#     [284, 285, 296, 297, 306, 307]]
# Window to exctract (in ms)

# # Load saved Experiment
#
# 4 s

# In[10]:

exp_cohort = Experiment(pycontrol_files_path)

# In[11]:

exp_cohort.sessions = [session for session in exp_cohort.sessions
                       if (session.subject_ID in [47, 48, 49, 51, 53]) and (session.number > 2)
                       and (session.task_name == 'reaching_go_spout_cued_uncued')]

ev_dataset = exp_cohort.behav_events_to_dataset(
    groups=groups,
    conditions_list=condition_list,
    cond_aliases=cond_aliases,
    when='all',
    task_names='reaching_go_spout_cued_uncued',
    trig_on_ev=None)

ev_dataset.set_trial_window(trial_window=trial_window, unit='milliseconds')
ev_dataset.set_conditions(conditions=condition_list, aliases=cond_aliases)

# ## Visualise a trial PETH using matplotlib

# ~~%TODO~~
# - drowdown to change time units
#
# This not doable!

# In[12]:

print(len(ev_dataset.metadata_df['keep']))

print(np.count_nonzero(ev_dataset.metadata_df['keep'] == True))

# In[13]:

ev_dataset.metadata_df.columns

# In[14]:

dates = ev_dataset.metadata_df['datetime'].apply( lambda x: x.date()  )
set(dates)

# In[15]:

tf = (ev_dataset.get_tfkeep_subjects(47)) & (ev_dataset.get_tfkeep_dates(date(2022,9,26)))

np.count_nonzero(tf)

# In[16]:

set(ev_dataset.metadata_df.session_nb[tf])

# In[17]:

ev_dataset.set_keep(tf)

# In[18]:

ev_dataset.triggers

# In[19]:

ev_dataset.data.head()

# In[20]:

from  matplotlib import pyplot as plt

plt.rcParams['font.family'] = ['Arial']

event_cols = [
    event_col for event_col in ev_dataset.data.columns if '_trial_time' in event_col]

event_name_stems = [event_col.split('_trial_time')[0] for event_col in event_cols]

triggers = ev_dataset.triggers

cm = 1/2.54  # centimeters in inches
fig, ax = plt.subplots(len(event_cols), len(triggers), sharex=True, sharey=True, figsize=(21.0*cm, 29.7*cm))

for trig_idx, trigger in enumerate(triggers):

    df_subset = ev_dataset.data.loc[(ev_dataset.data['trigger'] == trigger) & (ev_dataset.metadata_df['keep']) , :] #only include keep

    df_subset = df_subset.reset_index()

    for ev_idx, event_col in enumerate(event_cols):

        for r in range(0,df_subset.shape[0]):

            ev_times = df_subset.at[r, event_col]

            X = np.array(ev_times)
            X.shape = (1, len(X))
            X = np.tile(X,(2,1))/1000 # ms

            Y = np.array([r, r+1])
            Y.shape = (2,1)
            Y = np.tile(Y, (1, X.shape[1]))

            ax[ev_idx][trig_idx].plot(X, Y, 'k-', linewidth = 0.5)

            plot_names = trigger + ' ' + event_col

            event_name_stem = event_col.split('_trial_time')[0]

            ax[ev_idx][trig_idx].set_ylabel('Trials: ' + event_name_stem)

            ax[ev_idx][trig_idx].spines['top'].set_visible(False)
            ax[ev_idx][trig_idx].spines['right'].set_visible(False)

    ax[0][trig_idx].set_title(trigger)

    ax[ev_idx][trig_idx].set_xlabel('Time (s)')

# # Event_Dataset.plot_raster()

# In[21]:

ev_dataset.plot_raster()

# ## Overlay

# In[22]:

ev_dataset.plot_raster(separate=False)

# ## specify colors
#

# In[23]:

ev_dataset.plot_raster(separate=False, colors = ['gold','k','magenta','teal'])

# # Plotly

# In[24]:

ev_dataset.plot_raster(module='plotly')

# # In case of just one column
#
# [16/12 11:13] Julien Carponcy
#
# spotted a bug in your `plot_raster`, do not work with only one trigger, causes the shape of the ax is different when there is only one column
# replaced
#
# ```python
# ax[ev_idx][trig_idx]
# ```
#
# by
#
# ```python
# ax[ev_idx]
# ```
#

# In[26]:

from copy import deepcopy

ev_dataset2 = deepcopy(ev_dataset)

# In[32]:

ev_dataset2.metadata_df['trigger'] == 'cued'

# In[34]:

ev_dataset2.metadata_df = ev_dataset2.metadata_df.loc[ev_dataset2.metadata_df['trigger'] == 'cued', :]

# In[35]:

ev_dataset2.triggers

# In[39]:

ev_dataset2.plot_raster()


# -*- coding: utf-8 -*-
"""
Created on Tue May 11 10:00:46 2021

@author: jvano

"""

#%% import and explore data

import pandas as pd
import numpy as np
import geopandas as gpd
import glob, os

os.chdir('C:/...')
gemeenten = []
for shpfile in glob.glob("*.shp"):
    filename = os.path.splitext(shpfile)[0]
    gemeenten.append(filename)

#%% load Files & edit Material DataBase
M_total_NL = pd.DataFrame()
M_total_gem = pd.DataFrame()

building_types = ['vrijstaand', 'serieel', 'appartement', 'winkel', 'kantoor', 'industrie', 'overheid', 'overig']

# Building stock data per municipality (355 in total)
os.chdir('C:/...')

all_years = np.arange(1900,2019,1)
I_gebouwen = pd.DataFrame(0, index = all_years, columns = building_types)

#%%
gemeenten = []
for shpfile in glob.glob("*.shp"):
    filename = os.path.splitext(shpfile)[0]
    gemeenten.append(filename)

# Reclassified_II is "overig" aan toegevoegd, voor ongeclassificeerde BAG elementen (vaak schuurtjes etc.), is gemiddelde van alle andere gebouwen genomen
MI_db = pd.read_excel(r'C:/...MI_historic.xlsx')

MI_db['Type gebouw'] = MI_db['Type gebouw'].fillna(method='ffill')
tuples = list(zip(MI_db['Type gebouw'], MI_db['Cohort']))

MI_db.index = tuples
MI_db.drop(['Type gebouw', 'Cohort'], axis = 1, inplace = True)

material_columns = list(MI_db.columns)

material_index = list(MI_db.index)

#%% Loop door gemeenten Shapefiles

for file in glob.glob("*.shp"):

    BAGx = gpd.read_file(file)

    BAG = BAGx[['bouwjaar', 'status', 'gebruiks_1', 'geometry', 'GO','shape_Area', 'gebr_woonf' ]].copy()

    #2018 is start jaar, dus bouw na 2018 uit bestand verwijderen
    built_after_2018 = BAG[ BAG['bouwjaar'] > 2018].index
    BAG.drop(built_after_2018, inplace = True)

    filename = os.path.splitext(file)[0]
    print(filename)
    woningtypering = gpd.read_file(r'C:/.../'+filename+'.shp')

    # appartement : woning waaraan meerdere verblijfsobjecten zijn gerelateerd, ongeacht het gebruiksdoel van deze verblijfsobjecten, minimaal één 'woonfunctie'
    # vrijstaande woning: woning zonder andere verbonden verblijfsobjecten
    # tussen- of geschakelde woning: woning die met meerdere panden met een verblijsobject is verbonden, ook geschakelde woningen.
    # hoekwoning: eerste of laatste woning in een serie panden.
    # twee-onder-een-kap: deze woning is verbonden met een enkel pand met een verblijsobject en dit pand is alleen met het eerstgenoemde pand verbonden.
    woningtypering = woningtypering[['Woningtype', 'geometry']]

#%% Spatial join woningtypering & BAG

    BAG_1 = gpd.sjoin(BAG, woningtypering, how = 'left', op = 'intersects')
    BAG_1 = BAG_1[~BAG_1.index.duplicated(keep='first')]

#%% Classificatie gebouwen MB

# Classificatie (op basis van GO)

    # grofweg 1/4 van de data is ongeclassificeerd: het overgrootte schuurtjes/kleine huisjes in tuinen.

    BAG_1['Class'] = np.NaN

    BAG_1['Class'].loc[((BAG_1.gebruiks_1 == 'kantoorfunctie') |\
                        (BAG_1.gebruiks_1 == 'bijeenkomstfunctie') |\
                            (BAG_1.gebruiks_1 == 'logiesfunctie'))] = 'kantoor' # voor m2 kantoor & bijeenkomst is < 5.000 gekozen, dit is het miden van de range in m2 voor de categorie middelgroot

    BAG_1['Class'].loc[((BAG_1.gebruiks_1 == 'onderwijsfunctie') | \
                        (BAG_1.gebruiks_1 == 'gezondheidszorgfunctie') | \
                            (BAG_1.gebruiks_1 == 'celfunctie') | \
                                (BAG_1.gebruiks_1 == 'overige gebruiksfunctie') | \
                                        (BAG_1.gebruiks_1 == 'sportfunctie'))] = 'overheid'

    BAG_1['Class'].loc[(BAG_1['gebruiks_1']).isna()] = 'overig'

    BAG_1['Class'].loc[(BAG_1.gebruiks_1 == 'winkelfunctie')] = 'winkel'

    BAG_1['Class'].loc[(BAG_1.gebruiks_1 == 'industriefunctie')] = 'industrie' # aannemened industrie is gelijk aan bedrijfshal / distributiecentrum

    BAG_1['Class'].loc[((BAG_1.Woningtype == 'vrijstaande woning') | (BAG_1.Woningtype == 'twee-onder-een-kap' ))] = "vrijstaand"

    BAG_1['Class'].loc[((BAG_1.Woningtype == 'tussenwoning/geschakeld') | (BAG_1.Woningtype == 'hoekwoning' ))] = "serieel"

    BAG_1['Class'].loc[(BAG_1.Woningtype == 'appartement')] = "appartement" # tot 6 lagen, 6*3 meter per etage = 18m

#%% Sort per building year

    for building_type in building_types:
        summed_buildingtype = BAG_1['GO'].loc[(BAG_1.bouwjaar <= 1900) & (BAG_1.Class == building_type)].sum()
        I_gebouwen.at[1900, building_type] = I_gebouwen.at[1900, building_type] + summed_buildingtype
        for year in all_years:
            if year != 1900:
                summed_buildingtype = BAG_1['GO'].loc[(BAG_1.bouwjaar == year) & (BAG_1.Class == building_type)].sum()
                I_gebouwen.at[year, building_type] = I_gebouwen.at[year, building_type] + summed_buildingtype

#%% Add building material intensities

    BAG_copy = BAG_1.copy()
#    floor_height = 3 # MI in kg/m2, Materiaal(kg/m2) = opp(m)*hoogte(m)/floor_height(mi)*MI (kg/m2)

    cohort_names = ['<1945', '1945-1970', '1970-2000', '>2000']
    cohort_ranges = [[0,1945], [1945,1970], [1970, 2000],[2000,3000]]

    #BAG_copy['floor_area'] = BAG_copy.loc[:,'Opp_BVO']

    for material in material_columns:
        BAG_copy[material]=np.nan

    for index,cohort in enumerate(cohort_ranges): #  maakt 2 kolommen, index 1,2,3,4,... + waarde (cohort)
        for building_type in building_types:
            BAG_class_cohort_filter = ((BAG_copy['bouwjaar'] >= cohort[0]) & (BAG_copy['bouwjaar'] < cohort[1]) & (BAG_copy['Class'] == building_type))
            BAG_filtered = BAG_copy[BAG_class_cohort_filter]
            for material in material_columns:
                index_name = (building_type, cohort_names[index])
                material_intensity = MI_db.at[index_name, material]
                BAG_filtered[material] = BAG_filtered.loc[:,'GO']*material_intensity
                BAG_copy[BAG_class_cohort_filter] = BAG_filtered

    BAG_copy.to_file("C:\.../"+filename+"_voorraden.shp")

#%% Calculate total materialintensities in municipality for each class

    M_total_class = pd.DataFrame(columns = material_columns, index = material_index)

    for material in material_columns:
        value = BAG_copy[material].sum()
        M_total_gem.at[os.path.splitext(filename)[0], material] = value
        for building_type in building_types:
            for index,cohort in enumerate(cohort_ranges): #  maakt 2 kolommen, index 1,2,3,4,... + waarde (cohort)
                BAG_class_filter = ((BAG_copy['bouwjaar'] >= cohort[0]) & (BAG_copy['bouwjaar'] < cohort[1]) & (BAG_copy['Class'] == building_type))
                BAG_filtered = BAG_copy[BAG_class_filter]
                value1 = BAG_filtered[material].sum()
                index_name = (building_type, cohort_names[index])
                M_total_class.at[index_name, material]=value1

    M_total_NL = M_total_NL.add(M_total_class, fill_value=0)

    print("Einde loop: "+filename)

M_total_gem.to_excel('C:/.../M_totalen_gemeentes.xlsx')
M_total_NL.to_excel('C:/.../M_totalen_MB.xlsx')

I_gebouwen.to_excel('C:/.../Inflow_gebouwen_hist.xlsx')


from django.test import TestCase

# Create your tests here.

a = {'1': {'id': 1, 'img': '111', 'title': '爬虫开发',
           'price_policy_list': {'4': {'id': 4, 'valid_period': '1个月', 'price': 99.0},
                                 '5': {'id': 5, 'valid_period': '2个月', 'price': 199.0},
                                 '6': {'id': 6, 'valid_period': '3个月', 'price': 299.0}}, 'default_policy_id': 5}}
a.pop('1')
print(a)

a = 8
b = 20
b -= a
print(b)
b *= 0.01
print(b)

aa = 2
for i in range(2):
    aa += 10
print(aa)

import datetime
import time

#转换成localtime

dt = time.strftime("%Y%m%d%H%M%S", time.localtime())
print(dt)

print(datetime.datetime.now())
with open("backend_lc/keys/app_private_2048.txt") as p:
    print(p.read())

# import os
# baseDir =
# os.path.dirname(os.path.abspath(__name__)) # 获取运行路径
# jpgdir = os.path.join(baseDir, 'media') # 加上media路径
# filename = os.path.join(jpgdir, wenjian.name) # 获取文件路径


import numpy as np
import cv2
import streamlit as st
#Creating title for Streamlit app
st.title("Fabric Defect Detection with OpenCV")
#uploading file for processing
uploaded_file = st.file_uploader("Choose an image", type=["jpg", "jpeg", "png"])
if uploaded_file is not None:
    # Read the uploaded image using OpenCV
    image = cv2.imdecode(np.frombuffer(uploaded_file.read(), np.uint8), 1)

    img=image.copy()
    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    blur=cv2.blur(gray,(10,10))

    dst=cv2.fastNlMeansDenoising(blur,None,10,7,21)

    _,binary=cv2.threshold(dst,127,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)

    kernel=np.ones((5,5),np.uint8)

    erosion=cv2.erode(binary,kernel,iterations=1)
    dilation=cv2.dilate(binary,kernel,iterations=1)

    if (dilation==0).sum()>1:
        contours,_=cv2.findContours(dilation,cv2.RETR_TREE,cv2.CHAIN_APPROX_NONE)
        for i in contours:
            if cv2.contourArea(i)<261121.0:
                cv2.drawContours(img,i,-1,(0,0,255),3)
            cv2.putText(img,"defective fabric",(30,40),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)
    else:
        cv2.putText(img, "Good fabric", (30, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)

    st.image(image,caption="original image",channels="BGR")
    st.image(blur,caption="blur")
    st.image(binary,caption="binary")
    st.image(erosion,caption="erosion")
    st.image(dilation,caption="dilation")
    st.image(img,caption="defected area",channels="BGR")
cv2.waitKey(0)
cv2.destroyAllWindows()


from datetime import datetime, timedelta

from rdr_service.participant_enums import EnrollmentStatus, PhysicalMeasurementsStatus, QuestionnaireStatus, \
    SampleStatus
from tests.helpers.unittest_base import BaseTestCase

class CheckEnrollmentStatusTest(BaseTestCase):
    """Tests checking enrollment status of participants cron job"""

    def setUp(self):
        super().setUp()

    # test core participant meets requirements
    def test_core_meets_req(self):
        from rdr_service.offline.enrollment_check import check_enrollment
        person, ps_dao = self.setup_participant()
        # missing questionnaires and pm status
        self.assertEqual(check_enrollment(create_ticket=False), False)
        # update required attributes
        person.questionnaireOnLifestyle = QuestionnaireStatus.SUBMITTED
        person.questionnaireOnOverallHealth = QuestionnaireStatus.SUBMITTED
        person.questionnaireOnTheBasics = QuestionnaireStatus.SUBMITTED
        person.clinicPhysicalMeasurementsStatus = PhysicalMeasurementsStatus.COMPLETED
        with ps_dao.session() as session:
            session.add(person)
        self.assertEqual(check_enrollment(create_ticket=False), True)

    def setup_participant(self):
        """ A full participant (core) is defined as:
        completed the primary informed consent process
        HIPAA Authorization/EHR consent
        required PPI modules (Basics, Overall Health, and Lifestyle modules)
        provide physical measurements
        at least one biosample suitable for genetic sequencing.
        """
        twenty_nine = datetime.now() - timedelta(days=29)
        p = self.data_generator._participant_with_defaults(participantId=6666666, biobankId=9999999, version=1,
                                            lastModified=twenty_nine, signUpTime=twenty_nine)
        valid_kwargs = dict(
            participantId=p.participantId,
            biobankId=p.biobankId,
            withdrawalStatus=p.withdrawalStatus,
            dateOfBirth=datetime(2000, 1, 1),
            firstName="foo",
            lastName="bar",
            zipCode="12345",
            sampleStatus1ED04=SampleStatus.RECEIVED,
            sampleStatus1SAL2=SampleStatus.RECEIVED,
            samplesToIsolateDNA=SampleStatus.RECEIVED,
            consentForStudyEnrollmentTime=datetime(2019, 1, 1),
            numCompletedBaselinePPIModules=3,
            consentForStudyEnrollment=1,
            consentForElectronicHealthRecords=1,
            enrollmentStatus=EnrollmentStatus.FULL_PARTICIPANT,
            lastModified=twenty_nine)

        person = self.data_generator._participant_summary_with_defaults(**valid_kwargs)
        from rdr_service.dao.participant_summary_dao import ParticipantSummaryDao
        from rdr_service.dao.participant_dao import ParticipantDao
        dao = ParticipantDao()
        with dao.session() as session:
            session.add(p)
        ps_dao = ParticipantSummaryDao()
        with ps_dao.session() as session:
            session.add(person)

        return person, ps_dao


import requests
import json
import io
import base64

def base64ToString(b):
    return base64.b64decode(b)

def repos_from_user(username):
    """
    Returns a list of strings with the names of the repositories
    """
    r = requests.get('https://api.github.com/users/' + username + '/repos')
    if 'rate limit' in r.text:
        print('Rate limit exceeded')
        raise ValueError
    repoItem = json.loads(r.text or r.content, parse_float=True)
    list_of_repos = []
    for repo in repoItem:
        list_of_repos.append(repo.get('name'))
    return list_of_repos

def is_abandoned(username, repo):
    """
    Returns true if the repository is abandoned
    """
    r = requests.get('https://api.github.com/repos/' + username + '/' + repo + '/contents/')
    if(r.ok):
        repoItem = json.loads(r.text or r.content, parse_float=True)
        for file_or_folder in repoItem:
            if file_or_folder.get('name') == '.abandoned' :
                abandoned_file = file_or_folder
                return True
        return False
    else:
        if 'rate limit' in r.text:
            print('Rate limit exceeded')
        raise ValueError

def get_abandoned_info(username, repo):
    """
    """
    r = requests.get('https://api.github.com/repos/' + username + '/' + repo +'/contents/.abandoned')
    if(r.ok):
        repoItem = json.loads(r.text or r.content, parse_float=True)
        f = base64ToString(repoItem['content'])
        text = f.split('\n')
        final_text = ''
        for line in text:
            final_text += line
            final_text += """
"""
        return final_text

        # # Another way, more obscure
        # g = io.StringIO(f.decode('utf-8'))
        # for b in g.readlines():
        #     print(b)

if __name__ == '__main__':
    username = 'cperales'
    repositories = repos_from_user(username)

    for repo in repositories:
        if is_abandoned(username, repo):
            print(repo + ' is abandoned:')
            info = get_abandoned_info(username, repo)
            print(info)


# run below in cmd in the .ui folder to create a .py file
#  Classes\Version 2>C:\Users\jamie.kapilivsky\AppData\Local\Continuum\Anaconda3\Library\bin\pyuic5.bat -x pyqtdesignerV2.ui -o UI.py

# Designer folder
# C:\Users\jamie.kapilivsky\AppData\Roaming\Python\Python36\site-packages\pyqt5-tools

import os
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
import pandas as pd
import datetime
import subprocess

from Threads import Threaded
from UI import Ui_MainWindow

class Window(QMainWindow):
    requestDoc = pyqtSignal(str, str)

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        self.threading()
        self.btn_functionality()
        self.nav_functionality()

        self.MainWindow.show()

    def update_progressbar(self, percentage):
        self.ui.progressBar.setValue(percentage * 100)

    def threading(self):
        self._thread=QThread()
        self._threaded=Threaded(self.update_progressbar, result=self.display_page)

        self.requestDoc.connect(self._threaded.create_reports)

        self._thread.started.connect(self._threaded.start)
        self._threaded.moveToThread(self._thread)
        qApp.aboutToQuit.connect(self._thread.quit)
        self._thread.start()

    def btn_functionality(self):
        self.MainWindow = QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self.MainWindow)

        self.ui.pushButton_Run.clicked.connect(self.get_comboBox_info)
        self.ui.pushButton_GoToFolder.clicked.connect(self.go_to_folder)

    def nav_functionality(self):
        self.ui.actionNew.triggered.connect(self.new_project)
        self.ui.actionOpen.triggered.connect(self.file_path)
        self.ui.actionRun.triggered.connect(self.get_comboBox_info)
        self.ui.actionQuit.triggered.connect(lambda: QApplication.quit())

        self.ui.actionFAQ.triggered.connect(self.project_FAQ)
        self.ui.actionAbout.triggered.connect(self.project_about)
        self.ui.actionHow_To_Run.triggered.connect(self.how_to_run)

    def new_project(self):
        self.ui.textEdit.setText('')
        self.ui.progressBar.setValue(0)
        self.ui.label_excel_name.setText('Excel file')
        self.file_path()

    def project_FAQ(self):
        faq_file = open('txt_files/FAQ.txt', 'r')
        faq = faq_file.read()
        self.ui.textEdit.setText(faq)

    def project_about(self):
        about_file = open('txt_files/About.txt', 'r')
        about = about_file.read()
        self.ui.textEdit.setText(about)

    def how_to_run(self):
        howtorun_file = open('txt_files/HowToRun.txt', 'r')
        howto = howtorun_file.read()
        self.ui.textEdit.setText(howto)

    def go_to_folder(self):
        folder = 'Reports/' + str(datetime.date.today()) + '/'
        if not os.path.exists(folder):
            os.makedirs(folder)

        dir_path = os.path.dirname(os.path.realpath(__file__))
        folder = folder.replace('/', '\\')
        subprocess.Popen(r"explorer /select," + dir_path + '\\' + folder)

    def file_path(self):
        path = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'),
                                           'Excel(*.xlsx);;csv(*.csv);;All Files(*.*)')
        csv = False
        excel = False

        if path[0][-5:] == '.xlsx':
            excel = True
        elif path[0][-4:] == '.csv':
            csv = True

        if path[0] == " ":  # Needs a space... -.-
            return "Missing"
        if csv:
            df_new = pd.read_csv(path[0])
            writer = pd.ExcelWriter('temp.xlsx')
            df_new.to_excel(writer, 'Sheet1', index=False)
            writer.save()
            self.ui.label_excel_name.setText(path[0])
            return 'temp.xlsx'
        elif excel:
            self.ui.label_excel_name.setText(path[0])
            return path[0]

    @pyqtSlot()
    def get_comboBox_info(self):
        if self.ui.label_excel_name.text() == "Excel file":
            file_path = self.file_path()
            if file_path == 'Missing':
                # TODO - need a way to warn things
                #self.ui.textEdit.setText('WARNING: Must use a CSV or Excel file.')
                return
        else:
            # Makes sure to use the temp excel file if the user selected a CSV
            if self.ui.label_excel_name.text()[-4:] == '.csv':
                file_path = 'temp.xlsx'
            else:
                # Used if a file location has already been selected!
                file_path = self.ui.label_excel_name.text()

        self.template_select = self.ui.comboBox_report.currentText()

        self.requestDoc.emit(file_path, self.template_select)

        # Todo - disable buttons! *Turn them back on in "Display page function"
        self.ui.pushButton_Run.setEnabled(False)
        self.ui.pushButton_GoToFolder.setEnabled(False)

        self.ui.actionNew.setEnabled(False)
        self.ui.actionOpen.setEnabled(False)
        self.ui.actionRun.setEnabled(False)
        self.ui.actionGo_To_Folder.setEnabled(False)
        self.ui.actionQuit.setEnabled(False)

    @pyqtSlot(object)
    def display_page(self):
        # TODO - make sure all of these labels are correct
        self.ui.pushButton_Run.setEnabled(True)
        self.ui.pushButton_GoToFolder.setEnabled(True)

        self.ui.actionNew.setEnabled(True)
        self.ui.actionOpen.setEnabled(True)
        self.ui.actionRun.setEnabled(True)
        self.ui.actionGo_To_Folder.setEnabled(True)
        self.ui.actionQuit.setEnabled(True)


import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.1, 6.5, 100)  # x座標
y = 1/x  # y座標

left = np.array([0, 1, 2, 3, 4, 5])
height = np.array([1, 1/2, 1/3, 1/4, 1/5, 1/6])

plt.plot(x, y, color='red')  # 点列(x,y)を黒線で繋いだプロット
plt.bar(left, height, width=1.0, align='edge',
        color='#fff1c1', edgecolor='black')

plt.yticks([0, 1, 2])
plt.xlim([0, 6.5])
plt.ylim([0, 2])
plt.savefig('harmonic_number.png', dpi=300)
plt.show()  # プロットを表示


import datetime
import json

from django import http
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import Group
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.db.models import Q
from django.shortcuts import render, get_object_or_404, redirect
from django.utils.translation import ugettext as _

from fullcalendar.forms import CalendarModelForm, EventsModelForm
from fullcalendar.models import Calendar, Events, DOCTOR, DONE, INSPECTION, CAPACITATION, SIMULATION, CHARLAS, OTRO, \
    INDUCCION, CAPACITACION_DE_LEY, CAPACITACION_ESPECIFICA, CAPACITACION_SEGURIDAD, CAPACITACION_DE_SALUD_OCUPACIONAL, \
    ENTRENAMIENTO
from main.models import Company

def calendar_list(request, company_slug):
    group = Group.objects.get(name="Doctor")
    company = get_object_or_404(Company, slug=company_slug)

    if group in request.user.groups.all():
        calendars = Calendar.objects.filter(Q(company=company), Q(type=DOCTOR))
    else:
        calendars = Calendar.objects.filter(Q(company=company), ~Q(type=DOCTOR))
    return render(request, "fullcalendar/list.html", locals())

@login_required
def calendar_new(request, company_slug):
    title = _('Nuevo Cronograma')
    company = get_object_or_404(Company, slug=company_slug)
    calendar = True
    if request.POST:
        form = CalendarModelForm(request.POST, user=request.user)
        if form.is_valid():
            calendar = form.save(commit=False)
            group = Group.objects.get(name="Doctor")
            if group in request.user.groups.all():
                calendar.type = DOCTOR
            calendar.created_by = request.user
            calendar.company = company
            calendar.save()
            form.save_m2m()
            return redirect(reverse('fullcalendar:view_calendar', args=[company_slug, calendar.slug, calendar.id]))
        else:
            message = 'Revisa la informacion'
    else:
        form = CalendarModelForm(user=request.user)

    return render(request, "main/layout_form.html", locals())

@login_required
def calendar_edit(request, company_slug, calendar_id):
    title = _('Editar Cronorama')
    group = Group.objects.get(name="Doctor")
    company = get_object_or_404(Company, slug=company_slug)
    calendar = Calendar.objects.get(pk=calendar_id)
    if request.POST:
        form = CalendarModelForm(request.POST, instance=calendar, user=request.user)
        if form.is_valid():
            calendar = form.save(commit=False)
            if group in request.user.groups.all():
                calendar.type = DOCTOR
            calendar.save()
            return redirect(reverse('fullcalendar:calendar_list', args=[company_slug]))
        else:
            message = 'Revisa la informacion'
    else:
        if group in request.user.groups.all():
            calendar.type = None
        form = CalendarModelForm(instance=calendar, user=request.user)

    return render(request, "main/layout_form.html", locals())

@login_required
def calendar_delete(request, company_slug, calendar_id):
    company = get_object_or_404(Company, slug=company_slug)
    calendar = Calendar.objects.get(pk=calendar_id)
    events = Events.objects.filter(calendar=calendar)
    for e in events:
        e.delete()
    calendar.delete()
    return redirect(reverse('fullcalendar:calendar_list', args=[company_slug]))

@login_required
def view_calendar(request, company_slug, slug, calendar_id):
    calendar = True
    company = None
    try:
        company = get_object_or_404(Company, slug=company_slug)
        print('sluug', slug)
        calendar = Calendar.objects.get(company=company, slug=slug, id=calendar_id)
    except ObjectDoesNotExist:
        calendar = get_object_or_404(Calendar, id=calendar_id)
    dones = Events.objects.filter(state=DONE, calendar=calendar).count()
    not_do = Events.objects.filter(calendar=calendar).count() - dones
    # company = request.user.company
    form = EventsModelForm(calendar=calendar)
    info = {
        'view_calendar': {
            'name': calendar.title,
            'params': [slug, calendar.id]
        }
    }

    # breadcrumb = generate_breadcrumb_relations(links, 'view_calendar', info)
    return render(request, "fullcalendar/calendar.html", locals())

def events_json(request, calendar_id):
    calendar = get_object_or_404(Calendar, id=calendar_id)
    events_l = Events.objects.filter(calendar=calendar)
    events_list = []
    for event in events_l:
        event_start = event.event_start
        event_end = event.event_end

        all_day = event_start.hour == 0 and event_end.minute == 0

        if not event.is_cancelled:
            color = None
            if event.type_capacitations == INDUCCION:
                color = 'yellow'
            if event.type_capacitations == CAPACITACION_DE_LEY:
                color = 'red'
            if event.type_capacitations == CAPACITACION_ESPECIFICA:
                color = 'purple'
            if event.type_capacitations == CAPACITACION_SEGURIDAD:
                color = 'orange'
            if event.type_capacitations == CAPACITACION_DE_SALUD_OCUPACIONAL:
                color = 'red'
            if event.type_capacitations == ENTRENAMIENTO:
                color = 'blue'

            events_list.append({
                'id': event.id,
                'start': event_start.strftime('%Y-%m-%dT%H:%M%z'),
                'end': event_end.strftime('%Y-%m-%dT%H:%M%z'),
                'title': event.title,
                'allDay': all_day,
                "color": color
            })
    # if len(events_list) == 0:
    #    raise http.Http404
    # else:
    return http.HttpResponse(json.dumps(events_list), content_type="application/json")

def save_event(request, slug):
    response = {}
    if request.POST:
        print(request.FILES)
        if request.POST.get('id'):
            e = get_object_or_404(Events, pk=request.POST.get('id'))
            form = EventsModelForm(request.POST, request.FILES, instance=e)
        else:
            form = EventsModelForm(request.POST, request.FILES)
        print('gogogo')
        if form.is_valid():
            print('gogogox2')
            calendar = get_object_or_404(Calendar, slug=slug)
            event = form.save(commit=False)
            event.calendar = calendar
            event.created_by = request.user
            if event.calendar.type == CAPACITATION:
                event.type_inspeccions = None
            if event.calendar.type == INSPECTION:
                event.type_capacitations = None
                event.hours_worked = float(0)
                event.number_workers = 0
            if event.calendar.type == OTRO or event.calendar.type == SIMULATION or event.calendar.type == DOCTOR:
                event.type_inspeccions = None
                event.type_capacitations = None
                event.hours_worked = float(0)
                event.number_workers = 0

            if event.calendar.type == CHARLAS:
                event.type_inspeccions = None
                event.type_capacitations = None

            event.type = event.calendar.type

            event.save()

            color = None
            if event.type_capacitations == INDUCCION:
                color = 'yellow'
            if event.type_capacitations == CAPACITACION_DE_LEY:
                color = 'red'
            if event.type_capacitations == CAPACITACION_ESPECIFICA:
                color = 'purple'
            if event.type_capacitations == CAPACITACION_SEGURIDAD:
                color = 'orange'
            if event.type_capacitations == CAPACITACION_DE_SALUD_OCUPACIONAL:
                color = 'red'
            if event.type_capacitations == ENTRENAMIENTO:
                color = 'blue'

            response['success'] = True
            response['message'] = _("Save Success")
            response['id'] = event.id
            response['title'] = event.title
            response['start'] = event.event_start.strftime('%Y-%m-%d %I:%M %p %z')
            response['end'] = event.event_end.strftime('%Y-%m-%d %I:%M %p %z')
            response['allDay'] = event.event_start.hour == 0 and event.event_end.minute == 0
            response['color'] = color
        else:
            response['success'] = False
            print(form.errors)
            errors = form.errors
            response['errors'] = list(errors)
    else:
        response['success'] = True
        response['message'] = _("Invalid request")
    return http.HttpResponse(
        json.dumps(response),
        content_type="application/json"
    )

def get_event(request):
    response = {}
    import os
    if request.POST:
        event_id = request.POST.get('id')
        event = get_object_or_404(Events, id=event_id)
        response['success'] = True
        response['data'] = {
            'event': event.id,
            'event_start': event.event_start.strftime('%Y-%m-%d %I:%M %p %z'),
            'event_end': event.event_end.strftime('%Y-%m-%d %I:%M %p %z'),
            'title': event.title,
            'description': event.description,
            'observation': event.observation,
            'state': event.state,
            'type': event.type,
            'hours_worked': event.hours_worked,
            'number_workers': event.number_workers,
            'responsable': event.responsable,
            'type_capacitations': event.type_capacitations,
            'evidence_name': os.path.basename(event.evidence.name) if event.evidence else 'Ninguno',
            'url_evidence': event.evidence.url if event.evidence else 'Ninguno',

            # 'member': event.member.id,
            # 'member_fullname': event.member.first_name + ' ' + event.member.last_name
        }

        # 'type_inspeccion': event.type_inspeccion
    else:
        response['success'] = False
        response['message'] = _("Invalid request")
    return http.HttpResponse(json.dumps(response), content_type="application/json")

def update_event(request, slug):
    response = {}
    if request.POST:
        print(request.FILES)
        if request.POST.get('id'):
            e = get_object_or_404(Events, pk=request.POST.get('id'))
            form = EventsModelForm(request.POST, request.FILES, instance=e)
        else:
            form = EventsModelForm(request.POST, request.FILES)
        print('gogogo')
        if form.is_valid():
            print('gogogox2')
            calendar = get_object_or_404(Calendar, slug=slug)
            event = form.save(commit=False)
            event.calendar = calendar
            event.created_by = request.user
            if event.calendar.type == CAPACITATION:
                event.type_inspeccions = None
            if event.calendar.type == INSPECTION:
                event.type_capacitations = None
                event.hours_worked = 0
                event.number_workers = 0
            if event.calendar.type == OTRO or event.calendar.type == SIMULATION or event.calendar.type == DOCTOR:
                event.type_inspeccions = None
                event.type_capacitations = None
                event.number_workers = float(0)
                event.hours_worked = 0

            if event.calendar.type == CHARLAS:
                event.type_inspeccions = None
                event.type_capacitations = None

            event.type = event.calendar.type

            if event.evidence:
                event.state = DONE

            color = None
            if event.type_capacitations == INDUCCION:
                color = 'yellow'
            if event.type_capacitations == CAPACITACION_DE_LEY:
                color = 'red'
            if event.type_capacitations == CAPACITACION_ESPECIFICA:
                color = 'purple'
            if event.type_capacitations == CAPACITACION_SEGURIDAD:
                color = 'orange'
            if event.type_capacitations == CAPACITACION_DE_SALUD_OCUPACIONAL:
                color = 'red'
            if event.type_capacitations == ENTRENAMIENTO:
                color = 'blue'

            event.save()
            response['success'] = True
            response['message'] = _("Save Success")
            response['id'] = event.id
            response['title'] = event.title
            response['start'] = event.event_start.strftime('%Y-%m-%d %I:%M %p %z')
            response['end'] = event.event_end.strftime('%Y-%m-%d %I:%M %p %z')
            response['allDay'] = event.event_start.hour == 0 and event.event_end.minute == 0
            response['color'] = color
        else:
            response['success'] = False
            print(form.errors)
            errors = form.errors
            response['errors'] = list(errors)
    else:
        response['success'] = True
        response['message'] = _("Invalid request")
    return http.HttpResponse(
        json.dumps(response),
        content_type="application/json")

def delete_event(request, slug):
    if request.POST:
        if request.POST.get('id'):
            e = get_object_or_404(Events, pk=request.POST.get('id'))
            e.delete()
    return http.HttpResponse(1)

def settings_calendar(request, slug):
    company = request.user.company
    instance = get_object_or_404(Calendar, slug=slug)

    info = {
        'settings_calendar': {
            'params': [slug]
        },
        'view_calendar': {
            'name': instance.title,
            'params': [slug, instance.id]
        }
    }

    # breadcrumb = generate_breadcrumb_relations(links, 'settings_calendar', info)
    if request.POST:
        form = CalendarModelForm(request.POST, instance=instance)
        if form.is_valid():
            calendar = form.save()
            return redirect(reverse('fullcalendar:view_calendar', args=[calendar.slug, calendar.id]))
    else:
        form = CalendarModelForm(instance=instance)
        width = 12
    return render(request, "main/base_form.html", locals())


import json
import stringcase
from .utils import (
    object_hook,
    SNAKE_CASE,
    CAMEL_CASE,
    PASCAL_CASE,
)

class MyDict(dict):
    """
    A **Python** _dict_ subclass which tries to act like **JavaScript** objects, so you can use the **dot notation** (.) to access members of the object. If the member doesn't exist yet then it's created when you assign something to it. Brackets notation (d['foo']) is also possible.
    """

    def __init__(self, dict_source=None, **kw):
        if dict_source and isinstance(dict_source, (dict, MyDict)):
            for k, v in dict_source.items():
                self[k] = self._transform(v)

        for key, value in kw.items():
            self[key] = self._transform(value)

    def _transform(self, source):
        if isinstance(source, (dict, MyDict)):
            return MyDict(source)

        elif isinstance(source, list):
            return [item for item in map(self._transform, source)]

        elif isinstance(source, tuple):
            result = None
            for item in source:

                if not result:
                    result = (self._transform(item),)

                else:
                    result = result + (self._transform(item),)

            return result

        else:
            # no need for transformation (int, float, str, set, ...)
            return source

    def __getattr__(self, name):
        """
        Get a field "name" from the object in the form:
            obj.name
        """
        if name in self:
            return self[name]

    def __setattr__(self, name, value):
        """
        Sets a field into the object in the form:
            obj.name = value
        """
        self[name] = self._transform(value)

    def __getitem__(self, name):
        """
        Get a field "key" value from the object in the form:
            obj[name]
        """
        return self.get(name)

    def has_path(self, key):
        """
        Check existence of "path" in the tree.

        d = MyDict({'foo': {'bar': 'baz'}})
        d.has_path('foo.bar') == True

        **It only supports "dot-notation" (d.foo.bar)
        """
        if super(MyDict, self).__contains__(key):
            return True

        else:
            parts = str(key).split('.')
            if len(parts) > 1:
                k = '.'.join(parts[:1])
                return self[k].has_path('.'.join(parts[1:]))

            else:
                return super(MyDict, self).__contains__(key)

    def get(self, key, default=None):
        if key in self:
            return super(MyDict, self).get(key, default)

        else:
            parts = str(key).split('.')
            if len(parts) > 1:
                try:
                    return self.get(parts[0]).get('.'.join(parts[1:]))

                except Exception:
                    return None

            else:
                return super(MyDict, self).get(key, default)

    def to_json(self, case_type=None):
        """Returns a JSON-like string representing this instance"""
        return json.dumps(self.get_dict(case_type))

    def get_dict(self, case_type=None):
        """
        Returns a <dict> of the <MyDict> object

        Args:
            case_type: The type of case

        Returns:
            A <dict> representing the
        """

        def _get_dict(member, case_type):

            if isinstance(member, (dict, MyDict)):
                d = {}
                for k, v in member.items():
                    custom_key = k
                    if case_type == SNAKE_CASE:
                        custom_key = stringcase.snakecase(k)

                    elif case_type == CAMEL_CASE:
                        custom_key = stringcase.camelcase(k)

                    elif case_type == PASCAL_CASE:
                        custom_key = stringcase.pascalcase(k)

                    d[custom_key] = _get_dict(v, case_type)

                return d

            elif isinstance(member, (list,)):
                lst = []
                for a in member:
                    lst.append(_get_dict(a, case_type))

                return lst

            elif isinstance(member, (tuple,)):
                tpl = tuple()
                for a in member:
                    tpl = tpl + (_get_dict(a, case_type),)

                return tpl

            elif isinstance(member, (set,)):
                st = set([])
                for a in member:
                    st.add(_get_dict(a, case_type))

                return st

            else:
                return member

        return _get_dict(self, case_type)

    @staticmethod
    def from_json(json_source, case_type=None):
        """
        Returns a "MyDict" instance from a:
            JSON string
            <file>-like containing a JSON string
        """

        def _object_hook(obj):
            return object_hook(obj, case_type)

        if isinstance(json_source, (str, bytes)):
            # decode bytes to str
            if isinstance(json_source, bytes):
                json_source = json_source.decode('utf8')

            json_load_func = getattr(json, 'loads')

        elif hasattr(json_source, 'read'):
            json_source.seek(0)
            json_load_func = getattr(json, 'load')

        json_obj = json_load_func(
            json_source,
            object_hook=_object_hook,
        )

        return MyDict(json_obj)


from tkinter import *
import sys
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import time
import math

temp = 0
last = 0
angle = np.linspace(0, 359, num=360)
fig1 = plt.figure(1)
fig2 = plt.figure(2)
ar = fig1.gca(projection='3d')
sf = fig2.add_subplot(111)
sf.grid(True)
ar.set_xlim(-50, 50)
ar.set_ylim(-50, 50)
ar.set_zlim(-50, 50)
t_1 = 0
t_2 = 0
t_3 = 0
t_4 = 0
t_5 = 0
t_6 = 0
st_x = 0
st_y = 0
st_z = 10
r1 = 10
r2 = 20
r3 = 10

def to_RAD(deg):
    return float(deg)*(math.pi / 180)

def end_point(d1, d2, d3, d4, d5, d6):
    x_0 = 0
    y_0 = 0
    z_0 = 0

    x_1 = r1 * math.cos(to_RAD(d1)) * math.cos(to_RAD(d2)) + x_0
    y_1 = r1 * math.sin(to_RAD(d1)) * math.cos(to_RAD(d2)) + y_0
    z_1 = r1 * math.sin(to_RAD(d2)) + z_0

    x_2 = (r2 * math.cos(to_RAD(d3 + d1)) * math.cos(to_RAD(d2 + d4))) + x_1
    y_2 = (r2 * math.sin(to_RAD(d3 + d1)) * math.cos(to_RAD(d4 + d2))) + y_1
    z_2 = (r2 * math.sin(to_RAD(d4 + d2))) + z_1

    x_3 = (r3 * math.cos(to_RAD(d3 + d1 + d5)) * math.cos(to_RAD(d2 + d4 + d6))) + x_2
    y_3 = (r3 * math.sin(to_RAD(d3 + d1 + d5)) * math.cos(to_RAD(d4 + d2 + d6))) + y_2
    z_3 = (r3 * math.sin(to_RAD(d4 + d2 + d6))) + z_2

    return x_3, y_3, z_3

def forward_kinematics(d1, d2, d3, d4, d5, d6):
    x_0 = 0
    y_0 = 0
    z_0 = 0

    x_1 = r1 * math.cos(to_RAD(d1)) * math.cos(to_RAD(d2)) + x_0
    y_1 = r1 * math.sin(to_RAD(d1)) * math.cos(to_RAD(d2)) + y_0
    z_1 = r1 * math.sin(to_RAD(d2)) + z_0

    r_x_1 = np.array([x_0, x_1])
    r_y_1 = np.array([y_0, y_1])
    r_z_1 = np.array([x_0, z_1])
    r_1 = np.array([r_x_1, r_y_1, r_z_1])

    x_2 = (r2 * math.cos(to_RAD(d3 + d1)) * math.cos(to_RAD(d2 + d4))) + x_1
    y_2 = (r2 * math.sin(to_RAD(d3 + d1)) * math.cos(to_RAD(d4 + d2))) + y_1
    z_2 = (r2 * math.sin(to_RAD(d4 + d2))) + z_1

    r_x_2 = np.array([x_1, x_2])
    r_y_2 = np.array([y_1, y_2])
    r_z_2 = np.array([z_1, z_2])

    x_3 = (r3 * math.cos(to_RAD(d3 + d1 + d5)) * math.cos(to_RAD(d2 + d4 + d6))) + x_2
    y_3 = (r3 * math.sin(to_RAD(d3 + d1 + d5)) * math.cos(to_RAD(d4 + d2 + d6))) + y_2
    z_3 = (r3 * math.sin(to_RAD(d4 + d2 + d6))) + z_2

    r_x_3 = np.array([x_2, x_3])
    r_y_3 = np.array([y_2, y_3])
    r_z_3 = np.array([z_2, z_3])
    return x_3, y_3, z_3, r_x_1, r_y_1, r_z_1, r_x_2, r_y_2, r_z_2, r_x_3, r_y_3, r_z_3

def cost(x_c, y_c, z_c, t_x, t_y, t_z):
    cost_function = math.sqrt((x_c - t_x) ** 2 + (y_c - t_y) ** 2 + (z_c - t_z) ** 2)
    return float(cost_function)

x_3, y_3, z_3 = end_point(t_1, t_2, t_3, t_4, t_5, 90)
xd = 1
the = 0
while 1:
    print(the)
    st_x = 30*math.cos(to_RAD(the))
    st_y = 30*math.sin(to_RAD(the))
    st_z = the/10
    c_f_1 = []
    c_f_2 = []
    c_f_3 = []
    c_f_4 = []
    c_f_5 = []
    c_f_6 = []
    cost_func = cost(x_3, y_3, z_3, st_x, st_y, st_z)
    print('cost_function:', cost_func)
    if cost_func < 2:
        the += 1
    for counter in angle:
        i, j, k = end_point(counter, t_2, t_3, t_4, t_5, t_6)
        cost_func = cost(i, j, k, st_x, st_y, st_z)
        c_f_1.append(cost_func)
    for counter in angle:
        i, j, k = end_point(t_1, counter, t_3, t_4, t_5, t_6)
        cost_func = cost(i, j, k, st_x, st_y, st_z)
        c_f_2.append(cost_func)
    for counter in angle:
        i, j, k = end_point(t_1, t_2, counter, t_4, t_5, t_6)
        cost_func = cost(i, j, k, st_x, st_y, st_z)
        c_f_3.append(cost_func)
    for counter in angle:
        i, j, k = end_point(t_1, t_2, t_3, counter, t_5, t_6)
        cost_func = cost(i, j, k, st_x, st_y, st_z)
        c_f_4.append(cost_func)
    for counter in angle:
        i, j, k = end_point(t_1, t_2, t_3, t_4, counter, t_6)
        cost_func = cost(i, j, k, st_x, st_y, st_z)
        c_f_5.append(cost_func)
    for counter in angle:
        i, j, k = end_point(t_1, t_2, t_3, t_4, t_5, counter)
        cost_func = cost(i, j, k, st_x, st_y, st_z)
        c_f_6.append(cost_func)
    if xd == 1:

        t_5 = c_f_5.index(min(c_f_5))
        #print('t_1:',t_1)
    if xd == 2:
        t_6 = c_f_6.index(min(c_f_6))
        #print('t_2:',t_2)

    if xd == 3:
        t_1 = c_f_1.index(min(c_f_1))
        #print('t_3:',t_3)

    if xd == 4:
        t_2 = c_f_2.index(min(c_f_2))
        #print('t_4:',t_4)

    if xd == 5:
        t_3 = c_f_3.index(min(c_f_3))
        #print('t_5:',t_5)

    if xd == 6:
        t_4 = c_f_4.index(min(c_f_4))
        #print('t_6:',t_6)
        xd = 0

    #print(t_1, t_2, t_3, t_4, t_5, t_6)
    #arm move
    x_3, y_3, z_3, r_x_1, r_y_1, r_z_1, r_x_2, r_y_2, r_z_2, r_x_3, r_y_3, r_z_3 = forward_kinematics(t_1, t_2, t_3, t_4, t_5, t_6)
    #print(t_1, t_2, t_3, t_4, t_5, t_6)

    line1, = ar.plot(r_x_1, r_y_1, r_z_1, 'r-*')
    line2, = ar.plot(r_x_2, r_y_2, r_z_2, 'g-*')
    line3, = ar.plot(r_x_3, r_y_3, r_z_3, 'b-*')
    tgt = ar.scatter(st_x, st_y, st_z, color='black')
    angle1, = sf.plot(angle, c_f_1, 'r')
    angle2, = sf.plot(angle, c_f_2, 'g')
    angle3, = sf.plot(angle, c_f_3, 'b')
    angle4, = sf.plot(angle, c_f_4, 'c')
    angle5, = sf.plot(angle, c_f_5, 'm')
    angle6, = sf.plot(angle, c_f_6, 'k')

    ar.set_xlabel('X - axis')
    ar.set_ylabel('Y - axis')
    ar.set_zlabel('Z - axis')

    xd += 1

    plt.pause(0.01)
    line1.remove()
    line2.remove()
    line3.remove()
    #tgt.remove()
    angle1.remove()
    angle2.remove()
    angle3.remove()
    angle4.remove()
    angle5.remove()
    angle6.remove()


# MAIN FILE
# ///////////////////////////////////////////////////////////////
import time
import os
from pytube import YouTube
from main import MainWindow, Settings
from plyer import notification
from pypresence import Presence

cwd = os.getcwd()

def on_progress(self, vid, chunk, bytes_remaining):
    total_size = vid.filesize
    bytes_downloaded = total_size - bytes_remaining
    percentage_of_completion = bytes_downloaded / total_size * 100
    totalsz = (total_size / 1024) / 1024
    totalsz = round(totalsz, 1)
    remain = (bytes_remaining / 1024) / 1024
    remain = round(remain, 1)
    dwnd = (bytes_downloaded / 1024) / 1024
    dwnd = round(dwnd, 1)
    percentage_of_completion = round(percentage_of_completion, 2)
    self.ui.yt_logs.append(
        f"Download Progress: {percentage_of_completion}%, Total Size:{totalsz} MB, Downloaded: {dwnd} MB, Remaining:{remain} MB"
    )
    print(
        f"Download Progress: {percentage_of_completion}%, Total Size:{totalsz} MB, Downloaded: {dwnd} MB, Remaining:{remain} MB"
    )

# WITH ACCESS TO MAIN WINDOW WIDGETS
# ///////////////////////////////////////////////////////////////
class AppFunctions(MainWindow):
    # Youtube downloader
    def downloader(self, video_link, down_dir, audio):
        try:
            tube = YouTube(video_link, on_progress_callback=on_progress)
            title = tube.title
            self.ui.yt_logs.append("Now downloading,  " + str(title))
            print("Now downloading,  " + str(title))
            video = tube.streams.filter(only_audio=audio).first()
            self.ui.yt_logs.append(
                "FileSize : " + str(round(video.filesize / (1024 * 1024))) + "MB"
            )
            print("FileSize : " + str(round(video.filesize / (1024 * 1024))) + "MB")

            if down_dir is not None:
                video.download(down_dir)
            else:
                video.download("/Users/kridsanapong/Downloads")
            print("Download complete, " + str(title))
        except Exception as e:
            print(e)
            print("ErrorDownloadVideo | " + str(video_link))

    # Notification function
    def notifyMe(self, title, message):
        notification.notify(
            title=title,
            message=message,
            timeout=10,
            app_icon=f"{cwd}/bin/Icon/iconTimer.ico",
        )

    # Discord Rich Presence
    def discordRichPresence(self, enable):
        if enable:
            try:
                rpc = Presence("902601121124728884")
                rpc.connect()

                rpc.update(  # details="Make Life Better.",
                    state="Make life better",
                    large_image="logo_new",
                    large_text="Right_posture",
                    small_image="verify",
                    small_text="Verify by right posture team",
                    buttons=[{"label": "Github", "url": "https://github.com/ussnllmn"}],
                    # party_size=[100, 100],
                    start=time.time(),
                )
                self.ui.Setting_log.append("Discord Rich Presence Connected")
                print("Discord Rich Presence Connected")
            except Exception as e:
                self.ui.Setting_log.append("Pipe Not Found - Is Discord Running?")
                print(e)

    # USE CUSTOM TITLE BAR | USE AS "False" FOR MAC OR LINUX
    Settings.ENABLE_CUSTOM_TITLE_BAR = True

    def setThemeHack(self):
        Settings.BTN_LEFT_BOX_COLOR = "background-color: #495474;"
        Settings.BTN_RIGHT_BOX_COLOR = "background-color: #495474;"
        Settings.MENU_SELECTED_STYLESHEET = MENU_SELECTED_STYLESHEET = """
        border-left: 22px solid qlineargradient(spread:pad, x1:0.034, y1:0, x2:0.216, y2:0, stop:0.499 rgba(255, 121, 198, 255), stop:0.5 rgba(85, 170, 255, 0));
        background-color: #566388;
        """
        # SET MANUAL STYLES
        self.ui.lineEdit.setStyleSheet("background-color: #6272a4;")
        self.ui.pushButton.setStyleSheet("background-color: #6272a4;")
        self.ui.plainTextEdit.setStyleSheet("background-color: #6272a4;")
        self.ui.tableWidget.setStyleSheet(
            "QScrollBar:vertical { background: #6272a4; } QScrollBar:horizontal { background: #6272a4; }"
        )
        self.ui.scrollArea.setStyleSheet(
            "QScrollBar:vertical { background: #6272a4; } QScrollBar:horizontal { background: #6272a4; }"
        )
        self.ui.comboBox.setStyleSheet("background-color: #6272a4;")
        self.ui.horizontalScrollBar.setStyleSheet("background-color: #6272a4;")
        self.ui.verticalScrollBar.setStyleSheet("background-color: #6272a4;")
        self.ui.commandLinkButton.setStyleSheet("color: #ff79c6;")


import wx

from meerk40t.gui.scene.sceneconst import RESPONSE_CHAIN, RESPONSE_CONSUME
from meerk40t.gui.toolwidgets.toolwidget import ToolWidget
from meerk40t.svgelements import Matrix, Point

class PointTool(ToolWidget):
    """
    Point Drawing Tool.

    Adds points with clicks.
    """

    def __init__(self, scene):
        ToolWidget.__init__(self, scene)

    def process_draw(self, gc: wx.GraphicsContext):
        pass

    def event(
        self,
        window_pos=None,
        space_pos=None,
        event_type=None,
        nearest_snap=None,
        modifiers=None,
        **kwargs,
    ):
        response = RESPONSE_CHAIN
        if event_type == "leftclick":
            if nearest_snap is None:
                sx, sy = self.scene.get_snap_point(
                    space_pos[0], space_pos[1], modifiers
                )
                point = Point(sx, sy)
            else:
                point = Point(nearest_snap[0], nearest_snap[1])
            elements = self.scene.context.elements
            node = elements.elem_branch.add(
                point=point,
                matrix=Matrix(),
                type="elem point",
                stroke_width=elements.default_strokewidth,
                stroke=elements.default_stroke,
                fill=elements.default_fill,
            )
            if elements.classify_new:
                elements.classify([node])
            self.notify_created(node)
            response = RESPONSE_CONSUME
        elif event_type == "lost" or (event_type == "key_up" and modifiers == "escape"):
            if self.scene.pane.tool_active:
                self.scene.pane.tool_active = False
                self.scene.request_refresh()
                response = RESPONSE_CONSUME
            else:
                response = RESPONSE_CHAIN
        return response


from pydrive2.auth import GoogleAuth
from pydrive2.files import GoogleDriveFileList, ApiRequestError

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

def authenticate(client_json_path):
	"""
	Google authentication (requires 'client_secrets.json' credentials file).
	"""
	GoogleAuth.DEFAULT_SETTINGS['client_config_file'] = client_json_path
	google_auth = GoogleAuth()
	#try:
	google_auth.LocalWebserverAuth()
		#print(ret)
	#except KeyboardInterrupt:
	#	print('Google Drive authentification complete.')

	return google_auth

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

def get_drive_folder_content(drive, id):
	"""
	Check whether the folder with id 'id' exists in Google Drive 'drive' and get the list of sub-folders.
	"""
	# Auto-iterate through all files in the parent folder
	file_list = GoogleDriveFileList()
	try:
		file_list = drive.ListFile({'q': "'{0}' in parents and trashed=false".format(id)}).GetList()
		if len(file_list) == 0:
			print('No file found in Google Drive folder with id', id)
			return False
	except ApiRequestError:
		# Exit if the parent folder doesn't exist
		print('Folder not found with id :', id)
		return False

	return file_list


import base64
import cv2
import datetime
import json
import time
import requests

API_BASE_URL = "https://eq62sd0kbj.execute-api.us-east-1.amazonaws.com"
API_PATH_NEW_ACCESS = "/prd/new-access"
url = API_BASE_URL + API_PATH_NEW_ACCESS

cam = cv2.VideoCapture(0)

cv2.namedWindow("cam")

while True:
    ret, frame = cam.read()
    if not ret:
        print("failed to grab frame")
        break
    cv2.imshow("cam", frame)

    k = cv2.waitKey(1)
    if k%256 == 27:
        # ESC pressed
        print("Escape hit, closing...")
        break
    elif k%256 == 32:
        # SPACE pressed
        retval, buffer = cv2.imencode('.jpg', frame)
        image_encoded = (base64.b64encode(buffer))
        image_encoded = image_encoded.decode("utf-8")

        _params = {"fileEncoded": image_encoded}

        params_json_dump = json.dumps(_params)

        # Enviar foto para server
        response = requests.post(url, data=params_json_dump)
        # print(response.json())

cam.release()

cv2.destroyAllWindows()