from django.contrib.auth.forms import UsernameField
from django.shortcuts import redirect, render
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
from .forms import *
from django.views.decorators.cache import never_cache
from register import *

# Create your views here.

def index(response):
        if response.user.is_authenticated:
                logged_in_user = Profile.objects.get(username=response.user)
        else:
                logged_in_user = ""
        return render(response, "main/index.html", {"response":response, "logged_in_user":logged_in_user})

def profile(response):
        if response.user.is_authenticated:
                return HttpResponseRedirect('/profile/{}'.format(response.user.username))
        else:
                return HttpResponseRedirect('/')

@never_cache
def user(response, username):
        if Profile.objects.filter(username=username):
                user = Profile.objects.get(username=username)
                education = Education.objects.filter(owner=user).order_by('-start_year')
                work = Experience.objects.filter(owner=user).order_by('-start_year')
                language = Language.objects.filter(owner=user).order_by('-rating')
                hobby = Hobby.objects.filter(owner=user)
                skills = Skill.objects.filter(owner=user).order_by('-rating')
                certificate = Certificate.objects.filter(owner=user).order_by('-year')
                educationform = EducationForm()
                workform = WorkForm()
                certificateform = CertificateForm()
                hobbyform = HobbyForm()
                if response.user.is_authenticated:
                        logged_in_user = Profile.objects.get(username=response.user)
                else:
                        logged_in_user = ""
                edit_profile_form = EditProfileForm(initial={"username":user.username, "avatar" : user.avatar, "name" : user.name, "title" : user.title, "bio" : user.biography, "location" : user.location,})
                return render(response, "main/user.html", {
                        "logged_in_user":logged_in_user,
                        "response":response,"user":user,
                        "education":education, "work":work,
                        "language":language, "hobby":hobby,
                        "skills":skills,"certificate":certificate,
                        "edit_profile_form":edit_profile_form,
                        "educationform": educationform,
                        "workform": workform,
                        "hobbyform": hobbyform,
                        "certificateform" : certificateform,
                        })
        else:
                return HttpResponse("Profile Not Found")

def edit(response):
        if response.method == 'POST':
                if response.user.is_authenticated:
                        form = EditProfileForm(response.POST, response.FILES)
                        if 'submit-clear' in response.POST:
                                profile = Profile.objects.get(username=response.user.username)
                                profile.avatar.delete()
                                profile.save()
                                return HttpResponseRedirect('/profile/{}#editmodal'.format(response.user.username))
                        if form.is_valid():
                                profile = Profile.objects.get(username=response.user.username)
                                if response.FILES:
                                        profile.avatar = response.FILES['avatar']
                                profile.color = response.POST['form-color']
                                profile.name = form.cleaned_data['name'].strip()
                                profile.title = form.cleaned_data['title'].strip()
                                profile.biography = form.cleaned_data['bio'].strip()
                                profile.location = form.cleaned_data['location'].strip()
                                profile.save()
                                return HttpResponseRedirect('/profile/{}'.format(response.user.username))
                        else:
                                print(form.cleaned_data)
                                print(form.errors)
                                return HttpResponseRedirect('/one/{}'.format(response.user.username))
                else:
                        return HttpResponseRedirect('/two/{}'.format(response.user.username))
        else:
                return HttpResponseRedirect('/three/{}'.format(response.user.username))

def add(response):
         if response.method == 'POST':
                if response.user.is_authenticated:
                        if 'submit-addeducation' in response.POST:
                                form = EducationForm(response.POST)
                                if form.is_valid():
                                        print(form.cleaned_data)
                                        edu = Education()
                                        edu.owner = Profile.objects.get(username=response.user.username)
                                        edu.start_year = form.cleaned_data['start_year']
                                        edu.end_year = form.cleaned_data['end_year']
                                        edu.department = form.cleaned_data['department']
                                        edu.school = form.cleaned_data['school']
                                        edu.is_highschool = form.cleaned_data['is_highschool']
                                        edu.save()
                                        return HttpResponseRedirect('/profile/{}'.format(response.user.username))
                        if 'submit-addwork' in response.POST:
                                form = WorkForm(response.POST)
                                if form.is_valid():
                                        work = Experience()
                                        work.owner = Profile.objects.get(username=response.user.username)
                                        work.start_year = form.cleaned_data['start_year']
                                        work.end_year = form.cleaned_data['end_year']
                                        work.position = form.cleaned_data['position']
                                        work.firm = form.cleaned_data['firm']
                                        work.save()
                                        return HttpResponseRedirect('/profile/{}'.format(response.user.username))
                        if 'submit-addskill' in response.POST:
                                form = SkillForm(response.POST)
                                if form.is_valid():
                                        skill = Skill()
                                        skill.owner = Profile.objects.get(username=response.user.username)
                                        skill.name = form.cleaned_data['name']
                                        skill.rating = form.cleaned_data['rating']
                                        skill.save()
                                        return HttpResponseRedirect('/profile/{}'.format(response.user.username))
                        if 'submit-addlang' in response.POST:
                                form = LanguageForm(response.POST)
                                if form.is_valid():
                                        lang = Language()
                                        lang.owner = Profile.objects.get(username=response.user.username)
                                        lang.name = form.cleaned_data['name']
                                        lang.rating = form.cleaned_data['rating']
                                        lang.save()
                                        return HttpResponseRedirect('/profile/{}'.format(response.user.username))
                        if 'submit-addhobby' in response.POST:
                                form = HobbyForm(response.POST)
                                if form.is_valid():
                                        hobby = Hobby()
                                        hobby.owner = Profile.objects.get(username=response.user.username)
                                        hobby.name = form.cleaned_data['name']
                                        hobby.description = form.cleaned_data['description']
                                        hobby.save()
                                        return HttpResponseRedirect('/profile/{}'.format(response.user.username))
                        if 'submit-addcert' in response.POST:
                                form = CertificateForm(response.POST)
                                if form.is_valid():
                                        cert = Certificate()
                                        cert.owner = Profile.objects.get(username=response.user.username)
                                        cert.type = form.cleaned_data['type']
                                        cert.description = form.cleaned_data['description']
                                        cert.year = form.cleaned_data['year']
                                        cert.save()
                                        return HttpResponseRedirect('/profile/{}'.format(response.user.username))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug  8 11:26:45 2019

@author: burr
"""

from sklearn.discriminant_analysis import LinearDiscriminantAnalysis

from sklearn.model_selection import KFold
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
import sklearn as sk

import pandas as pd
from matplotlib import pyplot as plt
from fileutils import labellist
from learningfunctions import Kfold_validation, evaluate, normalize, print_top5, plotfeatureimportance, decodelabels
from learningfunctions import extractdifffeaturevectors, changelabeltoeventbased
from features import columns
plt.close('all')

df = pd.DataFrame(columns=columns)
appliancesublist = ['laptop', 'heatbulb', 'fluorescentlight', 'kettle', 'fan2']

y5, df5 = extractdifffeaturevectors('data/5_MassiveSwitching/featurescomplete', appliancesublist)
y5 = changelabeltoeventbased(y5)

y2, df2 = extractdifffeaturevectors('data/2_WithSwitchingEvents/featurescomplete', appliancesublist)
y2 = changelabeltoeventbased(y2)

y5.extend(y2)
dfmodel = df5.append(df2, ignore_index=True)

y = y5

#X = dfmodel.drop(['label'], axis=1)
dfmodel = dfmodel[['apparent_power', 'real_power', 'nonactive_power',
'imag01', 'imag03', 'imag05', 'imag07', 'imag09',
'imag11', 'imag13', 'imag15', 'imag17', 'imag19',
#'imag21', 'imag23', 'imag25', 'imag27', 'imag29',
#'imag31', 'imag33', 'imag35', 'imag37', 'imag39',
#'imag41', 'imag43', 'imag45', 'imag47', 'imag49',
#'imag51', 'imag53', 'imag55', 'imag57', 'imag59',
#
#
'real01', 'real03', 'real05', 'real07', 'real09',
'real11', 'real13', 'real15', 'real17', 'real19',
#'real21', 'real23', 'real25', 'real27', 'real29',
#'real31', 'real33', 'real35', 'real37', 'real39',
#'real41', 'real43', 'real45', 'real47', 'real49',
#'real51', 'real53', 'real55', 'real57', 'real59',
#
]]
X = dfmodel
X = X.values

X_train = X
y_train = y
X_train, X_test, y_train, y_test = sk.model_selection.train_test_split(X, y, test_size=0.33, random_state=12)

model1 = RandomForestClassifier(n_estimators =1000,min_samples_leaf=1, max_leaf_nodes=10,random_state=10)
#model1 = KNeighborsClassifier(n_neighbors=1, leaf_size=10)
#model1 = SVC(C=0.001, gamma=0.0001, kernel='linear')

model1.fit(X_train, y_train)
y_pred = model1.predict(X_test)
print('On Model Dataset')
evaluate(y_test, y_pred, labellist, plotconfusionmatrix="2OnModel2")
#print_top5(dfmodel.columns, axis=1).columns, model1)
#plotfeatureimportance(model1, dfmodel)

#
yunseen1, dfunseen1 = extractdifffeaturevectors('data/3_MultipleDevices_Order10/featurescomplete', ['0order'])
yunseen2, dfunseen2 = extractdifffeaturevectors('data/3_MultipleDevices_Order10/featurescomplete', ['1order'])
yunseen3, dfunseen3 = extractdifffeaturevectors('data/3_MultipleDevices_Order11/featurescomplete', ['0order'])
yunseen4, dfunseen4 = extractdifffeaturevectors('data/3_MultipleDevices_Order11/featurescomplete', ['1order'])
yunseen1.extend(yunseen2)
yunseen1.extend(yunseen3)
yunseen1.extend(yunseen4)
yunseen=yunseen1

dfunseen1=dfunseen1.append(dfunseen2, ignore_index=True)#.append(dfunseen3, ignore_index=True).append(dfunseen4, ignore_index=True)
dfunseen1=dfunseen1.append(dfunseen3, ignore_index=True)
dfunseen1=dfunseen1.append(dfunseen4, ignore_index=True)
dfunseen=dfunseen1
#Xunseen = dfunseen.drop(['label'],axis=1)

dfunseen = dfunseen[['apparent_power', 'real_power', 'nonactive_power',
'imag01', 'imag03', 'imag05', 'imag07', 'imag09',
'imag11', 'imag13', 'imag15', 'imag17', 'imag19',
#'imag21', 'imag23', 'imag25', 'imag27', 'imag29',
#'imag31', 'imag33', 'imag35', 'imag37', 'imag39',
#'imag41', 'imag43', 'imag45', 'imag47', 'imag49',
#'imag51', 'imag53', 'imag55', 'imag57', 'imag59',
#
#
'real01', 'real03', 'real05', 'real07', 'real09',
'real11', 'real13', 'real15', 'real17', 'real19',
#'real21', 'real23', 'real25', 'real27', 'real29',
#'real31', 'real33', 'real35', 'real37', 'real39',
#'real41', 'real43', 'real45', 'real47', 'real49',
#'real51', 'real53', 'real55', 'real57', 'real59',
#
]]
Xunseen = dfunseen

Xunseen = Xunseen.values

y_unseenpred = model1.predict(Xunseen)
evaluate(yunseen, y_unseenpred, labellist, plotconfusionmatrix="2OnUnseen3")


# -*- coding: utf-8 -*-

import os
import pickle
import time
import logging
import inspect
from pkg_resources import parse_version

_LOGGER = logging.getLogger(__name__)

class Tools:

    @staticmethod
    def get_next_major_version(version):
        """
        Given a parsed version from pkg_resources.parse_version, returns a new
        version string with the major minor version.

        Examples
        ========
        >>> _next_major_version(pkg_resources.parse_version('1.2.3'))
        '2.0.0'
        """

        if hasattr(version, 'base_version'):
            # New version parsing from setuptools >= 8.0
            if version.base_version:
                parts = version.base_version.split('.')
            else:
                parts = []
        else:
            parts = []
            for part in version:
                if part.startswith('*'):
                    break
                parts.append(part)

        parts = [p for p in parts]

        if len(parts) < 3:
            parts += [0] * (3 - len(parts))

        major, minor, micro = parts[:3]

        try:
            major = int(major)
        except:
            return None

        return parse_version('{0}.{1}.{2}'.format(major + 1, 0, 0))

    @staticmethod
    def get_next_major_version_prerelease(version):
        """
        Given a parsed version from pkg_resources.parse_version, returns a new
        version string with the next major version included '-dev0' to ignore new pre-release.

        Examples
        ========
        >>> _next_major_version(pkg_resources.parse_version('1.2.3'))
        '2.0.0-r0'
        """
        return parse_version('{0}-dev0'.format(Tools.get_next_major_version(version)))


from zipfile import ZipFile
import os

caminho = r'E:\Danilo Gomes\Pictures'

with ZipFile(r'aula137\arquivo.zip', 'w') as zip:
    for arquivo in os.listdir(caminho):
        #print(arquivo)
        if 'PNG' in arquivo or '.jpg' in arquivo:
            caminho_completo = os.path.join(caminho, arquivo)
            zip.write(caminho_completo, arquivo)

with ZipFile(r'aula137\arquivo.zip', 'r') as zip:
    for arquivo in zip.namelist():
        print(arquivo)

with ZipFile(r'aula137\arquivo.zip', 'r') as zip:
    zip.extractall(r'aula137\descompactado')


#!/usr/bin/env python

"""
    File name: plot_triplet_parameters.py
    Author: Halla Sigurthorsdottir, Christoph Blattgerste, Giorgia Dellaferrera
    Date created: 06/10/2016
    Date last modified: 18/09/2018
    Python Version: 2.7
"""

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

def plot_triplet_p(m, title=None):
    plt.subplot(221)
    plt.plot(m['syn_monitor'].t, m['syn_monitor'].o_1[0])
    plt.ylabel('o_1')

    plt.subplot(222)
    plt.plot(m['syn_monitor'].t, m['syn_monitor'].o_2[0])
    plt.ylabel('o_2')

    plt.subplot(223)
    plt.plot(m['syn_monitor'].t, m['syn_monitor'].r_1[0])
    plt.ylabel('r_1')
    plt.xlabel('t (s)')

    plt.subplot(224)
    plt.plot(m['syn_monitor'].t, m['syn_monitor'].r_2[0])
    plt.ylabel('r_2')
    plt.xlabel('t (s)')

    plt.title(title)

    plt.show()

def plot_prepost_spikes(m, voltage=True, title=None):
    '''
    This function plots the pre- and postsynaptic spikes as well as the voltage of the postsynaptic neuron (if voltage is True).
    '''
    plt.plot(m['pre_spikes'].t, -0.07 * np.ones(len(m['pre_spikes'].t)), '*')
    leg = ['Presynaptic spikes']

    if len(m['post_spikes'].t) > 0:
        plt.plot(m['post_spikes'].t, -0.07 * np.ones(len(m['post_spikes'].t)), '*')
        leg += ['Postsynaptic_spikes']

    if voltage:
        for i in range(m['post_monitor'].v.shape[0]):
            plt.plot(m['post_monitor'].t, m['post_monitor'].v[i])
            leg += ['Voltage of neuron' + str(i)]
            plt.ylabel('Voltage (V)')

    plt.legend(leg, loc='upper right')
    plt.xlabel('Time (s)')
    if not title is None:
        plt.title(title)

    plt.show()

def plot_w(m, no_syn=None, title=None):
    '''
    This function plots the weight change over time.
    '''
    leg = [0] * m['syn_monitor'].w_ampa.shape[0]
    if no_syn == None:
        no_syn = m['syn_monitor'].w_ampa.shape[0]
    else:
        no_syn = no_syn

    for i in range(no_syn):
        plt.figure()
        plt.plot(m['syn_monitor'].t, m['syn_monitor'].w_ampa[i])
        leg[i] = 'Synapse ' + str(i)

        plt.xlabel('Time (s)')
        plt.ylabel('Weight')
        plt.legend(leg)
        if not title is None:
            plt.title(title)

        plt.show()

def plot_rs_os(m, no_syn=None, title=None):
    '''
    This function plots the change of r_1, r_2, o_1, o_2 over time.
    '''
    leg = [0] * m['syn_monitor'].w_ampa.shape[0]
    if no_syn == None:
        no_syn = m['syn_monitor'].w_ampa.shape[0]
    else:
        no_syn = no_syn

    rs_and_os = True

    if rs_and_os == True:
        for i in range(no_syn):
            plt.figure()
            plt.plot(m['syn_monitor'].t, m['syn_monitor'].r_1[i], label='r_1')
            plt.plot(m['syn_monitor'].t, m['syn_monitor'].r_2[i], label='r_2')
            plt.plot(m['syn_monitor'].t, m['syn_monitor'].o_1[i], label='o_1')
            plt.plot(m['syn_monitor'].t, m['syn_monitor'].o_2[i], label='o_2')
            # leg[i] = 'Synapse ' + str(i)

            plt.xlabel('Time (s)')
            plt.ylabel('Weight')
            plt.legend()
            if not title is None:
                plt.title(title)

            plt.show()

def plot_spikes(m, save_in_path=False, path=None, show=False, title=None, no_poisson_spikes=15, poisson_pop=False):
    '''
    This function plots 20 (or input) pre spike arrivals and 10 (or input) post spike times.
    '''

    if len(m['post_spikes'].spike_trains()) < 10:
        no_post_spikes = len(m['post_spikes'].spike_trains())
    else:
        no_post_spikes = 10
    if len(m['pre_spikes'].spike_trains()) < 10:
        no_pre_spikes = len(m['pre_spikes'].spike_trains())
    else:
        no_pre_spikes = 10

    no_spikes = no_pre_spikes + no_post_spikes
    print('number of pre spike trains: {}'.format(no_pre_spikes))
    print('number of post spike trains: {}'.format(no_post_spikes))

    if poisson_pop == True:
        no_spikes += no_poisson_spikes

    # Prepare pre spike list
    pre_ids = random.sample(range(len(m['pre_spikes'].spike_trains())), no_pre_spikes)
    pre_spikes = [0] * no_pre_spikes
    for i in range(no_pre_spikes):
        pre_spikes[i] = m['pre_spikes'].spike_trains()[pre_ids[i]]

    # Prepare post spike list
    print(len(m['post_spikes'].spike_trains()), no_post_spikes)

    post_ids = random.sample(range(len(m['post_spikes'].spike_trains())), no_post_spikes)
    post_spikes = [0] * no_post_spikes
    for i in range(no_post_spikes):
        post_spikes[i] = m['post_spikes'].spike_trains()[post_ids[i]]

    if poisson_pop:
        # Prepare poisson spike list
        poisson_ids = random.sample(range(len(m['poisson_spikes'].spike_trains())), no_poisson_spikes)
        poisson_spikes = [0] * no_poisson_spikes
        for i in range(no_poisson_spikes):
            poisson_spikes[i] = m['poisson_spikes'].spike_trains()[poisson_ids[i]]

    # For the legend
    plt.plot(pre_spikes[0], no_spikes * np.ones(len(pre_spikes[0])), '|k')
    plt.plot(post_spikes[0], (no_spikes - no_pre_spikes) * np.ones(len(post_spikes[0])), '|r')
    if poisson_pop:
        plt.plot(poisson_spikes[0], (no_spikes - no_pre_spikes - no_poisson_spikes) * np.ones(len(poisson_spikes[0])),
                 '*b')

    for i in range(len(pre_spikes)):
        plt.plot(pre_spikes[i], (no_spikes - i) * np.ones(len(pre_spikes[i])), '|k', linewidth=3)

    for i in range(len(post_spikes)):
        plt.plot(post_spikes[i], (no_spikes - i - no_pre_spikes) * np.ones(len(post_spikes[i])), '|r', linewidth=3)

    if poisson_pop:
        for i in range(len(poisson_spikes)):
            plt.plot(poisson_spikes[i],
                     (no_spikes - i - no_pre_spikes - no_poisson_spikes) * np.ones(len(poisson_spikes[i])), '*b',
                     linewidth=3)

        # added by GD to monitor spike times
        # print('one train of pre spikes',pre_spikes[0])
        # print('one train of pre spikes',pre_spikes[1])
        # print('one train of pre spikes',pre_spikes[2])
        # print('one train of pre spikes',pre_spikes[3])
        # print('one train of post spikes',post_spikes[0])
        # print('one train of post spikes',post_spikes[1])
        # print('one train of post spikes',post_spikes[2])
        # print('one train of post spikes',post_spikes[3])
        # if poisson_pop:
        # print('one train of poisson spikes',poisson_spikes[0])
        # print('one train of poisson spikes',poisson_spikes[1])
        # print('one train of poisson spikes',poisson_spikes[2])

    # save the result to a text file
    # path = '../GD/fill_the_grid/sLFS/varyingNb/hippoplasticity/added_poisson_input/Clopath_long_tau_refract/'
    # path = '../GD/fill_the_grid/sLFS/varyingNb/visualplast/withpoisson_long_tau_refract/'
    # path = '../GD/puppet/100pulses_08Hz/'

    path = '../data/'
    name = 'Spike trains'
    out_name = path + name
    # save pre spikes
    np.savetxt(out_name + 'pre0.txt', pre_spikes[0])
    np.savetxt(out_name + 'pre1.txt', pre_spikes[1])
    np.savetxt(out_name + 'pre2.txt', pre_spikes[2])
    np.savetxt(out_name + 'pre3.txt', pre_spikes[3])
    # save post spikes
    np.savetxt(out_name + 'post0.txt', post_spikes[0])
    np.savetxt(out_name + 'post1.txt', post_spikes[1])
    np.savetxt(out_name + 'post2.txt', post_spikes[2])
    np.savetxt(out_name + 'post3.txt', post_spikes[3])
    # save poisson spikes
    if poisson_pop:
        np.savetxt(out_name + 'poisson0.txt', poisson_spikes[0])
        np.savetxt(out_name + 'poisson1.txt', poisson_spikes[1])
        np.savetxt(out_name + 'poisson2.txt', poisson_spikes[2])
        np.savetxt(out_name + 'poisson3.txt', poisson_spikes[3])

    plt.legend(['Presynaptic spikes', 'Postsynaptic spikes'], loc='upper right', fontsize=14)
    plt.xlabel('Time (s)', fontsize=20)
    plt.ylabel('Neuron index', fontsize=20)  # added by GD
    plt.savefig('../fig/spike_train.pdf', format='PDF')

    if not title is None:
        plt.title(title, fontsize=20)
    plt.tight_layout()
    if show:
        plt.show()
    if save_in_path and path is not None:
        plt.savefig(path + "spike_plot.pdf", format="PDF")

def plot_mean_weight(m, filename=None, path=None, title=None, show=False):
    """
    This function plots the mean synaptic weight over time.
    :param m:
    :param filename:
    :param path:
    :param title:
    :param show:
    :return:
    """

    plt.plot(m['syn_monitor'].t, np.mean(m['syn_monitor'].w_ampa, 0))
    plt.ylabel('mean weight', fontsize=18)
    plt.xlabel('time $[s]$', fontsize=18)

    if title is not None:
        plt.title(title, fontsize=18)
    plt.tight_layout()
    if show:
        plt.show()

    if filename != None and path != None:
        try:
            plt.savefig(path + filename + '.pdf', format='PDF')
        except:
            print("Wrong combination of path and filename - image not saved")

def visualize_connectivity(S, save_in_path=False):  # S is a Synapses object
    '''
    Plot a two different graps to visualize connectivity between each pre- and postsynaptic neuron.
    '''

    Ns = len(S.source)  # number of source neurons
    Nt = len(S.target)  # number of target neurons
    plt.figure(figsize=(10, 4))
    plt.subplot(121)
    plt.plot(np.zeros(Ns), np.arange(Ns), 'ok', ms=10)  # draw source neurons
    plt.plot(np.ones(Nt), np.arange(Nt), 'ok', ms=10)  # draw target neurons
    for i, j in zip(S.i, S.j):
        plt.plot([0, 1], [i, j], '-k')  # draw lines between them
        plt.xticks([0, 1], ['Source', 'Target'])
    plt.ylabel('Neuron index')
    plt.xlim(-0.1, 1.1)
    plt.ylim(-1, max(Ns, Nt))
    plt.title('Connectivity: Source to Target')

    print(S.i)
    for n in range(max(S.j)):
        indizes = np.where(S.j == n)
        print('Synapses at post neuron {} - {}'.format(n, len(indizes[0])))
    plt.subplot(122)
    plt.plot(S.i, S.j, 'ok')
    plt.xlim(-1, Ns)
    plt.ylim(-1, Nt)
    plt.xlabel('Source neuron index')
    plt.ylabel('Target neuron index')
    plt.title('Connectivity Matrix')
    if save_in_path:
        plt.savefig('../fig/pre:{}_post:{}_connect.pdf'.format(max(S.i), max(S.j)), format='PDF')
    plt.show()


"""
Module to store the functions that will make up a 'from scratch'
implementation of the k-nearest neighbors model for predictions
from a vector dataset
"""

from collections import Counter
from math import pow
from math import sqrt
from math import fsum
from operator import itemgetter

def euclidean_distance(vector1, vector2, length):
    """
    Compute distance between two vector of arbitrary length
    containing an arbitrary number of numerical values

    Args:
        vector1 (list): first vector
        vector2 (list): second vector
        length (int): length of vectors

    Returns:
        float representing the euclidean distance between the two vectors
    """
    distance = fsum([
        pow((vector1[i] - vector2[i]), 2) for i in range(length)
    ])
    return sqrt(distance)

def find_k_neighbors(query,
                     dataset,
                     k,
                     vector_length,
                     return_distances=False):
    """
    Return k vectors from dataset nearest to the query vector

    Args:
        query (list): vector for which neighbors will be found
        dataset (list): collection of vectors from which neighbors will
            be found
        k (int): number of neighbors to be returned
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        return_distances (bool): optional argument to enable find_k_neighbors
            to return distance values

    Returns:
        list of k vectors found to be nearest neighbors
    """
    distances = []
    for row in dataset:
        eu_dist = euclidean_distance(query, row, vector_length)
        distances.append((row, eu_dist))
    distances.sort(key=itemgetter(1))
    neighbors = [row[0] for row in distances[:k]]
    if return_distances:
        return neighbors, [row[1] for row in distances[:k]]
    else:
        return neighbors

def calc_category_frequency(dataset, vector_length, category_index=-1):
    """
    Return frequencies of the category variables in dataset

    Args:
        dataset (list): collection of vectors from which neighbors will
            be found
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        category_index (int): optional argument to select a specific element
            by index as the predicted category in the dataset rows;
            default is index in position one beyond length of query vector

    Returns:
        Counter object with frequencies of the category values in dataset
    """
    if category_index < 0:
        category_index = vector_length
    frequencies = Counter(
        [row[category_index] for row in dataset]
    )
    return frequencies

def predict_category_from_knn(query,
                              dataset,
                              k,
                              vector_length,
                              category_index=-1):
    """
    Return a category for query vector by knn algorithm applied to dataset

    Args:
        query (list): vector for which neighbors will be found
        dataset (list): collection of vectors from which neighbors will
            be found
        k (int): number of neighbors to be returned
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        category_index (int): optional argument to select a specific element
            by index as the predicted category in the dataset rows;
            default is index in position one beyond length of query vector

    Returns:
        nested list with knn "votes" by category sorted by descending votes
    """
    if category_index < 0:
        category_index = vector_length
    neighbors = find_k_neighbors(query, dataset, k, vector_length)
    votes = calc_category_frequency(neighbors,
                                    vector_length,
                                    category_index=category_index)
    predictions = [[key, value] for key, value in votes.iteritems()]
    predictions.sort(key=itemgetter(1))
    return predictions

def predict_knn_classes_from_set(test_set,
                                 training_set,
                                 k,
                                 vector_length,
                                 category_index=-1):
    """loop over the test set and generate predictions for each feature row

    Args:
        test_set (list): collection of vectors for which predictions are made
        dataset (list): collection of vectors from which neighbors will
            be found
        k (int): number of neighbors to be returned
        vector_length (int): equals the length of the vector to be used in
            distance measurement; assumes numbers are stored in the first
            `vector_length` units of the vector, predicted or descriptive
            content are assumed to be in the remaining portion of the vector
            if applicable
        category_index (int): optional argument to select a specific element
            by index as the predicted category in the dataset rows;
            default is index in position one beyond length of query vector
    """
    if category_index < 0:
        category_index = vector_length
    test_set_predictions = []
    for row in test_set:
        predictions = predict_category_from_knn(row,
                                                training_set,
                                                k,
                                                vector_length,
                                                category_index=category_index)
        prediction = predictions[0][0]
        test_set_predictions.append(prediction)
    return test_set_predictions


from decimal import Decimal
from typing import TYPE_CHECKING

from kivy.app import App
from kivy.factory import Factory
from kivy.properties import ObjectProperty
from kivy.lang import Builder
from kivy.uix.checkbox import CheckBox
from kivy.uix.label import Label
from kivy.uix.widget import Widget
from kivy.clock import Clock

from electrum.simple_config import FEERATE_WARNING_HIGH_FEE, FEE_RATIO_HIGH_WARNING
from electrum.gui.kivy.i18n import _
from electrum.plugin import run_hook
from electrum.util import NotEnoughFunds

#from .fee_dialog import FeeSliderDialog

if TYPE_CHECKING:
    from electrum.gui.kivy.main_window import ElectrumWindow

Builder.load_string('''
<ConfirmTxDialog@Popup>
    id: popup
    title: _('Confirm Payment')
    message: ''
    warning: ''
    extra_fee: ''
    show_final: False
    size_hint: 0.8, 0.8
    pos_hint: {'top':0.9}
    method: 0
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, 0.5
            Label:
                text: _('Amount to be sent:')
            Label:
                id: amount_label
                text: ''
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, 0.5
            Label:
                text: _('Mining fee:')
            Label:
                id: fee_label
                text: ''
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, (0.5 if root.extra_fee else 0.01)
            Label:
                text: _('Additional fees') if root.extra_fee else ''
            Label:
                text: root.extra_fee
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, 0.5
            Label:
                text: _('Fee rate:')
            Label:
                id: feerate_label
                text: ''
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, 0.2
            Label:
                text: _('Final')
                opacity: int(root.show_final)
            CheckBox:
                id: final_cb
                opacity: int(root.show_final)
                disabled: not root.show_final
        Label:
            text: root.warning
            text_size: self.width, None
        Widget:
            size_hint: 1, 0.5
        BoxLayout:
            orientation: 'horizontal'
            size_hint: 1, 0.5
            Button:
                text: _('Cancel')
                size_hint: 0.5, None
                height: '48dp'
                on_release:
                    popup.dismiss()
            Button:
                id: ok_button
                text: _('OK')
                size_hint: 0.5, None
                height: '48dp'
                on_release:
                    root.on_pay(root.tx)
                    popup.dismiss()
''')

class ConfirmTxDialog(Factory.Popup):

    def __init__(self, app: 'ElectrumWindow', amount, make_tx, on_pay, *, show_final=True):

        Factory.Popup.__init__(self)
   #     FeeSliderDialog.__init__(self, app.electrum_config, self.ids.slider)
        self.app = app
        self.amount = amount
        self.make_tx = make_tx
        self.on_pay = on_pay
        self.show_final = show_final
       # self.update_slider()
    #    self.update_text()
        self.update_tx()

    def update_tx(self):
        rbf = not bool(self.ids.final_cb.active) if self.show_final else False
        try:
            # make unsigned transaction
            tx = self.make_tx(rbf)
        except NotEnoughFunds:
            self.warning = _("Not enough funds")
            self.ids.ok_button.disabled = True
            return
        except Exception as e:
            self.ids.ok_button.disabled = True
            self.app.logger.exception('')
            self.app.show_error(repr(e))
            return
        self.ids.ok_button.disabled = False
        amount = self.amount if self.amount != '!' else tx.output_value()
        tx_size = tx.estimated_size()
        fee = tx.get_fee()
        self.ids.fee_label.text = self.app.format_amount_and_units(fee)
        feerate = Decimal(fee) / tx_size  # sat/byte
        self.ids.feerate_label.text = f'{feerate:.1f} doggies/B'
        self.ids.amount_label.text = self.app.format_amount_and_units(amount)
        x_fee = run_hook('get_tx_extra_fee', self.app.wallet, tx)
        if x_fee:
            x_fee_address, x_fee_amount = x_fee
            self.extra_fee = self.app.format_amount_and_units(x_fee_amount)
        else:
            self.extra_fee = ''
        fee_warning_tuple = self.app.wallet.get_tx_fee_warning(
            invoice_amt=amount, tx_size=tx_size, fee=fee)
        if fee_warning_tuple:
            allow_send, long_warning, short_warning = fee_warning_tuple
            self.warning = long_warning
        else:
            self.warning = ''
        self.tx = tx

  #  def on_slider(self, value):
   #     self.save_config()
    #    self.update_text()
     #   Clock.schedule_once(lambda dt: self.update_tx())

 #   def update_text(self):
#        target, tooltip, dyn = self.config.get_fee_target()
#        self.ids.fee_button.text = target


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):
    dependencies = [
        ('members', '0005_auto_20160219_1531'),
    ]

    operations = [
        migrations.AlterField(
            model_name='member',
            name='honorary',
            field=models.BooleanField(default=False, help_text='Honorary member'),
        ),
        migrations.AlterField(
            model_name='member',
            name='lifetime',
            field=models.BooleanField(default=False, help_text='Lifetime member'),
        ),
    ]


#!/usr/bin/env python

import argparse
import cv2 as cv
import os

def get_image_files(path):
    return sorted([os.path.join(path, f) for f in os.listdir(path) if f.endswith('.png') or f.endswith('.jpg')])

def put_mask(sample_image_filename, mask_filename):
    input_image = cv.imread(sample_image_filename)
    mask = cv.imread(mask_filename, 0)
    mask = cv.bitwise_not(mask)

    output_image = cv.bitwise_or(input_image, input_image, mask=mask)

    return output_image

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description="Put a given mask on provided set of images")
    parser.add_argument('--mode',
                        required=True,
                        choices=['sample', 'folder'])
    parser.add_argument('--mask',
                        required=True,
                        type=str)
    parser.add_argument('--raw_sample_image',
                        required=False,
                        type=str)
    parser.add_argument('--raw_image_folder',
                        required=False,
                        type=str)
    parser.add_argument('--masked_image_folder',
                        required=False,
                        type=str)
    args = parser.parse_args()

    if args.mode == 'folder':
        masked_image_folder = args.masked_image_folder
        if not os.path.exists(masked_image_folder):
            os.makedirs(masked_image_folder)
            print(f'Folder {masked_image_folder} created successfully')

        image_files = get_image_files(args.raw_image_folder)
        for i in range(len(image_files)):
            output_image = put_mask(image_files[i], args.mask)
            cv.imwrite(os.path.join(masked_image_folder, os.path.basename(image_files[i])), output_image)

    if args.mode == 'sample':
        output_image = put_mask(args.raw_sample_image, args.mask)
        cv.imshow("test", output_image)
        cv.waitKey(0)


# -*- coding: utf-8 -*-
# Name: attention.py
# Author: Shao Shidong
# Date: 2020/5/24
# Version: Python 3.6 64-bit

import torch
from utils.utils import length_to_mask
from torch.nn import Module
from torch.nn import Linear
from torch.nn import Softmax

class Attention(Module):
    def __init__(self):
        super(Attention,self).__init__()

    def forward(self, value, key=None, query=None, mask=None):
        if key is None:
            key = query
        if query is None:
            query = value
        attention_weights = self.score(query, key, mask)
        context = attention_weights.matmul(value)
        return context, attention_weights

class GeneralAttention(Attention):
    def __init__(self, hidden_dim):
        super(GeneralAttention,self).__init__()
        self.hidden_dim = hidden_dim
        self.W = Linear(in_features = hidden_dim, out_features = hidden_dim)
        self.softmax = Softmax(dim=-1)

    def score(self, query, key, mask=None):
        key = key.permute(0,2,1)
        atten = self.W(query).matmul(key)
        minimum = -float('inf')
        if mask is not None:
            atten.masked_fill_(mask, minimum)
        atten = atten.permute(0,2,1)
        attention_weights = self.softmax(atten)
        return attention_weights

class UniformAttention(Attention):
    def __init__(self):
        super(UniformAttention, self).__init__()
        self.softmax = Softmax(dim=-1)

    def score(self, query, key=None, mask=None):
        batch_size, seq_len, hidden_dim = query.shape
        atten = torch.ones(batch_size, seq_len, 1, device = query.device)
        minimum = -float('inf')
        if mask is not None:
            atten.masked_fill_(mask,minimum)
        atten = atten.permute(0,2,1)
        attention_weights = self.softmax(atten)
        return attention_weights

class ConditionalAttention(Module):
    def __init__(self, hidden_dim, use_bag_of_word=False):
        super(ConditionalAttention, self).__init__()
        self.hidden_dim = hidden_dim
        self.attention = GeneralAttention(hidden_dim)
        self.bag_of_word = UniformAttention()
        self.W = Linear(in_features=hidden_dim, out_features=hidden_dim)
        self.use_bag_of_word = use_bag_of_word

    def forward(self, variable, condition, variable_lengths=None, condition_lengths=None):
        if variable_lengths is None and condition_lengths is None:
            mask_var_cond = None
            mask_cond = None
        elif condition_lengths is None:
            mask_var_cond = length_to_mask(variable_lengths).to(variable.device)
            mask_cond = None
        else:
            mask_var_cond = length_to_mask(variable_lengths, condition_lengths).to(variable.device)
            mask_cond = length_to_mask(condition_lengths).to(variable.device)
        H_var_cond, _ = self.attention(variable, key=condition, mask=mask_var_cond)
        if self.use_bag_of_word:
            H_var_cond, _ = self.bag_of_word(H_var_cond, mask=mask_cond)
            H_var_cond = H_var_cond.squeeze(1)
        H_var_cond = self.W(H_var_cond)
        return H_var_cond

class BagOfWord(Module):
    def __init__(self):
        super(BagOfWord, self).__init__()
        self.attention = UniformAttention()

    def forward(self, variable, lengths):
        mask = length_to_mask(lengths)
        mask = mask.to(variable.device)
        context, _ = self.attention(variable, mask=mask)
        context = context.squeeze(1)
        return context


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

# Parameters to change
gap = 10
space = 20
magnet_size = [30, 20, 100]
iron_top_height = 30
iron_side_width = 40
divisions = [5, 5, 5]

strength = [0, 0, 0]

# Magnet and iron properties
magnet_material = rad.MatLin([0.05, 0.15], [0, 1.3, 0])
magnet_color = [0, 0, 1]
iron_material = rad.MatStd('Xc06')
iron_color = [0, 1, 0]

magnet_center = [0, magnet_size[1] / 2 + gap / 2, 0]
iron_top_size = [magnet_size[0] + space, iron_top_height, magnet_size[2]]
iron_halfside_size = [iron_side_width, magnet_size[1] + gap / 2 + iron_top_size[1], magnet_size[2]]
iron_top_center = [+(magnet_size[0] - iron_top_size[0])/2, magnet_size[1] + gap/2 + iron_top_size[1]/2, 0]
iron_halfside_center = [-(magnet_size[0]/2 + space + iron_halfside_size[0]/2), iron_halfside_size[1]/2, 0]

dipole = rad.ObjCnt([])

magnet_top = rad.ObjFullMag(
    magnet_center,
    magnet_size,
    strength,
    divisions,
    dipole, #module do later
    magnet_material,
    magnet_color
)

iron_top = rad.ObjFullMag(
    iron_top_center,
    iron_top_size,
    strength,
    divisions,
    dipole, #module do later
    iron_material,
    iron_color
)

iron_halfside = rad.ObjFullMag(
    iron_halfside_center,
    iron_halfside_size,
    strength,
    divisions,
    dipole, #module do later
    iron_material,
    iron_color
)
rad.TrfZerPara(dipole, [0,0,0], [0,1,0])

rad.Solve(dipole, 0.0003, 1000)

print('field at center', rad.Fld(dipole, 'b', [0, 0, 0]), '(T)')

# Make some plots

zstart = -magnet_size[2]
zstop = -zstart
Z = np.linspace(zstart, zstop, 1501)
B1 = rad.FldLst(dipole, 'b', [0, 0, zstart], [0, 0, zstop], len(Z), 'noarg')

plt.figure()
plt.title('Dipole field along Z')
plt.xlabel('Z Position (mm)')
plt.ylabel('Field (T)')
plt.plot(Z, [b[0] for b in B1], label='$B_x$')
plt.plot(Z, [b[1] for b in B1], label='$B_y$')
plt.plot(Z, [b[2] for b in B1], label='$B_z$')
plt.legend()
plt.show()

xstart = 0
xstop = 2 * magnet_size[0]
X = np.linspace(xstart, xstop, 1501)
B2 = rad.FldLst(dipole, 'b', [xstart, 0, 0], [xstop, 0, 0], len(X), 'noarg')

plt.figure()
plt.title('Dipole field along X')
plt.xlabel('X Position (mm)')
plt.ylabel('Field (T)')
plt.plot(X, [b[0] for b in B2], label='$B_x$')
plt.plot(X, [b[1] for b in B2], label='$B_y$')
plt.plot(X, [b[2] for b in B2], label='$B_z$')
plt.legend()
plt.show()


import numpy as np
import torch
from torch.utils.data import Dataset

class BCIC4_2A(Dataset):
    def __init__(self, args, phase):
        self.args = args
        self.load_data(phase)
        self.torch_form()
        self.reshape_data()

    def load_data(self, phase):
        if self.args.get_prediction:
            self.X = np.load(f"./data_loader/dataset/bcic4-2a/{phase}/S{self.args.subject:02}_X.npy")
        elif self.args.evaluation:
            self.y = np.load(f"./data_loader/dataset/bcic4-2a/{phase}/S{self.args.subject:02}_y.npy")
        else:
            self.X = np.load(f"./data_loader/dataset/bcic4-2a/{phase}/S{self.args.subject:02}_X.npy")
            self.y = np.load(f"./data_loader/dataset/bcic4-2a/{phase}/S{self.args.subject:02}_y.npy")

    def torch_form(self):
        if self.args.get_prediction:
            self.X = torch.Tensor(self.X)
        elif self.args.evaluation:
            self.y = torch.LongTensor(self.y)
        else:
            self.X = torch.Tensor(self.X)
            self.y = torch.LongTensor(self.y)

    def reshape_data(self):
        if not self.args.evaluation:
            self.X = self.X.unsqueeze(dim=1)

    def __len__(self):
        if not self.args.evaluation:
            return len(self.X)
        else:
            return len(self.y)

    def __getitem__(self, idx):
        if self.args.get_prediction:
            sample = self.X[idx]
            return sample
        elif self.args.evaluation:
            sample = self.y[idx]
            return sample
        else:
            sample = [self.X[idx], self.y[idx]]
            return sample


import datetime

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
from xml.sax.saxutils import escape
from django.http import JsonResponse

import cv2
import glob

from lr.models import *

def loadPhotosExt(photoLoc, ext):
    photos = []
    for img in glob.glob(photoLoc + "*." + ext):
        imgRead = cv2.imread(img)
        if imgRead is not None:
            photos.append(img)
    return photos

def getPhotos(photoLocation):
    images = []
    images.extend(loadPhotosExt(photoLocation, 'jpg'))
    images.extend(loadPhotosExt(photoLocation, 'png'))
    images.extend(loadPhotosExt(photoLocation, 'jpeg'))
    return images

def renderIndex(request, admin):
    landfill = Landfill.objects.all() # Landfill.objects.all().order_by('name')
    for lf in landfill:
        lf.photolocation = getPhotos(lf.photolocation)
        lf.datefind = str(lf.datefind)
        lf.datestatement = str(lf.datestatement)

    context = {
        'landfill': landfill,
        'admin': admin
    }
    return render(request, 'index.twig', context)

@require_http_methods(["GET"])
def index(request):
    return renderIndex(request, False)

@require_http_methods(["GET"])
def admin(request):
    return renderIndex(request, True)

def landfillOpen(request, id):
    try:
        landfill = Landfill.objects.get(id=id)
        landfill.datefind = str(landfill.datefind)
        landfill.datestatement = str(landfill.datestatement)
        info = landfill
    except Exception:
        return HttpResponse('Свалка с id = ' + str(id) + ' не найдена, сообщите администратору')

    info.photolocation = getPhotos(info.photolocation)
    vols = Volunteers.objects.filter(idlandfillvolunt=id)
    events = Events.objects.filter(idlandfillevent=id)

    context = {
        'info': info
    }
    return render(request, 'openDump.twig', context)

def form(request, id):
    context = {
        'edit': id != False
    }
    if id != False:
        try:
            landfill = Landfill.objects.get(id=id)
            landfill.datefind = str(landfill.datefind)
            landfill.datestatement = str(landfill.datestatement)
            context['info'] = landfill
            print(landfill.datefind)
        except Exception:
            return HttpResponse('Свалка с id = ' + str(id) + ' не найдена, сообщите администратору')
    return render(request, 'form.twig', context)

@require_http_methods(["GET"])
def formAdd(request):
    return form(request, False)

@require_http_methods(["GET"])
def formEdit(request, id):
    return form(request, id)

def htmlSpecialChars(unsafe):
    return escape(unsafe, {'"': '"', '\'': '''})

def landfillPost(request, id):
    if id != False:
        landfill = Landfill.objects.get(id=id)
    else:
        landfill = Landfill()
    formatStr = '%Y-%m-%d'

    landfill.name = htmlSpecialChars(request.POST['nameDump'].strip())
    if len(landfill.name) == 0:
        return JsonResponse({'result': 'Error', 'message': 'Название свалки не может оставаться пустым'})

    landfill.location = htmlSpecialChars(request.POST['location'])
    if len(landfill.location) == 0:
        return JsonResponse({'result': 'Error', 'message': 'Местоположение свалки не может оставаться пустым'})

    landfill.datefind = datetime.datetime.strptime(htmlSpecialChars(request.POST['datefind']), formatStr)
    # if len(landfill.dateFind) == 0:
    #     return JsonResponse({'result': 'Error', 'message': 'Дата нахождения свалки не может оставаться пустым'})

    landfill.datestatement = datetime.datetime.strptime(htmlSpecialChars(request.POST['datestatement']), formatStr)
    # if len(landfill.dateStatement) == 0:
    #     return JsonResponse(
    #         {'result': 'Error', 'message': 'Дата подачи заявления на свалку не может оставаться пустым'})

    landfill.photolocation = htmlSpecialChars(request.POST['photolocation'])
    if len(landfill.photolocation) == 0:
        return JsonResponse(
            {'result': 'Error', 'message': 'Ссылка с фотографиями на свалку не может оставаться пустым'})

    landfill.save()
    #return JsonResponse({'result': 'OK'})
    return renderIndex(request, True)

@require_http_methods(["GET", "POST", "DELETE"])
def landfill(request, id):
    if request.method == "GET":
        return landfillOpen(request, id)
    elif request.method == "POST":
        return landfillPost(request, id)
    elif request.method == "DELETE":
        landfill.objects.filter(id=id).delete()
        return HttpResponse('')

@require_http_methods(["POST", "DELETE"])
def landfillDel(request, id):
    Landfill.objects.filter(id=id).delete()
    return renderIndex(request, True)

@require_http_methods(["POST"])
def landfillAdd(request):
    return landfillPost(request, False)


from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
	ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock

class Paddle(Widget):
	score=NumericProperty(0)
	def BounceBall(self,ball):
		if self.collide_widget(ball):
			vx,vy =ball.velocity
			offset=(ball.center_y -self.center_y) /(self.height/2)
			bounced=Vector(-1 *vx, vy)
			vel =bounced *1.1
			ball.velocity=vel.x ,vel.y  + offset
#adding a ball with  ;
class Ball(Widget):
	#velocity of the ball in the x and y direction
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    # referencelist property so we can use ball.velocity as
    # a shorthand, just like e.g. w.pos for w.x and w.y
    velocity = ReferenceListProperty(velocity_x, velocity_y)
    #the move func will move the ball one by step in equal interval of time
    def move(self):
    	self.pos = Vector(*self.velocity) + self.pos

class PongGame(Widget):
	ball = ObjectProperty(None)
	player1 = ObjectProperty(None)
	player2 = ObjectProperty(None)
	def ServeBall(self,vel=(7,0)):
		self.ball.center=self.center
		self.ball.velocity=vel
	def update(self,dt):
		self.ball.move()
		#bounce of paddles:
		self.player1.BounceBall(self.ball)
		self.player2.BounceBall(self.ball)
		#bounce off the top and bottom:
		if (self.ball.y<0) or (self.ball.top>self.height):
			self.ball.velocity_y *= -1
		# updating the score:
		if self.ball.x <self.x:
			self.player2.score +=1
			self.ServeBall(vel=(4,0))
		if self.ball.x > self.width:
			self.player1.score+=1
			self.ServeBall(vel=(-4,0))

	#player control on paddle:
	def on_touch_move(self,touch):
		if touch.x< self.width  / 3:
			self.player1.center_y=touch.y
		if touch.x >self.width -self.width/3:
			self.player2.center_y=touch.y
#initialising the APP :
class PongApp(App):

    def build(self):
        game=PongGame()
        game.ServeBall()
        Clock.schedule_interval(game.update,1.0/60.0)
        return game

if __name__ == '__main__':
    PongApp().run()


from bs4 import BeautifulSoup
import requests

url= "https://quotecatalog.com/communicator/miyamoto-musashi" # you can change the name of the person you search for their quotes but remember to put - between their first and last name.

def down_quote():
	with open("quotes.txt","a+") as file:
		file.write(quote+"\n")

result = requests.get(url)
page = BeautifulSoup(result.text, "html.parser")

quotes = page.find_all(class_="block p-5 font-serif md:text-lg quoteCard__blockquote")
for quote in quotes:
		quote= quote.text.strip()
		quote = quote.replace(quote[0],'"')
		quote = quote.replace(quote[len(quote)-1], '"')
		down_quote()
		print("Done!")


import sqlite3

def initDb():
    # 创建SQLite数据库连接
    conn = sqlite3.connect('orders.db')
    cursor = conn.cursor()
    # 创建订单表
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS orders (
            id INTEGER PRIMARY KEY,
            order_time DATETIME DEFAULT CURRENT_TIMESTAMP,
            order_status INTEGER DEFAULT 0,
            account TEXT,
            contact TEXT,
            password TEXT,
            note TEXT,
            order_amount REAL DEFAULT 0
        )
    ''')

    # 提交表结构更改
    conn.commit()

def getDb():
    conn = sqlite3.connect('orders.db')
    cursor = conn.cursor()
    return conn , cursor

def run():
    initDb()

if __name__ == '__main__':
    run()


# ! ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
# ! ┃                                 IMPORTS                                  ┃
# ! ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

import os
import csv
import subprocess
import pandas as pd

from dotenv import load_dotenv
from datetime import datetime, time, timedelta
from dateutil.relativedelta import relativedelta

# ! ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
# ! ┃                              GLOBAL VAR`s                                ┃
# ! ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

# * Carrega as variáveis de ambiente do arquivo .env
load_dotenv()

NOME_DIRETORIO_RAIZ = str(os.getenv('NOME_DIRETORIO_RAIZ'))
FIRST_WORKING_DAY_OF_THE_MONTH = int(os.getenv('FIRST_WORKING_DAY_OF_THE_MONTH'))
LAST_WORKING_DAY_OF_THE_MONTH = int(os.getenv('LAST_WORKING_DAY_OF_THE_MONTH'))
VALUE_PER_HOUR = float(os.getenv('VALUE_PER_HOUR'))

# Diretório do executavel
dir_path = os.path.dirname(os.path.realpath(__file__))

# obter a data atual
data_atual = datetime.today()
dia = data_atual.strftime("%d")
# dia = data_atual.day+1
ano = data_atual.year
# mes = data_atual.strftime('%B')
mes = data_atual.month
GLOBAL_HORA_ATUAL = datetime.now().strftime('%H:%M:%S')

# nome do diretório correspondente ao ano atual
nome_diretorio = f'{NOME_DIRETORIO_RAIZ}/{ano}'

# nome do arquivo csv correspondente a este mês
nome_arquivo = f'{nome_diretorio}/{mes}.csv'

# diretorios
diretorio_anos = f'{dir_path}/{NOME_DIRETORIO_RAIZ}'
diretorio_atual = f'{dir_path}/{nome_diretorio}'
diretorio_file = f'{dir_path}/{nome_diretorio}/{mes}.csv'

executar_novamente = ''

meses_extenso = {
    1: "janeiro",
    2: "fevereiro",
    3: "março",
    4: "abril",
    5: "maio",
    6: "junho",
    7: "julho",
    8: "agosto",
    9: "setembro",
    10: "outubro",
    11: "novembro",
    12: "dezembro"
}

with open(nome_arquivo, 'r') as f:
    reader = csv.reader(f)
    linhas = list(reader)

# ! ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
# ! ┃                            GENERAL FUNCTIONS                             ┃
# ! ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

def send_notification(title, message):
    subprocess.run(["notify-send", title, message])

def open_directory_in_file_manager(path):
    if os.name == 'posix': # Verifica se o sistema operacional é Unix-based (Linux, macOS, etc.)
        os.system(f'xdg-open {path}')
    elif os.name == 'nt': # Verifica se o sistema operacional é Windows
        os.system(f'explorer {path}')

def calcular_total_horas(data_atual):
    print(f'╭─┴{str("".center(47, "─"))}╮')
    arquivo_não_encontrado = False
    total_horas = timedelta()

    if data_atual.day > FIRST_WORKING_DAY_OF_THE_MONTH:
        data_atual = data_atual + relativedelta(months=1)

    ano_atual = data_atual.year
    mes_atual = data_atual.month

    # Definir o intervalo de datas a serem consideradas
    data_inicio_mes_anterior = data_atual.replace(day=LAST_WORKING_DAY_OF_THE_MONTH)

    if data_inicio_mes_anterior.day > FIRST_WORKING_DAY_OF_THE_MONTH:
        if mes_atual == 1:  # Se for janeiro, volta para dezembro do ano anterior
            mes_anterior = 12
            ano_anterior = ano_atual - 1
        else:
            mes_anterior = mes_atual - 1
            ano_anterior = ano_atual
        data_inicio_mes_anterior = data_inicio_mes_anterior.replace(year=ano_anterior, month=mes_anterior)

    data_inicio_mes_atual = data_atual.replace(day=1)

    # Loop para percorrer os arquivos CSV
    for data_inicio in [data_inicio_mes_anterior, data_inicio_mes_atual]:
        nome_arquivo = f'{NOME_DIRETORIO_RAIZ}/{data_inicio.year}/{data_inicio.month}.csv'

        try:
            with open(nome_arquivo, 'r') as arquivo:
                reader = csv.reader(arquivo)
                next(reader)  # Ignorar a linha de cabeçalho

                for linha in reader:
                    dia = int(linha[0])
                    if data_inicio == data_inicio_mes_anterior and dia < LAST_WORKING_DAY_OF_THE_MONTH:  # Ignorar dias menores que {LAST_WORKING_DAY_OF_THE_MONTH} do mês anterior
                        continue
                    if data_inicio == data_inicio_mes_atual and dia > FIRST_WORKING_DAY_OF_THE_MONTH:  # Ignorar dias maiores que {FIRST_WORKING_DAY_OF_THE_MONTH} do mês atual
                        continue

                    total_dia = datetime.strptime(linha[-1], '%H:%M:%S')
                    total_horas += timedelta(hours=total_dia.hour, minutes=total_dia.minute, seconds=total_dia.second)

        except FileNotFoundError:
            arquivo_não_encontrado = True
            print(f'│{str(f"✘ Arquivo {nome_arquivo} não encontrado.".center(49))}│')

    # Exemplo de uso
    total = total_horas
    total_em_horas = total.total_seconds() / 3600
    total_em_horas = round(total_em_horas, 2)
    total_a_receber = total_em_horas * VALUE_PER_HOUR

    if(total_em_horas == 0):
        print(f'╰─┬{str("".center(47, "─"))}╯')
        return

    if(arquivo_não_encontrado):
        print(f'│{str("".center(49))}│')

    # Exibir a quantidade total de horas como número decimal
    print(f'│{str("".center(32))}╭─────────────╮  │')
    print(f'│{str(f" Total de horas  ╾".ljust(32, "─"))}┾ {str(f"{total_em_horas:.2f} Hrs").ljust(11)} │  │')
    print(f'│{str("".center(32))}├─────────────┤  │')
    if(total_em_horas < 160):
        total_horas_faltante = 160 - total_em_horas
        print(f'│{str(f" Carga horaria restante ╾".ljust(32, "─"))}┾ {str(f"{total_horas_faltante:.2f} Hrs").ljust(11)} │  │')
        print(f'│{str("".center(32))}├─────────────┤  │')

    print(f'│{str(f" Total aproximado a receber ╾".ljust(32, "─"))}┾ {str(f"R$: {total_a_receber:.2f}").ljust(11)} │  │')
    print(f'│{str("".center(32))}╰─────────────╯  │')

    # Exibir a quantidade total de horas no formato dias, horas e minutos
    dias = total.days
    horas, resto = divmod(total.seconds, 3600)
    minutos = resto // 60

    print(f'│{str("".center(49))}│')
    print(f'│{str(f" Total de horas (formato dias, horas e minutos)".center(49))}│')
    print(f'│{str(f" {dias} dia(s), {horas} hora(s) e {minutos} minuto(s)".center(49))}│')
    print(f'╰─┬{str("".center(47, "─"))}╯')
    send_notification(f"Total de horas: {total_em_horas:.2f} Hrs", f"No mês de {meses_extenso[mes_atual]}, {ano_atual}")

# ! ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
# ! ┃                              MENU FUNCTIONS                              ┃
# ! ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛

def option_1():
    print(f'╭─┴{str("".center(47, "─"))}╮')
    print(f'│{str(f"Abrindo: {dir_path}").center(49)}│')
    print(f'╰─┬{str("".center(47, "─"))}╯')

    subprocess.run(["code", dir_path])
    send_notification("Abrindo VS Code", dir_path)

def option_2():
    dataframe = pd.read_csv(diretorio_file)

    print(f'╭─┴{str("".center(71, "─"))}╮')
    print(dataframe.to_string(index=False, header=True, na_rep='  :  :  ', justify='center'))
    print(f'╰─┬{str("".center(71, "─"))}╯')

def option_3():
    print(f'╭─┴{str("".center(47, "─"))}╮')
    print(f'│{str(f"Abrindo: {diretorio_atual}").center(49)}│')
    print(f'╰─┬{str("".center(47, "─"))}╯')

    open_directory_in_file_manager(diretorio_atual)

def option_4():
    GLOBAL_HORA_ATUAL = datetime.now().strftime('%H:%M:%S')
    print(f'  │')
    for i, row in enumerate(linhas):
        if row[0] == str(dia):
            if row[1] == '' and row[2] == '':
                print(f'╭─┴{str("".center(47, "─"))}╮')
                print(f'│{str(f"Ainda abriu o PRIMEIRO ponto").center(49)}│')
                print(f'╰─┬{str("".center(47, "─"))}╯')
                return
            elif row[1] != '' and row[2] == '':
                print(f'╭─┴{str("".center(47, "─"))}╮')
                print(f'│{str(f"Ainda NÃO fechou o PRIMEIRO ponto").center(49)}│')
                print(f'╰─┬{str("".center(47, "─"))}╯')
                inicio_str = row[1]
                total_str = '00:00:01'
            elif row[2] != '' and row[3] == '':
                inicio_str = GLOBAL_HORA_ATUAL
                total_str = row[-1]
                print(f'╭─┴{str("".center(47, "─"))}╮')
                print(f'│{str(f"Ainda NÃO iniciou o SEGUNDO ponto").center(49)}│')
                print(f'│{str(f"Mas se iniciar outro agora ás {GLOBAL_HORA_ATUAL}").center(49)}│')
                print(f'╰─┬{str("".center(47, "─"))}╯')
            elif row[3] != '' and row[4] == '':
                inicio_str = row[3]
                total_str = row[-1]
            elif row[4] != '' and row[5] == '':
                print(f'╭─┴{str("".center(47, "─"))}╮')
                print(f'│{str(f"Ainda NÃO iniciou o TERCEIRO ponto").center(49)}│')
                print(f'│{str(f"Mas se iniciar outro agora ás {GLOBAL_HORA_ATUAL}").center(49)}│')
                print(f'╰─┬{str("".center(47, "─"))}╯')
                inicio_str = GLOBAL_HORA_ATUAL
                total_str = row[-1]
            elif row[5] != '' and row[6] == '':
                inicio_str = row[5]
                total_str = row[-1]
            else:
                print(f'╭─┴{str("".center(47, "─"))}╮')
                print(f'│{str(f"Ja bateu os três pontos").center(49)}│')
                print(f'│{str(f"E trabalhou um total de {row[-1]} hoje").center(49)}│')
                print(f'╰─┬{str("".center(47, "─"))}╯')
                return
            break

    # Hora total no formato "HH:MM:SS"
    tempo_total_com_ponto = datetime.strptime(total_str, '%H:%M:%S').time()

    # Hora total no formato "HH:MM:SS"
    hora_atual = datetime.strptime(GLOBAL_HORA_ATUAL, '%H:%M:%S').time()

    # Hora de início no formato "HH:MM:SS"
    tempo_ultimo_ponto_entrada = datetime.strptime(inicio_str, '%H:%M:%S')

    # Duração de 8 horas em um objeto timedelta
    carga_dia_trabalho = timedelta(hours=8)

    # Subtrai o tempo total da duração de 8 horas
    tempo_restante_com_ponto = carga_dia_trabalho - timedelta(hours=tempo_total_com_ponto.hour, minutes=tempo_total_com_ponto.minute, seconds=tempo_total_com_ponto.second)

    # Soma o tempo restante com o intervalo entre a hora de início e a hora atual
    tempo_trabalhado_sem_ponto = timedelta(hours=tempo_total_com_ponto.hour, minutes=tempo_total_com_ponto.minute, seconds=tempo_total_com_ponto.second) + timedelta(hours=hora_atual.hour, minutes=hora_atual.minute, seconds=hora_atual.second) - timedelta(hours=tempo_ultimo_ponto_entrada.hour, minutes=tempo_ultimo_ponto_entrada.minute, seconds=tempo_ultimo_ponto_entrada.second)
    tempo_restante_sem_ponto = carga_dia_trabalho - tempo_trabalhado_sem_ponto

    print(f'  │')
    print(f'╭─┴{str("".center(47, "─"))}╮')

    if tempo_restante_sem_ponto < timedelta(0):
        print(f'│ ╭───╮{str("".center(43))}│')
        print(f'├─┤ ✘ ├╼ Trabalhado SEM ponto : {str(tempo_trabalhado_sem_ponto).center(8)}  hrs     │')
        print(f'│ ╰───╯{str("".center(43))}│')
    else:
        print(f'│ ╭───╮{str("".center(43))}│')
        print(f'├─┤ ✘ ├╼ Trabalhado SEM ponto : {str(tempo_trabalhado_sem_ponto).center(8)}  hrs     │')
        print(f'├─┤ ✘ ├╼ Restante   SEM ponto : {str(tempo_restante_sem_ponto).center(8)}  hrs     │')
        print(f'│ ╰───╯{str("".center(43))}│')

    if tempo_restante_com_ponto < timedelta(0):
        print(f'│ ╭───╮{str("".center(43))}│')
        print(f'├─┤ ✔ ├╼ Trabalhado COM ponto : {str(tempo_total_com_ponto).center(8)}  hrs     │')
        print(f'│ ╰───╯{str("".center(43))}│')
        print(f'╰─┬────{str("".center(43, "─"))}╯')
        send_notification(f"Hoje ja trabalho um total de", f"{tempo_total_com_ponto} hrs")
    else:
        fim = tempo_ultimo_ponto_entrada + tempo_restante_com_ponto
        print(f'│ ╭───╮{str("".center(43))}│')
        print(f'├─┤ ✔ ├╼ Trabalhado COM ponto : {str(tempo_total_com_ponto).center(8)}  hrs     │')
        print(f'├─┤ ✔ ├╼ Restante   COM ponto : {str(tempo_restante_com_ponto).center(8)}  hrs     │')
        print(f'│ ╰─┬─╯{str("".center(43))}│')
        print(f'│   ╰──────────────────────────────────────╮      │')
        print(f'│                                    ╭─────┴────╮ │')
        print(f'│     Deve fechar o ponto as ╾───────┤ {str(fim.time().strftime("%H:%M:%S")).center(8)} │ │')
        print(f'│  Finalizar o dia com {str(carga_dia_trabalho).center(8)} Hrs  ╰─────┬────╯ │')
        print(f'╰─┬────────────────────────────────────────┴──────╯')
        send_notification(f"Para finalizar o dia falta {tempo_restante_com_ponto} hrs", f"Deve fechar o ponto as {fim.time()} hrs")

def option_5():
    calcular_total_horas(data_atual)

def option_6():
    # Obter a data especifica
    while True:
        print(f'  │')
        data_atual_string = input("  ├──╼ Data (MM/AAAA): ")
        try:
            data_especifica = datetime.strptime("01/" + data_atual_string, "%d/%m/%Y").date()
            break
        except ValueError:
            print("  ├──╼ Formato de data inválido. Certifique-se de usar o formato MM/AAAA.")
    calcular_total_horas(data_especifica)

def option_day(day):
    print(f'╭─┴{str("".center(47, "─"))}╮')
    print(f'│{str(f"Pasta: {nome_arquivo}").center(49)}│')
    for i, row in enumerate(linhas):
        if row[0] == str(day):
            hora, minuto, segundo = row[-1].split(":")
            print(f'│{str(f"No dia {day}, teve um total de {hora} horas e {minuto} minutos").center(49)}│')
            print(f'╰─┬{str("".center(47, "─"))}╯')
            break
    else:
        print(f'│{str(f"Dia {day} não encontrado").center(49)}│')
        print(f'╰─┬{str("".center(47, "─"))}╯')

def option_year(year):
    diretorio_espc_ano = f'{diretorio_anos}/{option}'

    print(f'╭─┴{str("".center(47, "─"))}╮')
    print(f'│{str(f"Abrindo: {diretorio_espc_ano}").center(49)}│')
    if os.path.isdir(diretorio_espc_ano):
        open_directory_in_file_manager(diretorio_espc_ano)
        print(f'╰──{str("".center(47, "─"))}╯')

    print(f'│{str(f"Pasta não existe: {diretorio_espc_ano}").center(49)}│')
    print(f'╰─┬{str("".center(47, "─"))}╯')

options_functions = {
    '1': option_1,
    '2': option_2,
    '3': option_3,
    '4': option_4,
    '5': option_5,
    '6': option_6
}

while True:
    print(f'┏━━━┓')
    print(f'┃ 1 ╉╼ Abrir projeto no VS Code')
    print(f'┃ 2 ╉╼ Para print o {nome_arquivo}')
    print(f'┃ 3 ╉╼ Para pasta do ANO ATUAL')
    print(f'┃ 4 ╉╼ Para calcular qual horario de saida para um total de 8h')
    print(f'┃ 5 ╉╼ Somar as horas do mês de trabalho')
    print(f'┃ 6 ╉╼ Somar as horas do mês atual')
    print(f'┗━┯━┛')
    print(f'┏━┷━━━━┓')
    print(f'┃  01  ╉╼ Para print do DIA especifico no MÊS atual')
    print(f'┃ 2020 ╉╼ Para pasta do ANO ESPECIFICO')
    print(f'┗━┯━━━━┛')
    print(f'┏━┷━┓')
    print(f'┃ 0 ╉╼ Para terminar')
    print(f'┗━┯━┛')

    if executar_novamente != '0':
        option = executar_novamente

    if option in options_functions:
        options_functions[option]()
    elif option.isdigit() and len(option) == 2:
        option_day(option)
    elif option.isdigit() and len(option) == 4:
        option_year(option)
    else:
        pass

    # Pergunta se o usuário quer executar o código novamente
    executar_novamente = input("  ╰──╼ Opção: ").lower()

    # Se a resposta for 'n' ou 'não', encerra o loop e o programa
    if executar_novamente in ['n', 'não', 'nao', '0']:
        break
    else:
        os.system('clear')


# -*- coding: utf-8 -*-

import re
import time
from datetime import timedelta

from ..base.multi_account import MultiAccount

class MegaRapidoNet(MultiAccount):
    __name__ = "MegaRapidoNet"
    __type__ = "account"
    __version__ = "0.10"
    __status__ = "testing"

    __config__ = [
        ("mh_mode", "all;listed;unlisted", "Filter downloaders to use", "all"),
        ("mh_list", "str", "Downloader list (comma separated)", ""),
        ("mh_interval", "int", "Reload interval in hours", 12),
    ]

    __description__ = """MegaRapido.net account plugin"""
    __license__ = "GPLv3"
    __authors__ = [("Kagenoshin", "kagenoshin@gmx.ch")]

    VALID_UNTIL_PATTERN = r'<\s*?div[^>]*?class\s*?=\s*?[\'"]premium_index[\'"].*?>[^<]*?<[^>]*?b.*?>\s*?TEMPO\s*?PREMIUM.*?<[^>]*?/b.*?>\s*?(\d*)[^\d]*?DIAS[^\d]*?(\d*)[^\d]*?HORAS[^\d]*?(\d*)[^\d]*?MINUTOS[^\d]*?(\d*)[^\d]*?SEGUNDOS'
    USER_ID_PATTERN = r'<\s*?div[^>]*?class\s*?=\s*?["\']checkbox_compartilhar["\'].*?>.*?<\s*?input[^>]*?name\s*?=\s*?["\']usar["\'].*?>.*?<\s*?input[^>]*?name\s*?=\s*?["\']user["\'][^>]*?value\s*?=\s*?["\'](.*?)\s*?["\']'

    def grab_hosters(self, user, password, data):
        hosters = {
            "1fichier": [],  #: leave it there are so many possible addresses?
            "1st-files": ["1st-files.com"],
            "2shared": ["2shared.com"],
            "4shared": ["4shared.com", "4shared-china.com"],
            "asfile": ["http://asfile.com/"],
            "bitshare": ["bitshare.com"],
            "brupload": ["brupload.net"],
            "crocko": ["crocko.com", "easy-share.com"],
            "dailymotion": ["dailymotion.com"],
            "depfile": ["depfile.com"],
            "depositfiles": ["depositfiles.com", "dfiles.eu"],
            "dizzcloud": ["dizzcloud.com"],
            "dl.dropbox": [],
            "extabit": ["extabit.com"],
            "extmatrix": ["extmatrix.com"],
            "facebook": [],
            "file4go": ["file4go.com"],
            "filecloud": ["filecloud.io", "ifile.it", "mihd.net"],
            "filefactory": ["filefactory.com"],
            "fileom": ["fileom.com"],
            "fileparadox": ["fileparadox.in"],
            "filepost": ["filepost.com", "fp.io"],
            "filerio": ["filerio.in", "filerio.com", "filekeen.com"],
            "filesflash": ["filesflash.com"],
            "firedrive": ["firedrive.com", "putlocker.com"],
            "flashx": [],
            "freakshare": ["freakshare.net", "freakshare.com"],
            "gigasize": ["gigasize.com"],
            "hipfile": ["hipfile.com"],
            "junocloud": ["junocloud.me"],
            "letitbit": ["letitbit.net", "shareflare.net"],
            "mediafire": ["mediafire.com"],
            "mega": ["mega.co.nz"],
            "megashares": ["megashares.com"],
            "metacafe": ["metacafe.com"],
            "netload": ["netload.in"],
            "oboom": ["oboom.com"],
            "rapidgator": ["rapidgator.net"],
            "rapidshare": ["rapidshare.com"],
            "rarefile": ["rarefile.net"],
            "ryushare": ["ryushare.com"],
            "sendspace": ["sendspace.com"],
            "turbobit": ["turbobit.net", "unextfiles.com"],
            "uploadable": ["uploadable.ch"],
            "uploadbaz": ["uploadbaz.com"],
            "uploaded": ["uploaded.to", "uploaded.net", "ul.to"],
            "uploadhero": ["uploadhero.com"],
            "uploading": ["uploading.com"],
            "uptobox": ["uptobox.com"],
            "xvideos": ["xvideos.com"],
            "youtube": ["youtube.com"],
        }

        hoster_list = []

        for item in hosters.values():
            hoster_list.extend(item)

        return hoster_list

    def grab_info(self, user, password, data):
        validuntil = None
        trafficleft = None
        premium = False

        html = self.load("http://megarapido.net/gerador")

        validuntil = re.search(self.VALID_UNTIL_PATTERN, html)
        if validuntil:
            #: Hier weitermachen!!! (müssen umbedingt die zeit richtig machen damit! (sollte aber möglich))
            validuntil = (
                time.time()
                + timedelta(hours=int(validuntil.group(1)) * 24).total_seconds()
                + timedelta(hours=int(validuntil.group(2))).total_seconds()
                + timedelta(minutes=int(validuntil.group(3))).total_seconds()
                + int(validuntil.group(4))
            )
            trafficleft = -1
            premium = True

        return {
            "validuntil": validuntil,
            "trafficleft": trafficleft,
            "premium": premium,
        }

    def signin(self, user, password, data):
        self.load("http://megarapido.net/login")
        self.load(
            "http://megarapido.net/painel_user/ajax/logar.php",
            post={"login": user, "senha": password},
        )

        html = self.load("http://megarapido.net/gerador")

        if "sair" not in html.lower():
            self.fail_login()
        else:
            m = re.search(self.USER_ID_PATTERN, html)
            if m is not None:
                data["uid"] = m.group(1)
            else:
                self.fail_login("Couldn't find the user ID")


from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from ..serializers import MeterstandSerializer
from ..models import Meterstand
from ..permissions import IsOwner

class MeterstandViewSet(viewsets.ModelViewSet):
    """
    Meter readings can be used for energy and gas consumption
    """
    queryset = Meterstand.objects.all()
    serializer_class = MeterstandSerializer
    permission_classes = [IsOwner]
    filterset_fields = ['datetime']

    def get_queryset(self):
        """
        This view should return a list of all the purchases
        for the currently authenticated user.
        """
        if getattr(self, 'swagger_fake_view', False):
            return None
        user = self.request.user
        return Meterstand.objects.filter(user=user)

    def create(self, request, *args, **kwargs):
        many = True if isinstance(request.data, list) else False
        serializer = MeterstandSerializer(data=request.data, many=many)
        if serializer.is_valid():
            if many:
                for meterstand in request.data:
                    Meterstand.objects.update_or_create(user=request.user, datetime=meterstand['datetime'], defaults=meterstand)
            else:
                #request.data.pop('csrfmiddlewaretoken', None)
                data = {x: request.data[x] for x in request.data if x not in ['csrfmiddlewaretoken']}
                Meterstand.objects.update_or_create(user=request.user, datetime=request.data['datetime'], defaults=data)
            #serializer.save()
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    @action(detail=False, methods=['get'], url_path='day/(?P<day>\d{4}-\d{2}-\d{2})/$')#'day/(?P<day>\w+)')
    def day(self, request, day, *args, **kwargs):
        datearray = day.split('-')
        meterstanden = Meterstand.objects.filter(user=self.request.user, datetime__year=datearray[0], datetime__month=datearray[1], datetime__day=datearray[2])
        meterstanden_data = self.get_serializer_class()(meterstanden, many=True)
        return Response(meterstanden_data.data)

    @action(detail=False, methods=['get'], url_path='month/(?P<month>\d{4}-\d{2})/$')
    def month(self, request, month, *args, **kwargs):
        datearray = month.split('-')
        meterstanden = Meterstand.objects.filter(user=self.request.user, datetime__year=datearray[0], datetime__month=datearray[1], datetime__hour=0, datetime__minute=0)
        meterstanden_data = self.get_serializer_class()(meterstanden, many=True)
        return Response(meterstanden_data.data)


from parse_sdf import IOPath, SetupHoldCheck
from os import path
import database
import sys, json, os, glob, pickle

def unescape_sdf_name(name):
    e = ""
    if name[0] == '"':
        assert name[-1] == '"'
        name = name[1:-1]
    for c in name:
        if c == '\\':
            continue
        e += c
    return e

# DSP cell types
dsp_celltypes = {
    "MULT9_CORE",
    "PREADD9_CORE",
    "MULT18_CORE",
    "REG18_CORE",
    "MULT18X36_CORE",
    "MULT36_CORE",
    "ACC54_CORE",
}

ebr_celltypes = {
    "SP16K_MODE",
    "DP16K_MODE",
    "PDP16K_MODE",
    "PDPSC16K_MODE",
    "FIFO16K_MODE",
}

# We strip off these prefices, as all delays to 'subports' are the same
dsp_prefixes = [
    "M9ADDSUB", "ADDSUB",
    "SFTCTRL", "DSPIN", "CINPUT", "DSPOUT", "CASCOUT", "CASCIN",
    "PML72", "PMH72", "SUM1", "SUM0",
    "BRS1", "BRS2", "BLS1", "BLS2", "BLSO", "BRSO", "PL18", "PH18", "PL36", "PH36", "PL72", "PH72",
    "P72", "P36", "P18", "AS1", "AS2", "ARL", "ARH", "BRL", "BRH",
    "AO", "BO", "AB", "AR", "BR", "PM", "PP",
    "A", "B", "C",
]
ebr_prefixes = [
    "DIA",
    "DIB",
    "DOA",
    "DOB",
    "CSA",
    "CSB",
    "ADA",
    "ADB",
]
lram_prefixes = [
    "DIA",
    "DIB",
    "DOA",
    "DOB",
    "CSA",
    "CSB",
    "ADA",
    "ADB",
    "BENA_N",
    "BENB_N",
    "ERRDECA",
    "ERRDECB",
]

# Which IOLOGIC signals are relevant for which purposes...
iol_input_sigs = ["SCLKIN", "CEIN", "LSRIN", "INFF", "DI", "WORDALIGN"] + ["RXDATA{}".format(i) for i in range(10)]
iol_output_sigs = ["SCLKOUT", "CEOUT", "LSROUT", "DOUT", "TOUT"] + ["TXDATA{}".format(i) for i in range(10)] + ["TSDATA{}".format(i) for i in range(4)]
iol_dly_sigs = ["INDD", "DIR", "LOAD_N", "MOVE", "CFLAG"]

subtracts = {}

def rewrite_path(modules, modtype, from_pin, to_pin):
    # Rewrite a (celltype, from_pin, to_pin) tuple given cell data, or returns None to drop the path
    # This looks at the JSON output by Yosys from the Lattice structural Verilog netlist in order
    # to determine what the cells in the SDF file are actually doing
    mod = modules["modules"][modtype]
    mod_cells = mod["cells"]

    def get_netid(name):
        if name not in mod["netnames"]:
            return -1
        return mod["netnames"][name]["bits"][0]

    for cellname, cell in mod_cells.items():
        # Go through each sub-cell inside the SDF-level cell module
        celltype = cell["type"]
        if celltype.startswith("UALUT4"):
            # Simple LUT4s
            if from_pin in ("A0", "A1", "B0", "B1", "C0", "C1", "D0", "D1") and to_pin in ("F0", "F1"):
                return ("OXIDE_COMB:LUT4", from_pin[0], to_pin[0])
        elif celltype.startswith("UACCU2"):
            # Carries
            if from_pin in ("A0", "A1", "B0", "B1", "C0", "C1", "D0", "D1", "FCI") and to_pin in ("F0", "F1", "FCO"):
                # TODO: split in half?
                return ("OXIDE_COMB:CCU2", from_pin, to_pin)
        elif celltype.startswith("UASLICEREG"):
            # Flipflops
            # We need to work if we are index 0 or 1 within the SLICE, use the connectivity of Q1 to determine this
            idx = 1 if cell["connections"]["Q"][0] == get_netid("Q1") else 0
            if from_pin in ("DI0", "DI1", "M0", "M1"):
                if int(from_pin[-1]) != idx:
                    continue
                from_pin = from_pin[:-1]
            elif from_pin not in ("LSR", "CE", "CLK"):
                continue
            if to_pin in ("Q0", "Q1"):
                if int(to_pin[-1]) != idx:
                    continue
                to_pin = to_pin[:-1]
            elif to_pin != "CLK":
                continue
            invstr = "N" if "CLK_INVERTERIN" in mod_cells else "P"
            invstr += "N" if "LSR_INVERTERIN" in mod_cells else "P"
            invstr += "N" if "CE_INVERTERIN" in mod_cells else "P"

            # Skip these, as they aren't actually different numerically so we can derive them later on and just clutter things up
            if invstr != "PPP":
                return None
            ffinst = modules["modules"][celltype]["cells"]["INST10"]
            synctype = "ASYNC" if ffinst["parameters"].get("ASYNC", "NO") == "YES" else "SYNC"
            return ("OXIDE_FF:{}:{}".format(invstr, synctype), from_pin, to_pin)
        elif celltype.startswith("UARAMW"):
            ramw_pins = (
                "A0", "A1", "B0", "B1", "C0", "C1", "D0", "D1", "CLK", "LSR",
                "WDO0", "WDO1", "WDO2", "WDO3", "WADO0", "WADO1", "WADO2", "WADO3", "WCKO", "WREO"
            )
            if from_pin in ramw_pins and to_pin in ramw_pins:
                return ("RAMW", from_pin, to_pin)
        elif celltype.startswith("UADPRAM"):
            if from_pin in ("A0", "A1", "B0", "B1", "C0", "C1", "D0", "D1", "WDI0", "WDI1"):
                return ("OXIDE_COMB:DPRAM", from_pin[:-1], to_pin[:-1])
        elif celltype.startswith("selmux2"):
            if to_pin == "OFX0":
                if from_pin in ("A0", "B0", "C0", "D0"):
                    return ("OXIDE_COMB:WIDEFN9", from_pin[:-1], to_pin[:-1])
                elif from_pin == "D1":
                    key = ("OXIDE_COMB:WIDEFN9", "F1", to_pin[:-1])
                    subtracts[key] = ("OXIDE_COMB:LUT4", "D", "F")
                    return key
                elif from_pin == "SEL":
                    return ("OXIDE_COMB:WIDEFN9", from_pin, to_pin[:-1])
        elif celltype.startswith("DCS"):
            if from_pin in ("CLK0", "CLK1", "SEL", "SELFORCE") and to_pin in ("DCSOUT", "CLK0", "CLK1"):
                return("DCS:DCS", from_pin, to_pin)
        elif "_INPUT" in modtype or "_OUTPUT" in modtype or "_INOUT" in modtype:
            # PIO config is encoded in name
            ct = modtype.split("__")
            new_type = "PIO:{}{}".format(
                ct[1], "".join(":{}".format(kv) for kv in ct[3:])
            )
            if "_INPUT" in from_pin or "_OUTPUT" in from_pin or "_INOUT" in from_pin:
                from_pin = "IOPAD"
            if "_INPUT" in to_pin or "_OUTPUT" in to_pin or "_INOUT" in to_pin:
                to_pin = "IOPAD"
            return (new_type, from_pin, to_pin)
        if "_S_IOB_" in modtype or "__IOB_" in modtype:

            def idelay_used():
                di_idx = get_netid("DI")
                for cellname2, cell2 in mod_cells.items():
                    if cell2["type"].startswith("DELAY") and cell2["connections"]["A"][0] == di_idx:
                        return True
                return False
            def odelay_used():
                dout_idx = get_netid("DOUT")
                for cellname2, cell2 in mod_cells.items():
                    if cell2["type"].startswith("DELAY") and cell2["connections"]["Z"][0] == dout_idx:
                        return True
                return False
            # For IOLOGIC, we encode in the buffer name (which becomes the IOL name)
            # whether this is a simple 'SIOLOGIC' or full 'IOLOGIC'
            s = "S" if "_S_IOB_" in modtype else ""
            if celltype.startswith("DELAY"):
                if from_pin in iol_dly_sigs or to_pin in iol_dly_sigs:
                    return ("{}IOLOGIC:DELAY".format(s), from_pin, to_pin)
            elif celltype.startswith("IOREG"):
                if from_pin in iol_input_sigs or to_pin in iol_input_sigs:
                    return ("{}IOLOGIC:IREG{}".format(s, ":DELAYED" if idelay_used() else ""), from_pin, to_pin)
                if from_pin in iol_output_sigs or to_pin in iol_output_sigs:
                    return ("{}IOLOGIC:OREG{}".format(s, ":DELAYED" if odelay_used() else ""), from_pin, to_pin)
            elif celltype.startswith("IDDR"):
                ddrtype = celltype[:6]
                if from_pin in iol_input_sigs or to_pin in iol_input_sigs:
                    if to_pin[-1].isdigit():
                        to_pin = to_pin[:-1]
                    return ("{}IOLOGIC:{}{}".format(s, ddrtype, ":DELAYED" if idelay_used() else ""), from_pin, to_pin)
            elif celltype.startswith("ODDR"):
                ddrtype = celltype[:6]
                if from_pin in iol_output_sigs or to_pin in iol_output_sigs:
                    if from_pin[-1].isdigit():
                        from_pin = from_pin[:-1]
                    return ("{}IOLOGIC:{}{}".format(s, ddrtype, ":DELAYED" if odelay_used() else ""), from_pin, to_pin)
        # Removing prefices as defined above; for buses that share delays
        def strip_prefix(x, p):
            for pr in p:
                if x.startswith(pr) and x[len(pr):].isdigit():
                    return pr
            return x
        def strip_prefix_ebr(x, p):
            for pr in p:
                if x.startswith(pr) and x[len(pr):].isdigit():
                    pin = pr
                    if pr in ("ADA", "ADB"):
                        i = int(x[len(pr):])
                        pin += "_13_5" if i > 4 else "_4_0"
                    return pin
            return x
        # Handle the special cases of DSP and EBR
        for dsp_type in dsp_celltypes:
            if not celltype.startswith(dsp_type):
                continue
            # Determine DSP cell programming
            dsp_postfix = set()
            for sub_cell in modules["modules"][celltype]["cells"].values():
                for k, v in sub_cell["parameters"].items():
                    if "REGBYPS" in k and v == "REGISTER":
                        dsp_postfix.add(k.replace("REGBYPS", "REG"))
                    if k == "BYPASS_PREADD9" and v == "BYPASS":
                        dsp_postfix.add("BYPASS")
            cell_type = dsp_type
            if len(dsp_postfix) > 0:
                cell_type += ":"
                cell_type += ",".join(sorted(dsp_postfix))
            return (cell_type, strip_prefix(from_pin, dsp_prefixes), strip_prefix(to_pin, dsp_prefixes))
        for ebr_type in ebr_celltypes:
            if not celltype.startswith(ebr_type):
                continue
            return (ebr_type, strip_prefix_ebr(from_pin, ebr_prefixes), strip_prefix_ebr(to_pin, ebr_prefixes))
        if celltype.startswith("LRAM_CORE"):
            return ("LRAM_CORE", strip_prefix(from_pin, lram_prefixes), strip_prefix(to_pin, lram_prefixes))
    return None

def main():
    folder = sys.argv[1]
    iopaths = {}
    setupholds = {}

    speedgrades = ["4", "5", "6", "10", "11", "12", "M"]
    for speed in speedgrades:
        iopaths[speed] = {}
        setupholds[speed] = {}

    # Import JSON netlists and SDF files
    for netlist in glob.glob(path.join(folder, "*.vo.json")):
        with open(netlist, "r") as jf:
            modules = json.load(jf)
        sdffile = netlist.replace(".vo.json", ".sdf.pickle")
        if not path.exists(sdffile):
            continue
        with open(sdffile, "rb") as sdff:
            sdf = pickle.load(sdff)

        speed = sdffile.replace(".sdf.pickle", "").split("_")[-1]
        assert speed in speedgrades
        for cell in sdf.cells.values():
            celltype = unescape_sdf_name(cell.type)
            for entry in cell.entries:
                if isinstance(entry, IOPath):
                    rewritten = rewrite_path(modules, celltype, entry.from_pin, entry.to_pin)
                    if rewritten is None:
                        continue
                    if rewritten in iopaths[speed]:
                        # If path appears multiple times; pick the worst case
                        iopaths[speed][rewritten] = (
                            min(iopaths[speed][rewritten][0], entry.rising.minv, entry.falling.minv),
                            max(iopaths[speed][rewritten][1], entry.rising.maxv, entry.falling.maxv),
                        )
                    else:
                        # Add to the list of paths
                        iopaths[speed][rewritten] = (
                            min(entry.rising.minv, entry.falling.minv),
                            max(entry.rising.maxv, entry.falling.maxv),
                        )
                elif isinstance(entry, SetupHoldCheck):
                    pin = entry.pin
                    if isinstance(entry.pin, list):
                        pin = pin[1]
                    rewritten = rewrite_path(modules, celltype, pin, entry.clock[1])
                    if rewritten is None:
                        continue
                    if rewritten in setupholds[speed]:
                        setupholds[speed][rewritten] = (
                            min(setupholds[speed][rewritten][0], entry.setup.minv),
                            max(setupholds[speed][rewritten][1], entry.setup.maxv),
                            min(setupholds[speed][rewritten][2], entry.hold.minv),
                            max(setupholds[speed][rewritten][3], entry.hold.maxv),
                        )
                    else:
                        setupholds[speed][rewritten] = (
                            entry.setup.minv, entry.setup.maxv,
                            entry.hold.minv, entry.hold.maxv,
                        )
    for speed in speedgrades:
        # Apply subtraction rules
        iopath_keys = sorted(iopaths[speed].keys())
        for key in iopath_keys:
            if key not in subtracts:
                continue
            sub_key = subtracts[key]
            sub_iopath = iopaths[speed][sub_key]
            # Compute all corner combinations
            cnr00 = iopaths[speed][key][0] - sub_iopath[0]
            cnr01 = iopaths[speed][key][0] - sub_iopath[1]
            cnr10 = iopaths[speed][key][1] - sub_iopath[0]
            cnr11 = iopaths[speed][key][1] - sub_iopath[1]
            iopaths[speed][key] = (
                min(cnr00, cnr01, cnr10, cnr11),
                max(cnr00, cnr01, cnr10, cnr11),
            )
        # Convert to the format that we save to JSON
        json_celltypes = {}
        for key, iopath in sorted(iopaths[speed].items()):
            if key[0] not in json_celltypes:
                json_celltypes[key[0]] = dict(iopaths=[], setupholds=[])
            json_celltypes[key[0]]["iopaths"].append(dict(from_pin=key[1], to_pin=key[2], minv=iopath[0], maxv=iopath[1]))
        for key, sh in sorted(setupholds[speed].items()):
            if key[0] not in json_celltypes:
                json_celltypes[key[0]] = dict(iopaths=[], setupholds=[])
            json_celltypes[key[0]]["setupholds"].append(dict(pin=key[1], clock=key[2],
                min_setup=sh[0], max_setup=sh[1],
                min_hold=sh[2], max_hold=sh[3])
            )
        timing_root = path.join(database.get_db_root(), "LIFCL", "timing")
        os.makedirs(timing_root, exist_ok=True)
        with open(path.join(timing_root, "cells_{}.json".format(speed)), 'w') as outf:
            json.dump(dict(celltypes=json_celltypes), outf, sort_keys=True, indent=4)
if __name__ == '__main__':
    main()