import discord,data
from logger import logOutput
from discord.ext.commands import Cog
from discord_slash import cog_ext,SlashContext
from discord_slash.utils.manage_commands import create_option

bot = data.load('bot')
users = data.load('users')
servers = data.load('servers')

class cmds(Cog):
	def __init__(self,client): self.client = client

	@cog_ext.cog_slash(name='info',description='information about reginald')
	async def info(self,ctx:SlashContext):
		embed = discord.Embed(title='Reginald Info:',description="""a mash up of the server mcstarter, the discipline sticc, and the mcfuck.\n
		please submit any issues using /reginald issue\n
		and if you have any suggestions, you can use /reginald suggest\n
		you can follow development here: https://discord.gg/4mteVXBDW7\n
		thank you, all hail reginald.""",color=bot.read(['config','embedColor']))
		await ctx.send(embed=embed)
		logOutput(f'reginald info requested',ctx)

	@cog_ext.cog_subcommand(base='get',name='userprofile',description='get the profile of a user')
	async def get_userprofile(self,ctx:SlashContext,user:discord.User=None):
		if not user: user = ctx.author
		description = [f'creation date: {user.created_at.strftime("%m/%d/%Y %H:%M:%S")}',f'display name: {user.display_name}']
		guilds = "\n- ".join([i.name for i in user.mutual_guilds])
		description.append(f'mutual guilds:\n  - {guilds}')
		if str(user.id) in users.read(): # adds birthday and rp score if user has saved data
			if users.read([str(user.id),'messages']): description.append(f"messages sent in mutual servers: {users.read([str(user.id),'messages'])}")
			if users.read([str(user.id),'birthday']): description.append(f"birthday: {users.read([str(user.id),'birthday'])}")
			if users.read([str(user.id),'ricePurityScore']): description.append(f"rice purity score: hidden" if users.read([str(user.id),'ricePurityScore']).startswith('h') else f"rice purity score: {users.read(user.id,['ricePurityScore'])}")
		embed = discord.Embed(title=f'{user.name}\'s profile',description=f'id: {user.id}\nname: {user.name}\ndiscriminator: {user.discriminator}',color=bot.read(['config','embedColor']))
		embed.set_thumbnail(url=user.avatar_url_as(format='png',size=512)) # sets thumbnail to user avatar
		embed.add_field(name='information:',value='\n'.join(description))
		await ctx.send(embed=embed)
		logOutput(f'profile of {user.name} requested',ctx)

	@cog_ext.cog_subcommand(base='get',name='guildprofile',description='get the profile of a guild',
		options=[create_option('guild','id of guild (current guild if left blank)',str,False)])
	async def get_guildprofile(self,ctx:SlashContext,guild_id:str=None):
		await ctx.defer()
		if guild_id: guild = self.client.get_guild(int(guild_id))
		else: guild = ctx.guild
		if not guild:
			try: guild = await self.client.fetch_guild(int(guild_id))
			except discord.errors.Forbidden: await ctx.send('I can\'t get the information on that guild, am I a member?')
		description = [
			f'creation date: {guild.created_at.strftime("%m/%d/%Y %H:%M:%S")}',
			f'online members: {len(list(filter(lambda member: str(member.status) != "offline" and not member.bot,guild.members)))} ({len(list(filter(lambda member: str(member.status) != "offline",guild.members)))})',
			f'total members: {len(list(filter(lambda member: not member.bot,guild.members)))} ({guild.member_count})',
			]
		embed = discord.Embed(title=f'{guild.name}\'s profile',description=f'id: {guild.id}\nname: {guild.name}\nowner: {guild.owner.mention}',color=bot.read(['config','embedColor']))
		embed.set_thumbnail(url=guild.icon.with_format('png').with_size(512).url) # sets thumbnail to guild avatar
		embed.add_field(name='information:',value='\n'.join(description))
		await ctx.send(embed=embed)
		logOutput(f'profile of {guild.name} requested',ctx)

	@cog_ext.cog_subcommand(base='get',name='data',description='request your user data')
	async def get_data(self,ctx:SlashContext):
		userData = users.read([str(ctx.author.id)])
		await ctx.send(embed=discord.Embed(title=f'{ctx.author.name}\'s data',description='\n'.join([f'{i}: {userData[i]}' for i in userData]),color=bot.read(['config','embedColor'])),hidden=True)
		logOutput('user data requested',ctx)

	@cog_ext.cog_subcommand(base='leaderboard',name='messages',description='leaderboard of message count in this server')
	async def leaderboard_messages(self,ctx:SlashContext):
		servers.write({key: value for key, value in sorted(servers.read([str(ctx.guild.id),'messageLeaderboard']).items(),key=lambda item: item[1],reverse=True)},[str(ctx.guild.id),'messageLeaderboard'])
		names = []
		index = 1
		for member in servers.read([str(ctx.guild.id),'messageLeaderboard']):
			if member not in bot.read(['idCache']):
				try: bot.write((await self.client.fetch_user(member)).name,['idCache',member])
				except: continue
			rank = str(index)+("th" if 4<=index%100<=20 else {1:"st",2:"nd",3:"rd"}.get(index%10, "th")); index += 1
			names.append(f"{rank} - {bot.read(['idCache',member])}: {servers.read([str(ctx.guild.id),'messageLeaderboard',member])}")
		await ctx.send(embed=discord.Embed(title='Message Leaderboard:',description='\n'.join(names),color=bot.read(['config','embedColor'])))
		logOutput(f'message leaderboard requested',ctx)

	@cog_ext.cog_slash(name='help',description='get the help page')
	async def help(self,ctx:SlashContext):
		await ctx.send('[Reginald Commands](<https://github.com/TyrantLink/reginald/wiki/commands>)')

def setup(client): client.add_cog(cmds(client))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 21 01:40:24 2019

@author: joshuajacob
"""

import numpy
import timeit
def primes_list_a(n):
    x = numpy.ones(n, dtype = numpy.bool)
    i = 2
    x[0] = x[1] = False
    while i<int((n**0.5)+1):
        if x[i]:
            x[2*i::i] = False
        i += 1
    return(x)

def denom_a(n,primes):
    x = numpy.array(range(n))
    x = numpy.array([float(a) for a in x])
    i = 2
    x[0] = 0
    x[1] = 0
    while i<n:
        if primes[i]:
            x[i::i] *= (i-1)/i
        i += 1
    return(x)

maxy = 1000000
print(sum(denom_a(maxy+1,primes_list_a(maxy+1))))


from telethon import TelegramClient

api_id = "your_api_id"
api_hash = "your_api_hash"

client = TelegramClient("default", api_id, api_hash)
client.start()

async def clean(res, chatsn):
    for n in chatsn:
        c = res[n]
        count, name, messages, group = c[0], c[1], c[2], c[3]

        print(f"Deleting {count} messages from {name}...", end=" ")
        await client.delete_messages(group, messages, revoke=True)
        print("completed!")

async def main():
    print("Telegram message cleaner")

    print("Fetching dialogs...", end="")
    dialogs = await client.get_dialogs(limit=None)
    print(f"\rFetched {len(dialogs)} dialogs in total")

    groups = [i for i in dialogs if i.is_group]
    print(f"{len(groups)} groups \n")

    me = await client.get_me()
    res = []
    for i in groups:
        print(f"\rFetching messages from {i.name}...\t\t", end="")
        messages = [i.id for i in await client.get_messages(i, limit=99999, from_user=me)]
        res.append((len(messages), i.name, messages, i))
    print("\rFetched messages from all groups\t\t")

    res = sorted(res, key=lambda i: (-i[0], i[1]))
    print("Top groups by message count \n")
    print("\n".join((f"[{i}]\t{c[0]} messages \t{c[1]}" for i, c in enumerate(res))))

    delfrom = None
    while not delfrom:
        try:
            print("Enter group numbers (separated by space) from which you want delete ALL your messages:")
            print("example: 0 3 5")
            delfrom = [int(i) for i in input().split()]
        except:
            pass
    await clean(res, delfrom)
    print("Done!")

with client:
    client.loop.run_until_complete(main())


#Fibras na Horizontal com k11 = 0.53, k22 = 0.485, e sem tumor
# 2 significa com tumor
#across em r, e along em z

import numpy
import math
import matplotlib.pyplot as plt
import seaborn

#valores pares, e manter proporção de 10 colunas por 8 linhas, para ficar o tamanho bom do tumor, que ele fique quadrado
#nr = 0.8 * nz
nr = 80
nz = 100

T = numpy.zeros([nr, nz], dtype=float)

Z = 0.1
R = 0.03
ra = 0.01

ro = 1050
c = 3617
Ta = 37

h = 10.0
Tinf = 23.0

#k11=0.53 para W e E
#k22=0.485 para S e N
#Na condicao de contorno fica em r aqui, e assim k11, podendo ser como ke, como está, porque o valor de ke
#muda aqui em cima tambem

def calculo(E):

    for i in range(0, nr, 1):

        ke = 0.53
        kw = 0.53
        ks = 0.485
        kn = 0.485
        gm = 991.9
        w = 0.0006722

        for j in range(0, nz, 1):

            an = ((((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * kn * ((R - ra) / nr)) / (Z / nz)
            asul = ((((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ks * ((R - ra) / nr)) / (Z / nz)
            ae = ((((i + 1) * (R - ra) / nr) + ra) * ke * (Z / nz)) / ((R - ra) / nr)
            aw = (((i * (R - ra) / nr) + ra) * kw * (Z / nz)) / ((R - ra) / nr)

            sc = (gm * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr))) + (
                        ro * c * w * Ta * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

            if (i == 0 and j == 0):
                ap = an + ae + (ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((ae * (E[i + 1, j])) / ap) + (sc / ap)

            elif (i == 0 and j != 0 and j != nz - 1):
                ap = an + ae + asul + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((asul * (E[i, j - 1])) / ap) + ((ae * (E[i + 1, j])) / ap) + (
                            sc / ap)

            elif (i == 0 and j == nz - 1):
                ap = ae + asul + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((asul * (E[i, j - 1])) / ap) + ((ae * (E[i + 1, j])) / ap) + (sc / ap)

            elif (i != 0 and i != nr - 1 and j == nz - 1):
                ap = ae + aw + asul + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((asul * (E[i, j - 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + (ae * (E[i + 1, j]) / ap) + (
                            sc / ap)

            elif (i == nr - 1 and j == nz - 1):
                q1 = 400
                q2 = h / (1 + (h * ((R - ra) / (nr * 2)) / ke))
                ap = aw + asul + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr))) + (
                                 (((i + 1.0) * (R - ra) / nr) + ra) * (Z / nz) * (q2))

                E[i, j] = ((asul * (E[i, j - 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + (sc / ap) + (
                            ((((i + 1.0) * (R - ra) / nr) + ra) * (Z / nz) * (q1 + (q2 * Tinf))) / ap)

            elif (i == nr - 1 and j != 0 and j != nz - 1):
                q1 = 400
                q2 = h / (1 + (h * ((R - ra) / (nr * 2)) / ke))
                ap = an + aw + asul + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr))) + (
                                 (((i + 1.0) * (R - ra) / nr) + ra) * (Z / nz) * (q2))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((asul * (E[i, j - 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + (
                            sc / ap) + (((((i + 1.0) * (R - ra) / nr) + ra) * (Z / nz) * (q1 + (q2 * Tinf))) / ap)

            elif (i == nr - 1 and j == 0):
                q1 = 400
                q2 = h / (1 + (h * ((R - ra) / (nr * 2)) / ke))
                ap = an + aw + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr))) + (
                                 (((i + 1.0) * (R - ra) / nr) + ra) * (Z / nz) * (q2))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + (sc / ap) + (
                            ((((i + 1.0) * (R - ra) / nr) + ra) * (Z / nz) * (q1 + (q2 * Tinf))) / ap)

            elif (i != 0 and i != nr - 1 and j == 0):
                ap = an + ae + aw + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + ((ae * (E[i + 1, j])) / ap) + (
                            sc / ap)

            elif ((i != 0 and i != nr - 1 and j != 0 and j != nz - 1) and ((i < ((nr/2))) or (i > ((nr/2) + (1 * nr/8))) or (j < (nz/2)) or (j > ((nz/2) + (1 * nz/10))))): # pra fora do tumor
                ap = an + ae + aw + asul + (
                            ro * c * w * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((asul * (E[i, j - 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + (
                            (ae * (E[i + 1, j])) / ap) + (sc / ap)

            elif ((i >= ((nr / 2))) and (i <= ((nr / 2) + (1 * nr / 8))) and (j >= (nz / 2)) and (j <= ((nz / 2) + (1 * nz / 10)))):  # pra dentro do tumor
                #professor pediu para multiplicar a perfusividade por 5, estou aumentano o w, mas precisa confirmar, CONFERIR SE E A PERFUSIVIDADE MESMO
                ap = an + ae + aw + asul + (
                        ro * c * (w*5) * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                #so multipliquei a geracao de calor do tumor por 10, ver se tem mais mudancas para ele
                sc = (10 * gm * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr))) + (
                        ro * c * (w*5) * Ta * ((Z / nz) * (((i + (1.0 / 2.0)) * (R - ra) / nr) + ra) * ((R - ra) / nr)))

                E[i, j] = ((an * (E[i, j + 1])) / ap) + ((asul * (E[i, j - 1])) / ap) + ((aw * (E[i - 1, j])) / ap) + (
                        (ae * (E[i + 1, j])) / ap) + (sc / ap)

    print(E)
    return E

#inicializacao com o T de zeros
F = calculo(T)
D = F.copy()

#iteracoes e convergencia
ncolunas3 = (nr * nz)
cont_i = 0

for a in range(0, 10000000000000, 1):
    DOld2 = D
    DOld3 = numpy.reshape(DOld2, ncolunas3)
    DOld4 = DOld3.copy()

    #print(DOld4)
    #print("----------------------------------")
    #print(D)
    D = calculo(D)
    #print(D)

    DNew2 = D.copy()
    DNew3 = numpy.reshape(DNew2, ncolunas3)
    DNew4 = DNew3.copy()
    #print(DNew4)

    Ddif = []
    for i in range(0, ncolunas3, 1):
        Ddif.append(math.fabs(DOld4[i] - DNew4[i]))

    MaxDif = numpy.max(Ddif)
    # print(MaxDif)
    Tol = 0.000001
    cont_i += 1

    if (MaxDif <= Tol):
        break

    #print(Ddif)

print(cont_i)

#plot
eixoz = numpy.linspace(0, Z)
eixor = numpy.linspace(ra, R, nr)
eixox = D

numpy.meshgrid(eixoz, eixor)
ax = seaborn.heatmap(eixox)
ax.invert_yaxis()

#plt.title('TccCode13_2_FH, Malha de '+ str(nr) + ' x ' + str(nz) + ' volumes', fontsize=20)
plt.xlabel("Eixo z [m]", fontsize=25)
plt.ylabel("Eixo r [m]", fontsize=25)
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])

#color bar formats
ax.collections[0].colorbar.set_label("T[°C]", fontsize=25)
cbar = ax.collections[0].colorbar.ax.tick_params(labelsize=20)

#legendas limites
x0, x1 = 0, 0.1
y0, y1 = 0.01, 0.03
ax.text(0, -0.07, x0, ha='center', va='top', fontsize=20, color='black', transform=ax.transAxes)
ax.text(1, -0.07, x1, ha='center', va='top', fontsize=20, color='black', transform=ax.transAxes)
ax.text(-0.05, 0, y0, ha='right', va='center', fontsize=20, color='black', transform=ax.transAxes)
ax.text(-0.05, 1, y1, ha='right', va='center', fontsize=20, color='black', transform=ax.transAxes)
ax.vlines([0, 1], [0, 0], [-0.06, -0.06], color='black', clip_on=False, transform=ax.transAxes)
ax.hlines([0, 1], [0, 0], [-0.04, -0.04], color='black', clip_on=False, transform=ax.transAxes)
plt.tight_layout()

plt.show()


import pandas as pd
import logging
import sys
import os
import numpy as np

from itertools import chain
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.decomposition import NMF, LatentDirichletAllocation

formatter = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s',
                              datefmt='%Y-%m-%d %H:%M:%S')
np.random.seed(42)

class Streamgraph(object):

    def __init__(self, loglevel="INFO"):
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(loglevel)
        handler = logging.StreamHandler(sys.stdout)
        handler.setFormatter(formatter)
        handler.setLevel(loglevel)
        self.logger.addHandler(handler)

    def get_streamgraph_data(self, metadata, query, n=12, method="tfidf"):
        df = pd.DataFrame.from_records(metadata)
        df.year = pd.to_datetime(df.year)
        df.year = df.year.map(lambda x: x.year)
        df.year = df.year.map(lambda x: pd.to_datetime(x, format="%Y"))
        df = df[df.subject.map(lambda x: x is not None)]
        df.subject = df.subject.map(lambda x: [s for s in x.split("; ") if s])
        df = df[df.subject.map(lambda x: x != [])]
        df["boundary_label"] = df.year
        df = df.explode('subject')
        df = df[df.subject != ""]
        counts = self.get_counts(df)
        boundaries = self.get_boundaries(df)
        daterange = self.get_daterange(boundaries)
        data = pd.merge(counts, boundaries, on='year')
        top_n = self.get_top_n(metadata, query, n, method)
        data = (data[data.subject.map(lambda x: x in top_n)]
                .sort_values("year")
                .reset_index(drop=True))
        x = self.get_x_axis(daterange)
        sg_data = {}
        sg_data["x"] = x
        sg_data["subject"] = self.postprocess(daterange, data)
        return sg_data

    @staticmethod
    def get_x_axis(daterange):
        return [str(x.year) for x in daterange]

    @staticmethod
    def get_daterange(boundaries):
        daterange = pd.date_range(start=min(boundaries.year).to_datetime64(),
                                  end=max(boundaries.year).to_datetime64(),
                                  freq='AS')
        if len(daterange) > 0:
            return sorted(daterange)
        else:
            return sorted(pd.unique(boundaries.year))

    @staticmethod
    def get_stream_range(df):
        stream_range = {
            "min": min(df.year),
            "max": max(df.year),
            "range": max(df.year) - min(df.year)
        }
        return stream_range

    @staticmethod
    def get_counts(df):
        counts = (df.groupby(["year", "subject"])
                    .agg({'subject': 'count', 'id': lambda x: ", ".join(x)}))
        counts.rename({"subject": "counts"}, axis=1, inplace=True)
        counts.reset_index(inplace=True)
        return counts

    @staticmethod
    def get_boundaries(df):
        boundaries = df[["boundary_label", "year"]].drop_duplicates()
        return boundaries

    def get_top_n(self, metadata, query, n, method):
        df = pd.DataFrame.from_records(metadata)
        df = df[df.subject.map(lambda x: len(x) > 2)]
        corpus = df.subject.tolist()
        # set stopwords , stop_words='english'
        tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2,
                                        tokenizer=lambda x: x.split("; "),
                                        lowercase=False,
                                        stop_words=[query]
                                        )
        tfidf_vectorizer = TfidfVectorizer(max_df=0.95, min_df=2,
                                           tokenizer=lambda x: x.split("; "),
                                           lowercase=False,
                                           stop_words=[query]
                                           )
        if method == "count":
            tf = tf_vectorizer.fit_transform(corpus)
            counts = pd.DataFrame(tf.toarray(),
                                  columns=tf_vectorizer.get_feature_names())
            candidates = counts.sum().sort_values(ascending=False).index.tolist()
            candidates = [c for c in candidates if len(c) > 0]
            top_n = candidates[:n]
        if method == "tfidf":
            tfidf = tfidf_vectorizer.fit_transform(corpus)
            weights = pd.DataFrame(tfidf.toarray(),
                                   columns=tfidf_vectorizer.get_feature_names())
            candidates = weights.sum().sort_values(ascending=False).index.tolist()
            candidates = [c for c in candidates if len(c) > 0]
            top_n = candidates[:n]
        if method == "nmf":
            tfidf = tfidf_vectorizer.fit_transform(corpus)
            nmf = NMF(n_components=n,
                      alpha=.1, l1_ratio=.5, init='nndsvd',
                      random_state=42).fit(tfidf)
            top_n = list(chain.from_iterable(
                            [self.get_top_words(t, tfidf_vectorizer.get_feature_names(), 1)
                             for t in nmf.components_]))
        if method == "lda":
            tf = tf_vectorizer.fit_transform(corpus)
            lda = LatentDirichletAllocation(n_components=n, max_iter=20,
                                            learning_method='batch',
                                            learning_offset=50.,
                                            random_state=42).fit(tf)
            top_n = list(chain.from_iterable(
                            [self.get_top_words(t, tf_vectorizer.get_feature_names(), 1)
                             for t in lda.components_]))
        return top_n

    @staticmethod
    def get_top_words(topic, feature_names, n):
        indices = topic.argsort()[::-1]
        words = [feature_names[i] for i in indices]
        words = [w for w in words if len(w) > 2]
        return words[:n]

    @staticmethod
    def postprocess(daterange, data):
        x = pd.DataFrame(daterange, columns=["year"])
        temp = []
        for item in pd.unique(data.subject):
            tmp = (pd.merge(data[data.subject == item], x,
                            left_on="year", right_on="year",
                            how="right")
                     .fillna({"counts": 0, "subject": item, "id": "NA"})
                     .sort_values("year"))
            y = tmp.counts.astype(int).to_list()
            ids_overall = (pd.unique(tmp[tmp.id != "NA"]
                                     .id.map(lambda x: x.split(", "))
                                     .explode()).tolist())
            ids_timestep = tmp.id.map(lambda x: x.split(", ")).tolist()
            temp.append({"name": item, "y": y,
                         "ids_overall": ids_overall,
                         "ids_timestep": ids_timestep})
        df = pd.DataFrame.from_records(temp)
        return df.to_dict(orient="records")


import unittest
import os
import cv2

from calibrate_camera import CalibratedCamera

class CalibratedCameraTest(unittest.TestCase):

	def test_constuctor_sets_mtx_dist_if_pickle_is_not_available(self):
		pickle_file_name = "something.p"
		images_pattern = "camera_cal/calibration*.jpg"

		os.remove(pickle_file_name)
		calibrated_camera = CalibratedCamera(pickle_file_name, images_pattern)

		self.assertIsNotNone(calibrated_camera.mtx)
		self.assertIsNotNone(calibrated_camera.dist)

	def test_constuctor_set_mtx_dist_from_pickle_if_available(self):
		pickle_file_name = "something.p"
		images_pattern = "camera_cal/calibration*.jpg"

		os.remove(pickle_file_name)

		# create the pickle
		CalibratedCamera(pickle_file_name, images_pattern)

		# now calibrated camera sets those from pickle
		calibrated_camera = CalibratedCamera(pickle_file_name, images_pattern)
		self.assertIsNotNone(calibrated_camera.mtx)
		self.assertIsNotNone(calibrated_camera.dist)

	def test_calibrated_camera_can_undistort_image(self):
		input_file = "./test_images/test1.jpg"
		output_file = "output_images/undistorted_example.jpg"
		c = CalibratedCamera()
		c.undistort_file(input_file, output_file)

		self.assertTrue(os.path.exists(output_file))

	def test_undistort_image(self):
		input_file = "./test_images/test1.jpg"
		image = cv2.imread(input_file)

		c = CalibratedCamera()
		undistorted_image = c.undistort(image)

		self.assertTrue(undistorted_image.shape == image.shape)


from contextlib import contextmanager
from functools import reduce
from operator import or_
from unittest import mock

from django.conf import settings
from django.contrib.auth.models import Permission
from django.db.models import Q
from rest_framework.test import APITestCase

class PermissionTest(APITestCase):

    @contextmanager
    def _set_perms(self, user, perms):
        if perms:
            q = reduce(or_, [Q(content_type__app_label=perm.split('.')[0]) & Q(codename=perm.split('.')[1])
                             for perm in perms])
            perm_pairs = Permission.objects.filter(q).values_list('content_type__app_label', 'codename')
            existing_perms = {f'{app_label}.{codename}' for app_label, codename in perm_pairs}

            self.assertSetEqual(set(perms), existing_perms, 'Some permissions do not exist. Typo?')

        patch = [None]

        def handler(_self, current_user, *args, **kwargs):
            if user.id == current_user.id:
                return set(perms)

            backend = patch[0].target()
            original = patch[0].temp_original
            return original(backend, current_user, *args, **kwargs)

        patch[0] = mock.patch(f'{settings.AUTHENTICATION_BACKENDS[0]}.get_all_permissions', handler)

        with patch[0]:
            yield


import tkinter as tk
from tkinter import filedialog

import numpy as np

from Classes import Evento

def leitura_evento():
    root = tk.Tk()
    root.withdraw()

    f_tse = filedialog.askopenfilename(
        title="Selecione o arquivo .tse",
        filetypes=(("tse files", "*.tse"), ("all files", "*.*")),
    )
    return f_tse

def importar_evento():
    root = tk.Tk()
    root.withdraw()

    f_tse = filedialog.askopenfilename(
        title="Selecione o arquivo .tse",
        filetypes=(("tse files", "*.tse"), ("all files", "*.*")),
    )

    # f_tse = open("caminho_arquivo", "r")

    # conteudo = np.loadtxt(f_tse, dtype=('f4', 'f4', 'str', 'i4'), skiprows=2)

    conteudo = np.genfromtxt(f_tse, dtype="str", skip_header=2)

    quantidade_eventos = len(conteudo[:])

    eventos = []

    for i in range(0, quantidade_eventos - 1):
        evento = Evento.Evento(
            float(conteudo[i][0]),
            float(conteudo[i][1]),
            conteudo[i][2],
            float(conteudo[i][3]),
        )
        eventos.append(evento)

    return eventos


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

import rospy
from geometry_msgs.msg import Pose2D, Twist
from tms_msg_rc.srv import rc_robot_control, rc_robot_controlResponse
from tms_msg_db.srv import TmsdbGetData, TmsdbGetDataRequest

import datetime
import pymongo
from math import sin, cos, atan2, pi, radians, degrees, sqrt
pub = rospy.Publisher("mimamorukun/cmd_vel", Twist, queue_size=10)

GOAL = None

def main():
    global GOAL
    global cmd
    print ("\x1b[32mHello World\x1b[39m")
    rospy.init_node('wheelchair_voronoi_follower')

    print ("finding DB service server")
    rospy.wait_for_service('/tms_db_reader')
    print ("found DB service server")

    service = rospy.Service(
        "mkun_goal_pose", rc_robot_control, goalPoseCallback)

    r = rospy.Rate(10)
    while not rospy.is_shutdown():
        if None == GOAL:
            continue
        KPang = 0.3  # 1.0
        KDang = 0
        KPdist = 0.4  # 2.0
        KDdist = 0
        ARV_DIST = 0.25

        pose = getCurrentPose()
        twist = Twist()
        errorT = normalizeAng(GOAL.theta - pose.theta)

        if cmd == 10:
            twist.angular.z = 0
            twist.linear.x = 0
            GOAL = None
        elif cmd == 1:
            tmp_turn = limit(KPang * errorT,0.15,-0.15)
            rospy.loginfo("turn:{0}".format(tmp_turn))
            twist.angular.z = tmp_turn
            twist.linear.x = 0
        else:
            errorX = GOAL.x - pose.x
            errorY = GOAL.y - pose.y
            targetT = atan2(errorY, errorX)

            errorNX = errorX * cos(-pose.theta) - errorY * sin(-pose.theta)
            errorNT = normalizeAng(targetT - pose.theta)

            tmp_spd = limit(KPdist * errorNX, 0.2, -0.2)
            tmp_turn = limit(KPang * errorNT, 0.15, -0.15)

            distance = sqrt(errorX ** 2 + errorY ** 2)
            rospy.loginfo("dist:{0}".format(distance))
            rospy.loginfo("psd:{0}  turn:{1}".format(tmp_spd, tmp_turn))
            twist.angular.z = tmp_turn
            twist.linear.x = tmp_spd
        pub.publish(twist)
        r.sleep()

def goalPoseCallback(req):
    rospy.loginfo("\x1b[32mreq:\x1b[39m{} \x1b[32m/req\x1b[39m".format(req))

    global GOAL
    GOAL = Pose2D()
    GOAL.x = req.arg[0]
    GOAL.y = req.arg[1]
    GOAL.theta = req.arg[2]
    global cmd
    cmd = req.cmd

    return rc_robot_controlResponse()   # response is not used

def getCurrentPose():
    pose = Pose2D()
    db_req = TmsdbGetDataRequest()
    db_req.tmsdb.id = 2007     # wheelchair
    db_req.tmsdb.sensor = 3001  # vicon
    try:
        srv_client = rospy.ServiceProxy("/tms_db_reader",
                                        TmsdbGetData)
        res = srv_client(db_req)
        if 0 == len(res.tmsdb):
            return pose     # failed
        # print datetime.datetime.now(),
        # print"x:%4f  y:%4f yaw:%4f" % (res.tmsdb[0].x, res.tmsdb[0].y, res.tmsdb[0].ry)
        pose.x = res.tmsdb[0].x
        pose.y = res.tmsdb[0].y
        pose.theta = res.tmsdb[0].ry
    except rospy.ServiceException as e:
        print ("Service call failed: %s" % e)
    return pose

def normalizeAng(rad):
    while rad > pi:   # 角度を-180°~180°(-π~π)の範囲に合わせる
        rad = rad - (2 * pi)
    while rad < -pi:
        rad = rad + (2 * pi)
    return rad

def limit(val, maxn, minn):
    return max(min(maxn, val), minn)

if __name__ == '__main__':
    try:
        main()
    except rospy.ROSInterruptException:
        pass


#!/usr/bin/python3
# encoding: utf-8
"""
Created on 04/01/2017
@author: Data Team
"""
# _*_ coding:utf-8 _*_
from pymongo import MongoClient
import datetime
import calendar
import sys
import os
import time
import math
from bson.objectid import ObjectId
from collections import OrderedDict, Counter, defaultdict
import pandas as pd
import numpy as np
import xlsxwriter
import multiprocessing
import threading
import pickle
import logging

sys.path.append(os.path.abspath(__file__))
mongo = MongoClient(host='10.8.8.111', port=27017, connect=False)
event_mongo = MongoClient('10.8.8.22:27017')

db = mongo['eventsV4']  # 111埋点相关数据库
onions = mongo['onions']  # 用户、课程相关数据库
cache = mongo['cache']  # cache数据库
xinyu = event_mongo['xinyu']

col_pay = db.orderEvents
col_event = db.eventV4
col_event_bak = db.eventV4_bak
col_tutorialTopics = onions.tutorialtopics
col_loudou = xinyu.loudou
col_distinct = xinyu.user_distinct
col_chapter = onions.chapters
col_topic = onions.topics

ONLINE_DATE = datetime.datetime(2017, 3, 12, 16)  # 4.2版本上线时间

now = datetime.datetime.now()
TODAY = datetime.datetime(now.year, now.month, now.day) - datetime.timedelta(hours=8)  # 今天凌晨12点的日期
TOMORROW = TODAY + datetime.timedelta(days=1)
A_WEEK_AGO = TODAY - datetime.timedelta(weeks=1)  # 一周前
NUM_OF_PROCESS = 7  # 多进程时的进程数
appVersion = ['3.3.'+str(i) for i in range(10)]

def get_week_day(weekday):
    """
    获得今天之前的本周或上周星期几的凌晨十二点时间, 比如想知道这个周六的日期(如果今天等于或大于周六, 否则得到的上周六的日期): get_week_day(6)
    :param weekday: 星期一:1, 星期二:2,... 星期天: 7.
    :return: 日期
    """
    idx = ((TODAY+datetime.timedelta(hours=8)).weekday() + 1) % 7
    return TODAY - datetime.timedelta(idx-weekday+(0 if idx >= weekday else 7))

# END = get_week_day(1)  # 本周一凌晨12点日期
# START = END - datetime.timedelta(weeks=1)  # 本周一的一周前日期

# Excel表单格式
HEADER_FORMAT = {
    'bold': 1,  # 字体粗细
    'border': 1,  # 框线粗细
    'align': 'center',  # 水平方向对齐
    'valign': 'vcenter',  # 垂直方向对齐
    'fg_color': 'green',  # 背景颜色
    'color': 'white',  # 字体颜色,
    'font_size': 14
    }

def write_excel(data, no, s2e):
    """
    将数据写入excel文件
    :param data: 二维数组, 数据格式如下:
    [
        ['表头1'],
        ['步骤', 'uv', '转化率'],
        ['步骤1', 10],
        ['步骤2', 5, '50%'],
        ['步骤3', 1, '10%'],
        ['表头2'],
        [['视频类型', 0, 0], ['普通教学视频', 1, 2], ['洋葱真人秀视频', 3, 6]]  # 如果为二维数组, 表示该行需要分块合并单元格,数据依次为[内容, 合并开始列,合并结束列]
        ['指标', '用户数', '付费用户', '付费率'],
        ['指标1', 100, 10, '10%'],
        ['指标2', 100, 10, '10%']
    ]
    :param no: 需求编号, 可以为数字或字符串, 2 或 '02'
    :param s2e: 起始时间, 如: '20170109-20170115'
    :return:
    """
    if type(no) is int:
        no = ('' if no//10 else '0') + str(no)
    workbook = xlsxwriter.Workbook('req' + no + '-' + s2e + '.xlsx')
    worksheet = workbook.add_worksheet('req'+no)

    width = max([len(d) for d in data]) - 1
    worksheet.set_column(0, 0, 25)
    worksheet.set_column(1, width, 15)
    header_format = workbook.add_format(HEADER_FORMAT)
    align_center = workbook.add_format({'align': 'center'})
    # align_right = workbook.add_format({'align': 'right'})

    r = 0
    for i, d in enumerate(data):
        if len(d) == 1:  # 如果该数据长度为1, 则认为是表头, 表头单元格宽度设为下一行数据的宽度
            r += 2 if i != 0 else 0
            w = 1 if i+1 >= len(data) else len(data[i+1])-1 if not all(isinstance(dd, list) for dd in data[i+1]) else width
            worksheet.merge_range(r, 0, r, w, d[0], header_format)
            r += 1
        elif all(isinstance(i, list) for i in d):  # 如果元素是二维数组, 分块合并单元格
            for dd in d:
                if dd[1] >= dd[2]:
                    worksheet.write(r, dd[1], dd[0], align_center)
                else:
                    worksheet.merge_range(r, dd[1], r, dd[2], dd[0], align_center)
            r += 1
        else:
            worksheet.write_row(r, 0, d)
            r += 1
    workbook.close()

def rotate_matrix(data):
    c = len(data)
    r = len(data[0])
    res = [[0 for x in range(c)] for y in range(r)]
    for i in range(c):
        for j in range(r):
            res[j][i] = data[i][j]
    return res

def percent(d1, d2, r=2):
    """
    百分比 (格式: '10.23%')
    :param d1: 分子
    :param d2: 分母
    :param r: 小数点后位数, 默认2
    :return: 百分比, 如果分母为0的话, 返回 NA
    """
    return str(round(d1/d2*100, r)) + '%' if d2 else 'NA'

def start_2_end(start, end, time_difference=True):
    """
    获得起始时间 "2016.05.01-2016.05.10" 格式的字符串
    :param start: 开始时间
    :param end: 结束时间
    :param time_difference 是否需要加八小时的时差,False直接打印传入的start和end
    :return: "2016.05.01-2016.05.10"格式的字符串
    """

    if time_difference:
        start = start + datetime.timedelta(hours=8)
        # end = end + datetime.timedelta(hours=8)

    return str(start.strftime("%Y%m%d")) + '-' + str(end.strftime("%Y%m%d"))

def unpack(iterable):
    """
    unpack a nested array
    :param iterable: input array, e.g. [[1, 2], [3, 4], [4]]
    :return: unpacked array, e.g. [1, 2, 3, 4, 4]
    """
    result = []
    for x in iterable:
        if type(x) is list:
            result.extend(unpack(x))
        else:
            result.append(x)
    return result

def eventtime_2_datetime(t):
    """
    将eventTime(前端时间)转化为datetime形式(UTC时间)
    :param t: 时间戳
    :return: datetime格式的时间(UTC时间)
    """
    return datetime.datetime.fromtimestamp(t/1000) - datetime.timedelta(hours=8)

def datetime_2_timestamp(d):
    """
    将datetime时间(UTC)转化成时间戳
    :param d: datetime格式时间
    :return: 时间戳
    """
    return calendar.timegm(d.timetuple()) * 1000

def generate_sheet(data, workbook, sheetname):
    sheet = workbook.add_worksheet(sheetname)
    for r, row in enumerate(data):
        for c, col in enumerate(row):
            sheet.write(r, c, col)


import numpy as np
import random
from replay_buffer import ReplayBuffer, NaivePrioritizedReplayBuffer
from defaults import *
from model import QNetwork, DuelingQNetwork

import torch
import torch.nn.functional as F
import torch.optim as optim

class DqnAgent():
    """Deep Q-Network agent that interacts with and learns from the environment."""

    def __init__(self, id, state_size, action_size, seed, use_double=False, use_prio=False, use_dueling=False):
        """Initialize an Agent object.

        Params
        ======
            id (int): id used to identify the agent
            state_size (int): dimension of each state
            action_size (int): dimension of each action
            seed (int): random seed
            double (boolean): Use Double DQN algorithm
            use_prio (boolean): Use Prioritized Experience Replay
            use_dueling (boolean): Use Dueling DQN algorithm
        """
        self.state_size = state_size
        self.action_size = action_size
        self.id = id

        self.use_double = use_double
        self.use_prio = use_prio
        self.use_dueling = use_dueling
        self.seed = random.seed(seed)

        self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

        # Q-Network
        if use_dueling:
            self.qnetwork_local = DuelingQNetwork(state_size, action_size, seed).to(self.device)
            self.qnetwork_target = DuelingQNetwork(state_size, action_size, seed).to(self.device)
        else:
            self.qnetwork_local = QNetwork(state_size, action_size, seed).to(self.device)
            self.qnetwork_target = QNetwork(state_size, action_size, seed).to(self.device)

        self.optimizer = optim.Adam(self.qnetwork_local.parameters(), lr=LR)

        # Replay memory
        if use_prio:
            self.memory = NaivePrioritizedReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed, PRIO_ALPHA, PRIO_EPSILON)
        else:
            self.memory = ReplayBuffer(action_size, BUFFER_SIZE, BATCH_SIZE, seed)
        # Initialize time step (for updating every UPDATE_EVERY steps)
        self.t_step = 0

    def step(self, state, action, reward, next_state, done, beta=PRIO_BETA):
        # Save experience in replay memory
        self.memory.add(state, action, reward, next_state, done)

        # Learn every UPDATE_EVERY time steps.
        self.t_step = (self.t_step + 1) % UPDATE_EVERY
        if self.t_step == 0:
            # If enough samples are available in memory, get random subset and learn
            if len(self.memory) > BATCH_SIZE:
                if self.use_prio:
                    experiences, weights = self.memory.sample(beta)
                    states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(self.device)
                    actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(self.device)
                    rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device)
                    next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(self.device)
                    dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(self.device)
                    weights = torch.from_numpy(np.vstack(weights)).float().to(self.device)

                    experiences = (states, actions, rewards, next_states, dones)
                    self.learn(experiences, GAMMA, weights)
                else:
                    experiences = self.memory.sample()

                    states = torch.from_numpy(np.vstack([e.state for e in experiences if e is not None])).float().to(self.device)
                    actions = torch.from_numpy(np.vstack([e.action for e in experiences if e is not None])).long().to(self.device)
                    rewards = torch.from_numpy(np.vstack([e.reward for e in experiences if e is not None])).float().to(self.device)
                    next_states = torch.from_numpy(np.vstack([e.next_state for e in experiences if e is not None])).float().to(self.device)
                    dones = torch.from_numpy(np.vstack([e.done for e in experiences if e is not None]).astype(np.uint8)).float().to(self.device)

                    experiences = (states, actions, rewards, next_states, dones)
                    self.learn(experiences, GAMMA)

    def act(self, state, eps=0.):
        """Returns actions for given state as per current policy.

        Params
        ======
            state (array_like): current state
            eps (float): epsilon, for epsilon-greedy action selection
        """
        state = torch.from_numpy(state).float().unsqueeze(0).to(self.device)
        self.qnetwork_local.eval()
        with torch.no_grad():
            action_values = self.qnetwork_local(state)
        self.qnetwork_local.train()

        # Epsilon-greedy action selection
        if random.random() > eps:
            return np.argmax(action_values.cpu().data.numpy()).item()
        else:
            return random.choice(np.arange(self.action_size)).item()

    def learn(self, experiences, gamma, weights=None):
        """Update value parameters using given batch of experience tuples.

        Params
        ======
            experiences (Tuple[torch.Tensor]): tuple of (s, a, r, s', done) tuples
            gamma (float): discount factor
            weights (array_like): list of weights for compensation the non-uniform sampling (used only
                                    with prioritized experience replay)
        """
        states, actions, rewards, next_states, dones = experiences

        if self.use_double:
            # Evaluate the greedy policy according to the local network
            target_next_indices_local = self.qnetwork_local(next_states).detach().max(1)[1].unsqueeze(1)

            # Get max predicted Q values (for next states) from target model
            Q_targets_next = self.qnetwork_target(next_states).detach().gather(1, target_next_indices_local)
        else:
            # Get max predicted Q values (for next states) from target model
            Q_targets_next = self.qnetwork_target(next_states).detach().max(1)[0].unsqueeze(1)

        # Compute Q targets for current states
        Q_targets = rewards + (gamma * Q_targets_next * (1 - dones))

        # Get expected Q values from local model
        Q_expected = self.qnetwork_local(states).gather(1, actions)

        # Compute loss
        if self.use_prio:
            td_error = Q_expected - Q_targets
            loss = (td_error) ** 2

            loss = loss * weights
            loss = loss.mean()

            self.memory.update_priorities(np.hstack(td_error.detach().cpu().numpy()))

        else:
            loss = F.mse_loss(Q_expected, Q_targets)

        # Minimize the loss
        self.optimizer.zero_grad()
        loss.backward()
        self.optimizer.step()

        # ------------------- update target network ------------------- #
        self.soft_update(self.qnetwork_local, self.qnetwork_target, TAU)

    def soft_update(self, local_model, target_model, tau):
        """Soft update model parameters.
        θ_target = τ*θ_local + (1 - τ)*θ_target

        Params
        ======
            local_model (PyTorch model): weights will be copied from
            target_model (PyTorch model): weights will be copied to
            tau (float): interpolation parameter
        """
        for target_param, local_param in zip(target_model.parameters(), local_model.parameters()):
            target_param.data.copy_(tau*local_param.data + (1.0-tau)*target_param.data)

    def getId(self):
        """ Return the ID of the agent """
        return self.id

    def summary(self):
        """ Return a brief summary of the agent"""
        s = 'DQN Agent {}: Double: {}, PER: {}, Dueling: {}\n'.format(self.id, self.use_double, self.use_prio, self.use_dueling)
        s += self.qnetwork_local.__str__()
        s += '\nMemory size: {} \nBatch size: {}\nGamma: {}\nLR: {}\nTau: {}\nUpdate every: {}'.format(BUFFER_SIZE, BATCH_SIZE, GAMMA, LR, TAU, UPDATE_EVERY)
        return s


#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from datetime import datetime
from pymongo.errors import PyMongoError
from config import DEBUG

def mongo_ingestion(name):

    def decorator(f):

        def wrapper(*args, **kwargs):

            start_time = datetime.now()

            if DEBUG:
                print('*** Start {} ***\n{}\n\n'.format(name, start_time))

            try:
                f(*args, **kwargs)

            except PyMongoError:
                print('Error while committing on MongoDB')
                raise
            except:
                print('Unexpected error:', sys.exc_info()[0])
                raise

            end_time = datetime.now()

            if DEBUG:
                print('\n*** End {} ***\n{}\n'.format(name, end_time))

            elapsed_time = end_time - start_time
            print('\n*** Elapsed ***\n{}\n'.format(elapsed_time))

        return wrapper

    return decorator


import os, sys, importlib
import numpy as np
import const as const

# General visibility dataset object
class dataset:

   def __init__(self, um, vm, vis, wgt, nu_TOPO, nu_LSRK, tstamp_ID):

        # spatial frequencies in meters units
        self.um = um
        self.vm = vm

        # spectral frequencies in Hz units (LSRK for each timestamp)
        self.nu_TOPO = nu_TOPO
        self.nu_LSRK = nu_LSRK

        # data visibilities, weights, and timestamp IDs
        self.vis = vis
        self.npol, self.nchan, self.nvis = vis.shape
        self.wgt = wgt

        self.tstamp = tstamp_ID
        self.nstamps = len(np.unique(tstamp_ID))

# Inference-specific dataset object
class inf_dataset:

    def __init__(self, um, vm, vis_bin, wgt_bin, nu_TOPO, nu_LSRK, tstamp_ID,
                 iwgt, M_bin, invM_bin, lnL0):

        # spatial frequencies in lambda units
        self.um = um
        self.vm = vm

        # timestamps (indices)
        self.tstamp = tstamp_ID
        self.nstamps = len(np.unique(tstamp_ID))

        # **unbinned** frequencies in Hz units (LSRK for each timestamp)
        self.nu_TOPO = nu_TOPO
        self.nu_LSRK = nu_LSRK

        # **binned** data visibilities, weights
        self.vis = vis_bin
        self.wgt = wgt_bin
        self.iwgt = iwgt
        self.npol, self.nchan, self.nvis = self.vis.shape
        self.chbin = np.int(len(self.nu_TOPO) / self.vis.shape[1])

        # likelihood-related quantities
        self.cov = M_bin
        self.inv_cov = invM_bin
        self.lnL0 = lnL0

# Data parsing to generate inputs for likelihood function
def fitdata(file_prefix, vra=None, vcensor=None):

    # Load the configuration file
    inp = importlib.import_module('mconfig_'+file_prefix)

    # Load the metadata and initialize the output dictionary
    data_dict = np.load(inp.dataname+'.npy', allow_pickle=True).item()
    nobs = data_dict['nobs']
    out_dict = {'nobs': nobs}

    # Loop through each EB
    for i in range(nobs):

        # load the data into a dataset object
        d_ = np.load(inp.dataname+'_EB'+str(i)+'.npz')
        idata = dataset(d_['um'], d_['vm'], d_['data'], d_['weights'],
                        d_['nu_TOPO'], d_['nu_LSRK'], d_['tstamp_ID'])

        # if necessary, distribute weights across spectrum
        if not idata.wgt.shape == idata.vis.shape:
            idata.wgt = np.tile(idata.wgt, (idata.nchan, 1, 1))
            idata.wgt = np.rollaxis(idata.wgt, 1, 0)

        # convert the LSRK frequency grid to a velocity grid
        v_LSRK = const.c_ * (1 - idata.nu_LSRK / inp.restfreq)

        # fix direction of desired velocity bounds, based on data format
        if vra is None: vra = [-1e5, 1e5]
        dvi, dvra = np.diff(v_LSRK, axis=1), np.diff(vra)
        if np.logical_or(np.logical_and(np.all(dvi<0), np.all(dvra>0)),
                         np.logical_and(np.all(dvi>0), np.all(dvra<0))):
            vra = vra[::-1]
        sgn_v = np.sign(np.diff(vra)[0])

        # find where to clip to lie within the desired velocity bounds
        midstamp = np.int(idata.nstamps / 2)
        ixl = np.abs(v_LSRK[midstamp,:] - vra[0]).argmin()
        ixh = np.abs(v_LSRK[midstamp,:] - vra[1]).argmin()

        # reconcile channel set to be evenly divisible by binning factor
        if ((ixh - ixl + (ixh - ixl) % inp.chbin[i]) < idata.nchan):
            for j in range((ixh - ixl) % inp.chbin[i]):
                if not (ixh == idata.nchan-1):
                    ixh += 1
                elif not (ixl == 0):
                    ixl -= 1
                else:
                    if j % 2 == 0:
                        ixh -= 1
                    else:
                        ixl += 1

        # clip the data to cover only the frequencies of interest
        inu_TOPO = idata.nu_TOPO[ixl:ixh]
        inu_LSRK = idata.nu_LSRK[:,ixl:ixh]
        iv_LSRK = v_LSRK[:,ixl:ixh]
        inchan = inu_LSRK.shape[1]
        ivis = idata.vis[:,ixl:ixh,:]
        iwgt = idata.wgt[:,ixl:ixh,:]

        # spectral binning
        bnchan = np.int(inchan / inp.chbin[i])
        wt = iwgt.reshape((idata.npol, -1, inp.chbin[i], idata.nvis))
        bvis = np.average(ivis.reshape((idata.npol, -1, inp.chbin[i],
                                        idata.nvis)), weights=wt, axis=2)
        bwgt = np.sum(wt, axis=2)

        # channel censoring
        if vcensor is not None:
            # determine number of censoring zones
            ncens = len(vcensor)

            # approximate velocities of binned channels
            v_ = iv_LSRK[midstamp,:]
            v_bin = np.average(v_.reshape(-1, inp.chbin[i]), axis=1)

            # identify which (binned) channels are censored (==False)
            cens_chans = np.ones(inchan, dtype='bool')
            for j in range(ncens):
                if sgn_v < 0:
                    vcens = (vcensor[j])[::-1]
                else: vcens = vcensor[j]
                ixl = np.abs(iv_LSRK[midstamp,:] - vcens[0]).argmin()
                ixh = np.abs(iv_LSRK[midstamp,:] - vcens[1]).argmin()
                cens_chans[ixl:ixh+1] = False
            cens_chans = np.all(cens_chans.reshape((-1, inp.chbin[i])), axis=1)

            # set weights --> 0 in censored channels
            bwgt[:,cens_chans == False,:] = 0

        # pre-calculate the spectral covariance matrix and its inverse
        if inp.chbin[i] == 2:
            di, odi = (5./16), (3./32)
        elif inp.chbin[i] == 3:
            di, odi = (1./4), (1./24)
        elif inp.chbin[i] == 4:
            di, odi = (13./64), (3./128)
        else:
            di, odi = 1, 0      # this is wrong, but maybe useful to test
        scov = di * np.eye(bnchan) + \
               odi * (np.eye(bnchan, k=-1) + np.eye(bnchan, k=1))
        scov_inv = np.linalg.inv(scov)

        # pre-calculate the log-likelihood normalization
        dterm = np.empty((idata.npol, idata.nvis))
        for ii in range(idata.nvis):
            for jj in range(idata.npol):
                sgn, lndet = np.linalg.slogdet(scov / bwgt[jj,:,ii])
                dterm[jj,ii] = sgn * lndet
        lnL0 = -0.5*(np.prod(bvis.shape) * np.log(2*np.pi) + np.sum(dterm))

        # package the data and add to the output dictionary
        out_dict[str(i)] = inf_dataset(idata.um, idata.vm, bvis, bwgt,
                                       inu_TOPO, inu_LSRK, idata.tstamp, iwgt,
                                       scov, scov_inv, lnL0)

    # return the output dictionary
    return out_dict


'''Python Exercises'''

'''1. Reverse the order of words in a sentence. I.e.: “She sells sea shells” -> “shells sea sells She”.
Both input and output should be strings.'''

napis = "Wniosek urlopowy został zaakceptowany przez dział kadr"
napis1 = "She sells sea shells"
napis2 = "Eve has a cat"

def zadanie_jeden(zdanie):
    #podane zdanie i jego typ
    print(zdanie)
    print(type(zdanie))
    #dodanie do tablicy wyrazów
    tablica = zdanie.split(" ")
    tablica = tablica[::-1]
    print(tablica)
    #odwrocenie tablicy, usuniecie '', zmaina typu
    tablica = str(" ".join(tablica))
    #wypisanie + sprawdzenie typu
    print(type(tablica))
    print(tablica)

#zadanie_jeden(napis)
#zadanie_jeden(napis1)
#zadanie_jeden(napis2)

'''2. Translate input text string to string of numbers on feature-phone keyboard basis. I.e. “a” is one
press of button 2, “b” - two presses of 2, etc. “Eve has a cat”-> 3388833#4427777#2#22228.
 (One can use # as a space). Translation should be case insensitive.'''

klawiatura = {"a": 2, "b": 22, "c": 222, "d": 3, "e": 33, "f": 333, "g": 4, "h": 44, "i": 444,
              "j": 5, "k": 55, "l": 555, "m": 6, "n": 66, "o": 666, "p": 7, "q": 77, "r": 777, "s": 7777,
              "t": 8, "u": 88, "v": 888, "w": 9, "x": 99, "y": 999, "z": 9999, " ": chr(35)}

def zadanie_dwa(zdanie):
    zdanie = zdanie.lower()
    print(zdanie)
    wynik = []
    #literowanie zdania i słownika, jezeli sa takie same to przypisujemy wartosc
    for x in zdanie:
        for y in klawiatura:
            if x == y:
                wynik.append(str(klawiatura[y]))
    wynik = str("".join(wynik))
    print(wynik)

#zadanie_dwa(napis)
#zadanie_dwa(napis1)
#zadanie_dwa(napis2)

'''3. Check how many different digits are in given number. I.e.: 177 - > 2.'''

liczba0 = 177
liczba1 = 77
liczba2 = -7410
liczba3 = 'Javier'

def zadanie_trzy(liczba):
    if type(liczba) != int:
        raise TypeError("Podaj liczbę")
    if liczba < 0:
        liczba = abs(liczba)
    tablica = []
    #rozbicie liczby na cyfry i wpisanie do tablicy
    while liczba > 0:
        x = liczba % 10
        tablica.append(x)
        liczba = int(liczba/10)
    print(tablica)
    wynik = []
    #jezeli jakas cyfra nie wystepuje w nowej tablicy, to ja dodajemy
    for y in tablica:
        if y not in wynik:
            wynik.append(y)
    print(wynik)
    print('Różnych cyfr: ' + str(len(wynik)))

#zadanie_trzy(liczba0)
#zadanie_trzy(liczba1)
#zadanie_trzy(liczba2)
#zadanie_trzy(liczba3)

'''4. Palindrome. Write a program which tells if a word or a sentence is a palindrome.
I.e. “A toyota”, “11 02 2011”, “Anna”. Ignore spaces or letter case.'''

napis4 = "A toyota"
napis5 = "11 02 2011"
napis6 = "Anna"
napis7 = "python"
napis8 = "kajak"
napis9 = "A man a plan a Canal Panama"

def zadanie_cztery(zdanie):
    #ignorowanie wielkości liter i spacji
    napis = zdanie.lower()
    napis = napis.split(" ")
    #print(napis)
    napis = "".join(napis)
    print(napis)
    h = int(len(napis)/2)
    #h wartosci od początku
    czescA = napis[:h]
    #h wartośći od końca
    czescB = napis[-h:]
    czescB = czescB[::-1]
    if czescA == czescB:
        print("Wyrażenie jest palindromem")
    else:
        print('Wyrażenie nie jest palindromem')

#zadanie_cztery(napis4)
#zadanie_cztery(napis5)
#zadanie_cztery(napis6)
#zadanie_cztery(napis7)
#zadanie_cztery(napis8)
zadanie_cztery(napis9)


def inputStringFromFile(inputFilename = None):
    if inputFilename == None:
        print ('input the file name')
        inputFilename = input('>')
    inputFile = open(inputFilename)
    message = inputFile.read()
    inputFile.close()
    return message

def outputStringToFile(message, outputFilename=None):
    if outputFilename==None:
        print('output the string to a file? Y for yes, N for no')
        response = input('>')
        if response.strip().upper().startswith('Y'):
            print ('input the output file name')
            outputFilename = input('>')
    outputFile = open(outputFilename,'w')
    myMessage = outputFile.write(message)
    outputFile.close()


#!/usr/bin/env python3
import sys
import argparse
import json
import yaml
import pymongo
from datetime import datetime
import pandas as pd
from inspect import getmembers, isfunction
from pymongoarrow.api import find_pandas_all, aggregate_pandas_all
import logging

# local lib
import metrics as m

__copyright__ = (
    "© "
    + str(datetime.utcnow().year)
    + ", National Infrastructures for Research and Technology (GRNET)"
)

__status__ = "Production"
__version__ = "0.2.2"

logging.basicConfig(
    stream=sys.stdout,
    level=logging.DEBUG,
    format="[%(asctime)s] %(levelname)s %(message)s",
)

def print_help(func):
    def inner():
        print("RS Metrics Evaluator")
        print("Version: " + __version__)
        print(__copyright__ + "\n")
        func()

    return inner

parser = argparse.ArgumentParser(
    prog="rsmetrics",
    description="Calculate metrics for the EOSC Marketplace RS",
    add_help=False,
)
parser.print_help = print_help(parser.print_help)
parser._action_groups.pop()
optional = parser.add_argument_group("optional arguments")

optional.add_argument(
    "-c",
    "--config",
    metavar=("FILEPATH"),
    help="override default configuration file (./config.yaml)",
    nargs="?",
    default="./config.yaml",
    type=str,
)
optional.add_argument(
    "-p",
    "--provider",
    metavar=("DIRPATH"),
    help=("source of the data based on providers specified "
          "in the configuration file"),
    nargs="?",
    default="cyfronet",
    type=str,
)
optional.add_argument(
    "-s",
    "--starttime",
    metavar=("DATETIME"),
    help=("calculate metrics starting from given datetime in ISO format (UTC) "
          "e.g. YYYY-MM-DD"),
    nargs="?",
    default=None,
)
optional.add_argument(
    "-e",
    "--endtime",
    metavar=("DATETIME"),
    help=("calculate metrics ending to given datetime in ISO format (UTC) "
          "e.g. YYYY-MM-DD"),
    nargs="?",
    default=None,
)

optional.add_argument(
    "-h", "--help", action="help", help="show this help message and exit"
)
optional.add_argument(
    "-V", "--version", action="version", version="%(prog)s v" + __version__
)
optional.add_argument("-v", action="store_true")

args = parser.parse_args()
logging.disable = not args.v

run = m.Runtime()

if args.starttime:
    args.starttime = datetime.fromisoformat(args.starttime)

if args.endtime:
    edt = datetime.fromisoformat(args.endtime)
    args.endtime = datetime.combine(edt, datetime.max.time())

# if not args.starttime:
#     args.starttime = datetime(1970, 1, 1)

# if not args.endtime:
#     args.endtime = datetime.utcnow()

if args.starttime and args.endtime:
    if args.endtime < args.starttime:
        print("End date must be older than start date")
        sys.exit(0)

# read configuration file
with open(args.config, "r") as _f:
    config = yaml.load(_f, Loader=yaml.FullLoader)

if args.provider not in [p["name"] for p in config["providers"]]:
    print("Provider must be in the configuration")
    sys.exit(0)

# read data
# connect to db server
datastore = pymongo.MongoClient(config["datastore"],
                                uuidRepresentation="pythonLegacy")

# use db
rsmetrics_db = datastore[config["datastore"].split("/")[-1]]

# establish a matching query to select data for correct provider and
# start/end date
match_query = {}
if args.starttime is not None:
    if "timestamp" not in match_query:
        match_query["timestamp"] = {}
    match_query["timestamp"]["$gte"] = args.starttime

if args.endtime is not None:
    if "timestamp" not in match_query:
        match_query["timestamp"] = {}
    match_query["timestamp"]["$lte"] = args.endtime

# merge dictionaries to create two seperate match queries (one for user
# actions and one for rec)
match_ua = {**match_query, "provider": {"$in": [args.provider]}}
match_rs = {**match_query, "provider": args.provider}

# first column (_id) ignored, where iloc is used
# pymongoarrow lib provides efficient and direct load of query results into
# panda data frames using functions such as find_pandas_all and
# aggregate_pandas_all
logging.info("Reading user actions...")
run.user_actions_all = find_pandas_all(
    rsmetrics_db["user_actions"], match_ua
).iloc[:, 1:]

logging.info("Reading recommendations...")
if args.provider == "athena":
    # aggregate_pandas_all directly returns a pandas dataframe
    run.recommendations = aggregate_pandas_all(
        rsmetrics_db["recommendations"],
        [
            {"$match":  match_rs},
            {
                "$addFields": {
                    "x": {"$zip": {"inputs": ["$resource_ids",
                                   "$resource_scores"]}}
                }
            },
            {"$unwind": "$x"},
            {
                "$addFields": {
                    "resource_ids": {"$first": "$x"},
                    "resource_scores": {"$last": "$x"},
                }
            },
        ],
    ).iloc[:, 1:-1]

else:
    run.recommendations = aggregate_pandas_all(
        rsmetrics_db["recommendations"],
        [{"$match": match_rs},
         {"$unwind": "$resource_ids"}],
    ).iloc[:, 1:]

run.recommendations.rename(columns={'resource_ids': 'resource_id'},
                           inplace=True)

# Due to the users and services data having nested fields and small number of
# results (hundreds to a couple of thousands) the pymongoarrow lib is not
# used to create the data frames. _ids are filtered out from the column
# results during the query
logging.info("Reading users...")

run.users = pd.DataFrame(
    list(rsmetrics_db["users"].find({
        "$and": [
            {"provider": {"$in": [args.provider]}},
            {"$or": [{"created_on": {"$lte": args.endtime}},
                     {"created_on": None}]},
            {"$or": [{"deleted_on": {"$gte": args.starttime}},
                     {"deleted_on": None}]},
        ]},
        {"_id": 0}))
)

logging.info("Reading services...")
run.services = pd.DataFrame(
    list(rsmetrics_db["resources"].find({
        "$and": [
            {"provider": {"$in": [args.provider]}},
            {"$or": [{"created_on": {"$lte": args.endtime}},
                     {"created_on": None}]},
            {"$or": [{"deleted_on": {"$gte": args.starttime}},
                     {"deleted_on": None}]},
        ]},
        {"_id": 0}))
)

logging.info("Reading categories...")
run.categories = pd.DataFrame(
                              list(rsmetrics_db["category"].find({},
                                   {"_id": 0}))
)

logging.info("Reading scientific domains...")
run.scientific_domains = pd.DataFrame(
                              list(rsmetrics_db["scientific_domain"].find({},
                                   {"_id": 0}))
)

data_errors = []
if len(run.user_actions_all) == 0:
    data_errors.append("No user actions found")

if len(run.user_actions_all) == 0:
    data_errors.append("No recommendations found")

if len(run.services) == 0:
    data_errors.append("No services found")

if len(run.users) == 0:
    data_errors.append("No users found")

if len(run.categories) == 0:
    data_errors.append("No categories found")

if len(run.scientific_domains) == 0:
    data_errors.append("No scientific domains found")

if data_errors:
    for data_error in data_errors:
        logging.error(data_error)
    logging.error("Not enough data. Skipping computations!")
    sys.exit(1)

# convert timestamp column to datetime object
run.user_actions_all["timestamp"] = (
    pd.to_datetime(run.user_actions_all["timestamp"])
)

run.recommendations["timestamp"] = (
    pd.to_datetime(run.recommendations["timestamp"])
)

# remove user actions when user or service does not exist in users' or
# services' catalogs adding -1 in all catalogs indicating the anonynoums
# users or not-known services
run.user_actions = run.user_actions_all[
    run.user_actions_all["user_id"].isin(run.users["id"].tolist() + [-1])
]
run.user_actions = run.user_actions[
    (run.user_actions["source_resource_id"]
     .isin(run.services["id"].tolist() + [-1]))
]
run.user_actions = run.user_actions[
    (run.user_actions["target_resource_id"]
     .isin(run.services["id"].tolist() + [-1]))
]

# remove recommendations when user or service does not exist in users' or
# services' catalogs adding -1 in all catalogs indicating the anonynoums users
# or not-known services
run.recommendations = run.recommendations[
    run.recommendations["user_id"].isin(run.users["id"].tolist() + [-1])
]
run.recommendations = run.recommendations[
    (run.recommendations["resource_id"]
     .isin(run.services["id"].tolist() + [-1]))
]

run.provider = args.provider

output = {"timestamp": str(datetime.utcnow())}
metrics = []
statistics = []

# get all function names in metrics module
func_names = list(map(lambda x: x[0], getmembers(m, isfunction)))
# keep all function names except decorators such as metric and statistic
func_names = list(filter(lambda x: not (x == "metric" or x == "statistic"),
                         func_names))

for func_name in func_names:
    # get function based on function name

    func = getattr(m, func_name)
    # if function has attribute kind
    # (which means that evaluates a metric or a static)
    if hasattr(func, "kind"):
        kind = getattr(func, "kind")
        logging.info("Evaluating {}: {}...".format(kind, func_name))
        # execute and get value
        value = func(run)
        documentation = ""
        # if has documentation ge it
        if hasattr(func, "doc"):
            documentation = func.doc
        # prepare json output object with function name, execution result
        # and optional documentation
        item = {"name": func_name, "value": value, "doc": documentation}
        # if metric add it to the metrics list else to the statistics list
        if kind == "metric":
            metrics.append(item)
        elif kind == "statistic":
            statistics.append(item)

# Add the two lists to the final output onject
output["metrics"] = metrics
output["statistics"] = statistics
output["type"] = "service"
output["provider"] = args.provider

# this line is necessary in order to store the output to MongoDB
jsonstr = json.dumps(output, indent=4)

rsmetrics_db["metrics"].delete_many({"provider": args.provider})
rsmetrics_db["metrics"].insert_one(output)

# result in stdout console (not in logs)
print(jsonstr)
logging.info("Metrics computation finished for {}...".format(
    args.provider))


#!/bin/python3

import math
import os
import random
import re
import sys

import math

#
# Complete the 'protectionTime' function below.
#
# The function is expected to return an INTEGER.
# The function accepts following parameters:
#  1. INTEGER_ARRAY startingPos
#  2. INTEGER_ARRAY speed
#

def protectionTime(startingPos, speed):
    # Write your code here
    sec = 1
    goal_times = []

    for i in range(len(startingPos)):
        goal_times.append( math.ceil(startingPos[i] / speed[i]) )

    goal_times.sort()

    # for i in range(len(startingPos)):
    #     goal_times.remove(min(goal_times))
    #     if sec in goal_times or len(goal_times) == 0:
    #         return sec
    #     sec += 1

    for i in range(0, len(goal_times)):
        if sec > goal_times[i]:
            return goal_times[i]
        sec += 1

    return goal_times[-1]

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    startingPos_count = int(input().strip())

    startingPos = []

    for _ in range(startingPos_count):
        startingPos_item = int(input().strip())
        startingPos.append(startingPos_item)

    speed_count = int(input().strip())

    speed = []

    for _ in range(speed_count):
        speed_item = int(input().strip())
        speed.append(speed_item)

    result = protectionTime(startingPos, speed)

    fptr.write(str(result) + '\n')

    fptr.close()


import tensorflow.compat.v1 as tf
import argparse
import os

def convert_to_tflite(graph_def_file, in_layer_name, out_layer_name, input_shapes=None):
    file_name, file_ext = os.path.splitext(graph_def_file)
    converter = tf.lite.TFLiteConverter.from_frozen_graph(graph_def_file, [in_layer_name], [out_layer_name], input_shapes)
    converter.allow_custom_ops = True
    tflite_model = converter.convert()
    output_filename = file_name + ".tflite"
    with open(output_filename, "wb") as file:
        file.write(tflite_model)
    return output_filename

def main():
    parser = argparse.ArgumentParser(description='Converts a tensorflow frozen model to tflite.')
    parser.add_argument('--file', '-f', action='store', dest='graph_def_file',
                        help='input tensorflow frozen model (.pb file)')
    parser.add_argument('--in-layer', '-i', action='store', dest='input_arrays',
                        help='name of input array')
    parser.add_argument('--out-layer', '-o', action='store', dest='output_arrays',
                        help='name of output array')
    parser.add_argument('--input_shapes', action='store', dest='input_shapes',
                        help='input shape size')
    args = parser.parse_args()
    convert_to_tflite(args.graph_def_file, args.input_arrays, args.output_arrays, args.input_shapes)

if __name__ == "__main__":
    main()


from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView

from .models import Author, Book
from .serializers import AuthorSerializer, BookSerializer

class AuthorDetail(RetrieveUpdateDestroyAPIView):
    """
    Retrieves, updates or deletes an author
    """

    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

class AuthorList(ListCreateAPIView):
    """
    Lists all existing authors or creates a new one
    """

    queryset = Author.objects.all()
    serializer_class = AuthorSerializer

class BookDetail(RetrieveUpdateDestroyAPIView):
    """
    Retrieves, updates or deletes an author
    """

    queryset = Book.objects.all()
    serializer_class = BookSerializer

class BookList(ListCreateAPIView):
    """
    Lists all existing books or creates a new one
    """

    queryset = Book.objects.all()
    serializer_class = BookSerializer


import pytest
from tutor import app, db
from tutor.models.course import Resource, Course
from tutor.models.users import Users

@pytest.fixture
def client():
    app.config['WTF_CSRF_ENABLED'] = False
    app.config['TESTING'] = True
    return app.test_client()

@pytest.fixture(autouse=True)
def cleanup():
    yield None
    for user in Users.query.all():
        user.removeAllFavorites()
    Resource.query.delete()
    Course.query.delete()
    Users.query.delete()
    db.session.commit()


from flask_restplus import Resource
import app.main.service.update_user_service as update_user_service
from app.main.controller.rest_plus_api import Api

api = Api.api

@api.route('/<id>/update')
@api.doc(params={'id': 'users id', 'runId': 'the id of the specific run'})
class UpdateController(Resource):
    @api.doc('Forces an update from the user')
    def get(self, id):
        """Updates the user"""
        update_user_service.updateUser(id)
        return {}, 200


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

"""Test Canvas object."""

# Third party imports
import pytest

# Local imports
from canvascli import Canvas
from data import CANVAS_2_3, TEST_CASE_1, TEST_CASE_2

TEST_WIDTH = 20
TEST_HEIGHT = 4

# --- Fixtures
# -----------------------------------------------------------------------------
@pytest.fixture
def test_canvas():
    c = Canvas(TEST_WIDTH, TEST_HEIGHT)
    return c

# --- Helper methods
# -----------------------------------------------------------------------------
def flatten(lst):
    return [item for sublist in lst for item in sublist]

# --- Tests
# -----------------------------------------------------------------------------
def test_canvas_empty():
    canvas = Canvas()
    assert canvas._canvas is None

def test_canvas_init_valid(test_canvas):
    assert test_canvas._canvas is not None

def test_canvas_init_invalid():
    with pytest.raises(TypeError):
        Canvas(1.5, 1.6)

    with pytest.raises(TypeError):
        Canvas(1.5)

    with pytest.raises(TypeError):
        Canvas(-5, 10)

    with pytest.raises(TypeError):
        Canvas(5, -10)

    with pytest.raises(TypeError):
        Canvas(0, 0)

    with pytest.raises(TypeError):
        Canvas(0, 10)

    with pytest.raises(TypeError):
        Canvas(10, 0)

def test_canvas_create_valid():
    canvas = Canvas()
    canvas.create(20, 6)
    assert canvas._canvas is not None

def test_canvas_create_invalid():
    canvas = Canvas()

    with pytest.raises(TypeError):
        canvas.create(1.5, 1.6)

    with pytest.raises(TypeError):
        canvas.create(1.5)

    with pytest.raises(TypeError):
        canvas.create(-5, 10)

    with pytest.raises(TypeError):
        canvas.create(5, -10)

    with pytest.raises(TypeError):
        canvas.create(0, 0)

    with pytest.raises(TypeError):
        canvas.create(0, 10)

    with pytest.raises(TypeError):
        canvas.create(10, 0)

def test_canvas_draw_line_valid(test_canvas):
    # Horizontal
    test_canvas.draw_line(1, 1, 2, 1)

    # Vertical
    test_canvas.draw_line(1, 1, 1, 2)

def test_canvas_draw_line_invalid(test_canvas):
    # Oblique
    with pytest.raises(ValueError):
        test_canvas.draw_line(1, 2, 3, 4)

    # Negative
    with pytest.raises(TypeError):
        test_canvas.draw_line(-6, -5, 3, 4)

    # Outside
    with pytest.raises(ValueError):
        test_canvas.draw_line(1, 1, 40, 1)

    with pytest.raises(ValueError):
        test_canvas.draw_line(1, 40, 1, 1)

def test_canvas_draw_rect_valid(test_canvas):
    test_canvas.draw_rectangle(1, 1, 2, 2)
    test_canvas.draw_rectangle(3, 3, 4, 4)

def test_canvas_draw_rect_invalid(test_canvas):
    # Negative
    with pytest.raises(TypeError):
        test_canvas.draw_rectangle(-6, -5, 3, 4)

    # Outside
    with pytest.raises(ValueError):
        test_canvas.draw_rectangle(1, 1, 40, 1)

    with pytest.raises(ValueError):
        test_canvas.draw_rectangle(1, 40, 1, 1)

def test_canvas_fill_valid(test_canvas):
    test_canvas.fill(1, 1, 'p')
    assert flatten(test_canvas._canvas).count('p') == TEST_WIDTH*TEST_HEIGHT

    test_canvas.fill(1, 1, 'l')
    assert flatten(test_canvas._canvas).count('l') == TEST_WIDTH*TEST_HEIGHT

def test_canvas_fill_invalid(test_canvas):
    with pytest.raises(TypeError):
        test_canvas.fill(1, 0, 'p')

    with pytest.raises(ValueError):
        test_canvas.fill(TEST_WIDTH+1, TEST_HEIGHT+1, 'op')

    with pytest.raises(ValueError):
        test_canvas.fill(1, 1, '')

    with pytest.raises(ValueError):
        test_canvas.fill(1, 1, 'op')

def test_canvas_erase(test_canvas):
    test_canvas.draw_line(1, 1, 4, 1)
    assert flatten(test_canvas._canvas).count(None) != TEST_WIDTH*TEST_HEIGHT
    test_canvas.erase()
    assert flatten(test_canvas._canvas).count(None) == TEST_WIDTH*TEST_HEIGHT

def test_canvas_properties(test_canvas):
    assert test_canvas.width == TEST_WIDTH
    assert test_canvas.height == TEST_HEIGHT
    assert len(flatten(test_canvas.data)) == TEST_WIDTH*TEST_HEIGHT
    assert flatten(test_canvas.data).count(None) == TEST_WIDTH*TEST_HEIGHT

def test_canvas_str():
    canvas = Canvas()
    assert canvas.__str__() == '[]'
    assert canvas.__unicode__() == '[]'
    assert canvas.__repr__() == '[]'
    canvas.create(2, 3)
    assert canvas.__str__() == CANVAS_2_3[0]
    assert canvas.__unicode__() == CANVAS_2_3[0]
    assert canvas.__repr__() == CANVAS_2_3[1]

def test_canvas_check():
    canvas = Canvas()
    with pytest.raises(Exception):
        canvas._check_canvas()

    with pytest.raises(Exception):
        canvas.draw_line(1, 1, 2, 1)

    with pytest.raises(Exception):
        canvas.draw_rectangle(1, 1, 3, 3)

    with pytest.raises(Exception):
        canvas.fill(1, 1, 'o')

def test_big_canvas():
    w = 50
    h = w*2
    canvas = Canvas(w, h)
    canvas.fill(1, 1, 's')
    assert flatten(canvas._canvas).count('s') == w*h

def test_canvas_cases():
    canvas = Canvas()
    for TEST_CASE in [TEST_CASE_1, TEST_CASE_2]:
        for ((cmd, cmd_line), expected_canvas) in TEST_CASE:
            eval('canvas.' + cmd)
            assert canvas.__str__() == expected_canvas


import csv
import re
from datetime import date
import sqlite3
import requests
import os
import ConfigParser

###########################
### CONFIGURATION FILE
iniFile = "conf.ini"

############################
### FIELD NAMES
F_TAG = 'tag'
F_DATE = 'date'
F_ROLE = 'role'
F_EXPLEVEL = 'expLevel'
F_TROPHIES = 'trophies'
F_CLANRANK = 'clanRank'
F_DONATIONS = 'donations'
F_DONATIONSRECEIVED = 'donationsReceived'
F_NAME = 'name'
F_PRES = 'presentation'
F_INCLAN = 'inClan'

############################
### DB TABLES
T_HISTORY = 'hist'
T_MEMBER = 'membre'

############################
### global var
inputCsvFile = 'tmpCsvFile.csv'

######################################################################################
## FUNCTIONS
######################################################################################

############################
### initDb()
### Check DB existance and create it
############################
def initDb():
    # init var
    b_history = False
    b_member = False

    # connect db file
    conn = sqlite3.connect(dbFileName)
    c = conn.cursor()

    # get db tables
    c.execute("select * from SQLite_master")
    tables = c.fetchall()

    # parse tables to find T_MEMBER and T_HISTORY
    for table in tables:
        if table[1] == T_MEMBER:
            b_member = True
        if table[1] == T_HISTORY:
            b_history = True

    # if T_MEMBER table doesn't exist, create it
    if b_member == False:
        reqCreate = "CREATE TABLE {}({} text, {} text, {} text, {} int)".format(T_MEMBER,
                                F_TAG, F_NAME, F_PRES, F_INCLAN)
        c.execute(reqCreate)

    # if T_HISTORY table doesn't  exist, create it
    if b_history == False:
        reqCreate = "CREATE TABLE {}({} text, {} text, {} text, {} int, {} int,{} int,{} int,{} int)".format(T_HISTORY,
                                F_TAG, F_DATE, F_ROLE, F_EXPLEVEL, F_TROPHIES, F_CLANRANK, F_DONATIONS, F_DONATIONSRECEIVED)
        c.execute(reqCreate)

    # commit updates
    conn.commit()

    # close db
    conn.close()

############################
### is_downloadable(i_url)
### Check if url return downloadable file
### i :
###     i_url : string : url to check
### r : bolean : (true -> downloadable / false)
############################
def is_downloadable(i_url):
    # request header
    h = requests.head(i_url, allow_redirects=True)
    header = h.headers

    # get the content type
    content_type = header.get('content-type')
    if 'text' in content_type.lower():
        return False
    if 'html' in content_type.lower():
        return False
    return True

############################
### getCsvFile()
### download CSV file on CRAPI
### r : bolean : (true -> downloaded / false)
############################
def getCsvFile():
    # build full URL
    url = apiUrl+clanId+'/'+fileType

    # check if url exists and is downloadable
    if is_downloadable(url) == True:
        # request with GET
        r = requests.get(url)

        # parse content into csv file
        with open(inputCsvFile, 'wb') as f:
            f.write(r.content)

        return True
    return False

############################
### addHistory(i_history, i_conn)
### add history into db
### i :
###    i_history : dictionary list : full history
###    i_con : connector : db connector
############################
def addHistory(i_history, i_conn):
    # get DB cursor
    cursor = i_conn.cursor()

    # for each CVS entry, add as history line into db
    for hisoryLine in i_history:
        createHistoryInput(hisoryLine, cursor)

    # commit updates
    i_conn.commit()

############################
### createHistoryInput(i_hystoryInput, i_cursor):
### add a single history input into db
### i :
###    i_hystoryInput : dictionary : single history
###    i_cursor : cursor : db cursor
############################
def createHistoryInput(i_hystoryInput, i_cursor):
    # create DB request
    reqAdd = '''INSERT INTO {}({},{},{},{},{},{},{},{})
                VALUES ('{}','{}','{}',{},{},{},{},{});'''.format(T_HISTORY,
                 F_TAG, F_DATE, F_ROLE, F_EXPLEVEL, F_TROPHIES, F_CLANRANK, F_DONATIONS, F_DONATIONSRECEIVED,
                 i_hystoryInput[F_TAG], i_hystoryInput[F_DATE], i_hystoryInput[F_ROLE], i_hystoryInput[F_EXPLEVEL],
                 i_hystoryInput[F_TROPHIES], i_hystoryInput[F_CLANRANK], i_hystoryInput[F_DONATIONS], i_hystoryInput[F_DONATIONSRECEIVED])

    # execute reques
    i_cursor.execute(reqAdd)

############################
### createMembers(i_memberList, i_conn)
### add members into db
### i :
###    i_memberList : dictionary list : full members list
###    i_conn : connector : db connector
############################
def createMembers(i_memberList, i_conn):
    # get DB cursor
    cursor = i_conn.cursor()

    # for each member in CSV file, add single member
    for member in i_memberList:
        createMember(member, cursor)

    # commit updates
    i_conn.commit()

############################
### createMember(i_member, i_cursor):
### add a single member input into db
### i :
###    i_member : dictionary : single member
###    i_cursor : cursor : db cursor
############################
def createMember(i_member, i_cursor):

    # build a requestion to know if current user already in the DB
    reqFound = "SELECT * FROM {} WHERE {} = '{}'".format(T_MEMBER, F_TAG, i_member[F_TAG])

    # execute the request
    i_cursor.execute(reqFound)

    # if current member is not in the DB, add him
    if (i_cursor.fetchone() == None):
        # build the add request
        reqAdd = '''INSERT INTO {}({},{},{},{}) VALUES ('{}','{}','',1);'''.format(T_MEMBER,
                    F_TAG, F_NAME, F_PRES, F_INCLAN,
                    i_member[F_TAG], i_member[F_NAME])
        # execute it
        i_cursor.execute(reqAdd)

############################
### memberInClan(i_listeMembres, i_conn):
### check members mouvements (quit clan / return to clan)
### i :
###    i_listeMembres : dictionary list : full members list
###    i_conn : connector : db connector
############################
def memberInClan(i_listeMembres, i_conn):
    # get the DB cursor
    cursor = i_conn.cursor()

    # build the request to get all members mark as in clan in the DB
    reqFound = "SELECT {} FROM {} WHERE {} = {};".format(F_TAG, T_MEMBER, F_INCLAN, 1)

    # for each member in clan
    for row in cursor.execute(reqFound):
        # check if always into the clan in CSV file
        b_found = False
        for member in i_listeMembres:
            if row[0] == member[F_TAG]:
                b_found = True
                break

        # if member quit clan (in DB as inclan and not in clan snapshot)
        if b_found != True:
            # update inclan field in DB (set to 0)
            reqUpdate="UPDATE {} SET {} = {} WHERE {} = '{}';".format(T_MEMBER, F_INCLAN, 0, F_TAG, row[0])
            cursor.execute(reqUpdate)

    # build the request to get all members mark as not in clan in the DB
    reqFound = "SELECT {} FROM {} WHERE {} = {};".format(F_TAG, T_MEMBER, F_INCLAN, 0)

    # for each member in clan
    for row in cursor.execute(reqFound):
        # check if always into the clan in CSV file
        b_found = False
        for member in i_listeMembres:
            if row[0] == member[F_TAG]:
                b_found = True
                break
        # if member return in clan (in DB as not inclan and present in clan snapshot)
        if b_found == True:
            reqUpdate="UPDATE {} SET {} = {} WHERE {} = '{}';".format(T_MEMBER, F_INCLAN, 1, F_TAG, row[0])
            cursor.execute(reqUpdate)

    # commit updates
    i_conn.commit()

############################
### getConfig():
### Read ini file
### r : boolean : true -> ini file read and correct / false
############################
def getConfig():
    # declare global var
    global dbFileName
    global apiUrl
    global clanId
    global fileType

    # read ini file
    config = ConfigParser.ConfigParser()
    config.read(iniFile)

    # try to get each ini files
    # in case of error, return false
    try:
        dbFileName = config.get('DEFAULT', 'dbFileName')
    except:
        return False;
    try:
        apiUrl = config.get('DEFAULT', 'apiUrl')
    except:
        return False;
    try:
        clanId = config.get('DEFAULT', 'clanId')
    except:
        return False;
    try:
        fileType = config.get('DEFAULT', 'fileType')
    except:
        return False;
    return True

############################
### main():
### main function
############################
def main():
    # initialise list of dico
    listeMembers = []
    history = []

    # get current date
    today = date.today()

    # read ini file
    print ("Read INI file: ")
    if getConfig() == True:
        print ("               OK")
        # if successfull, download CSV files
        print ("Download CSV file: ")
        if getCsvFile() == True:
            print ("                  OK")
            # if successfull, parse CSV file
            with open(inputCsvFile) as csvfile:
                reader = csv.DictReader(csvfile)

                # for each CSV row, build member list and history list
                for row in reader:
                    lineMember={F_TAG:row[F_TAG],
                                F_NAME:re.sub("[^a-zA-Z0-9_@ ]", "", row[F_NAME])}

                    lineHistory={F_TAG:row[F_TAG],
                                F_DATE:str(today),
                                F_ROLE:row[F_ROLE],
                                F_EXPLEVEL:int(row[F_EXPLEVEL]),
                                F_TROPHIES:int(row[F_TROPHIES]),
                                F_CLANRANK:int(row[F_CLANRANK]),
                                F_DONATIONS:int(row[F_DONATIONS]),
                                F_DONATIONSRECEIVED:int(row[F_DONATIONSRECEIVED])}
                    listeMembers.append(lineMember)
                    history.append(lineHistory)
            # check or create DB
            initDb()

            # open DB
            conn = sqlite3.connect(dbFileName)

            # add new members in DB
            createMembers(listeMembers, conn)
            # update member presence in clan in DB
            memberInClan(listeMembers, conn)
            # store history in DB
            addHistory(history,conn)

            # close DB
            conn.close()

            # remove temporary CSV file
            os.remove(inputCsvFile)

########################################################
########################################################
### ENTRY POINT
########################################################
########################################################
if __name__ == "__main__":
    main()


import unittest
import numpy as np
from lagrange import interpolate

class LagrangeTest(unittest.TestCase):

  def setUp(self):
    pass

  def test_interpolate(self):
    x  = np.arange(40)

    y1 = x ** 2
    f1 = interpolate(x, y1)
    self.assertListEqual(y1, [f1(xi) for xi in x])

    y2 = np.sin(2 * np.pi * x / len(x))
    f2 = interpolate(x, y2)
    self.assertListEqual(y2, [f2(xi) for xi in x])

    y3 = np.e ** (2 * np.pi * x / len(x))
    f3 = interpolate(x, y3)
    self.assertListEqual(y3, [f3(xi) for xi in x])

  def assertListEqual(self, l1, l2):
    self.assertTrue( np.all(l1 == l2) )

if __name__ == '__main__':
  unittest.main()


from rest_framework.permissions import SAFE_METHODS, BasePermission

class IsAdminOrReadOnly(BasePermission):

    def has_permission(self, request, view):
        if request.user.is_authenticated:
            return (
                request.user.role == 'admin'
                or request.user.is_staff
                or request.user.is_superuser
            )
        if request.method in SAFE_METHODS:
            return True


# imports
from influxdb import InfluxDBClient
from datetime import datetime
from datetime import timedelta
import tkinter
import plotly.offline as py
import plotly.graph_objs as go
import plotly.io.orca
from tkinter import messagebox
from tkinter.filedialog import *
from dateutil.relativedelta import relativedelta

dateFormat = "%Y-%m-%dT%H:%M:%SZ"
dateFormatWithoutT = "%Y-%m-%d %H:%M:%S"
dateFormatLite = "%Y-%m-%d"
dateFormatHours = "%H:%M"
# Verbindung zur Datenbank
databases = None
layout = None
# noinspection PyBroadException
try:
    client = InfluxDBClient(host='localhost', port=8086)
    databases = client.get_list_database()
except:
    messagebox.showerror("Datenbankverbindung fehlgeschlagen",
                         "Es konnte keine Verbindung zur Datenbank hergestellt werden." +
                         "Bitte starten Sie die Datenbank und versuchen Sie es erneut")
    sys.exit()

databaseNames = [d['name'] for d in databases]
if "test" in databaseNames:
    client.switch_database('test')
else:
    client.create_database('test')

traceList = []
calendarDateFrom = datetime.now()
calendarDateTo = datetime.now()
monthList = ["Jaenner", "Februar", "Maerz", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober",
             "November", "Dezember"]

def getDays():
    dataList = []
    timeList = []
    counter = 0
    sqlString = "Select sum(" + str(channel) + ") from " + str(customer.get()) + " where time >= '" + str(year) + \
                "-01-01' and time <= '" + str(year) \
                + "-12-31 23:59:59' group by time(1d)"
    rs = list(client.query(sqlString).get_points())
    for i in rs:
        if i['sum'] is None:
            dataList.append(0)
        else:
            dataList.append("%.2f" % i['sum'])
        counter += 1
        timeList.append(counter)
    traceList.append(go.Bar(
        x=timeList,
        y=dataList,
        name="Sum",
        marker=dict(
            color='#0069B4'
        )
    ))

def getWeeks():
    setCalendarWeek()
    dateFromNew = calendarDateFrom
    dateToNew = dateFromNew + timedelta(days=7)
    dataList = []
    timeList = []
    counter = 0
    while dateToNew <= calendarDateTo:
        sqlString = "Select sum(" + str(channel) + ") from " + str(customer.get()) + " where time >= '" + \
                    dateFromNew.strftime(dateFormatLite) + "' and time <= '" + dateToNew.strftime(dateFormatLite) + "'"
        rs = list(client.query(sqlString).get_points())
        if rs[0]['sum'] is None:
            dataList.append(0)
        else:
            dataList.append(rs[0]['sum'])
        counter += 1
        timeList.append(counter)
        dateToNew = dateToNew + timedelta(days=7)
        dateFromNew = dateFromNew + timedelta(days=7)
    traceList.append(go.Bar(
        x=timeList,
        y=dataList,
        name="Sum",
        marker=dict(
            color='#0069B4'
        )
    ))

def getMonths():
    dataList = []
    timeList = []
    referenceDate = datetime(int(year), 1, 1)
    for i in range(12):
        newDate1 = referenceDate + relativedelta(months=+ i)
        newDate2 = referenceDate + relativedelta(months=+ (i + 1))
        sqlString = "Select sum(" + str(channel) + ") from " + str(customer.get()) + " where time >= '" + \
                    str(newDate1.strftime(dateFormatLite)) + \
                    "' and time <= '" + str(newDate2.strftime(dateFormatLite)) + "'"
        rs = list(client.query(sqlString).get_points())
        if rs:
            dataList.append(rs[0]["sum"])
        else:
            dataList.append(0)
        timeList.append(newDate1.strftime(dateFormatLite))
    traceList.append(go.Bar(
        x=monthList,
        y=dataList,
        name="Sum",
        marker=dict(
            color='#0069B4'
        )
    ))

def validateMeasurementName(measurementNameEntry):
    customerNames = client.get_list_measurements()
    nameList = [d['name'] for d in customerNames]
    if measurementNameEntry.get() in nameList:
        return True
    else:
        return False

def getDataForDropdownList():
    rs = list(client.query("SELECT * from " + customer.get() + " limit 1").get_points())
    dropdowndataList = list(rs[0].keys())

    for i in range(len(dropdowndataList)):
        if dropdowndataList[i] == "time":
            del dropdowndataList[i]
            break

    for i in range(len(dropdowndataList)):
        if dropdowndataList[i] == "GeraeteNummer":
            del dropdowndataList[i]
            break

    for i in range(len(dropdowndataList)):
        if dropdowndataList[i] == "Wochentag":
            del dropdowndataList[i]
            break

    return dropdowndataList

def setCalendarWeek():
    global calendarDateFrom
    global calendarDateTo
    x = datetime(int(year), 1, 1)
    # Situation: 1.1 befindet sich in der Kalenderwoche des letzten Jahres
    while int(x.strftime('%V')) > 1:
        x = x + timedelta(days=1)

    # Situation: 1.1 befindet sich in der ersten Kalenderwoche des Jahres aber ist nicht der erste Tag der Woche
    while int(x.strftime('%V')) == 1 and x.weekday() != 0:
        x = x - timedelta(days=1)

    calendarDateFrom = x

    y = datetime(int(year), 12, 31)
    # Situation: 31.12 befindet sich in der ersten Kalenderwoche des nächsten Jahres
    while int(y.strftime('%V')) == 1:
        y = y - timedelta(days=1)

    # Situation: 31.12 befindet sich in der letzten Kalenderwoche
    while int(y.strftime('%V')) != 1:
        y = y + timedelta(days=1)

    calendarDateTo = y

def checkMeasurementEvent(event):
    global dropdowndata
    if validateMeasurementName(customer):
        dropdowndata = getDataForDropdownList()
        menu = omKanal["menu"]
        menu.delete(0, "end")
        for string in dropdowndata:
            menu.add_command(label=string,
                             command=lambda value=string:
                             omKanalVar.set(value))
        omKanal.configure(state="active")
        bt2.configure(state="active")
    else:
        messagebox.showerror("Fehler", "Kundenname wurde nicht gefunden. Bitte versuchen Sie es erneut")
        ent0.focus()

def plot():
    fig = go.Figure(data=traceList, layout=layout)
    if entNameVar.get() is "":
        py.plot(fig, show_link=False)
    else:
        plotly.io.write_image(fig, entNameVar.get() + '.png', format='png')
        py.plot(fig, filename=entNameVar.get() + '.html', show_link=False)

def addLayoutWithoutRange():
    global layout
    global omVar23

    if omVar23.get() == intervallList[0]:
        layout = go.Layout(
            title="Monats-Verbraeuche",
            barmode='overlay',
            xaxis=dict(
                anchor='x1',
                type="category",
                title="Monat",
            ),
            yaxis=dict(
                scaleanchor="y",
                title="Verbrauch [kWh]",

            )
        )
    elif omVar23.get() == intervallList[1]:
        layout = go.Layout(
            title="Wochen-Verbraeuche",
            barmode='overlay',
            xaxis=dict(
                anchor='x1',
                type="category",
                title="Kalenderwochen",
            ),
            yaxis=dict(
                scaleanchor="y",
                title="Verbrauch [kWh]",
            )
        )
    else:
        layout = go.Layout(
            title="Tages-Verbraeuche",
            barmode='overlay',
            xaxis=dict(
                anchor='x1',
                type="category",
                title="Tage",
            ),
            yaxis=dict(
                scaleanchor="y",
                title="Verbrauch [kWh]",

            )
        )

def addLayoutWithRange():
    global layout
    global omVar23

    if omVar23.get() == intervallList[0]:
        layout = go.Layout(
            title="Monats-Verbraeuche",
            barmode='overlay',
            xaxis=dict(
                anchor='x1',
                type="category",
                title="Monat",
            ),
            yaxis=dict(
                scaleanchor="y",
                title="Verbrauch [kWh]",
                range=[0, int(entYAchse.get())]
            )
        )
    elif omVar23.get() == intervallList[1]:
        layout = go.Layout(
            title="Wochen-Verbraeuche",
            barmode='overlay',
            xaxis=dict(
                anchor='x1',
                type="category",
                title="Kalenderwochen",
            ),
            yaxis=dict(
                scaleanchor="y",
                title="Verbrauch [kWh]",
                range=[0, int(entYAchse.get())]
            )
        )
    else:
        layout = go.Layout(
            title="Tages-Verbraeuche",
            barmode='overlay',
            xaxis=dict(
                anchor='x1',
                type="category",
                title="Tage",
            ),
            yaxis=dict(
                scaleanchor="y",
                title="Verbrauch [kWh]",
                range=[0, int(entYAchse.get())]
            )
        )

def visualise():
    global channel
    global dropdowndata
    global year
    traceList.clear()
    channel = omKanalVar.get()
    year = entJahr.get()
    if omVar23.get() == intervallList[0]:
        getMonths()
    elif omVar23.get() == intervallList[1]:
        getWeeks()
    else:
        getDays()
    if entYAchse.get() is "":
        addLayoutWithoutRange()
    else:
        addLayoutWithRange()
    plot()

# Hauptframe
mainFrame = tkinter.Tk()
mainFrame.wm_title("Summierte Visualisierung")

# Groesse bestimmen
fr0 = tkinter.Frame(mainFrame)
fr0.pack()

customer = StringVar()

fr1 = tkinter.Frame(fr0)
fr1.pack()
lb0 = tkinter.Label(fr1, text="Name der Messung:", anchor="w")
lb0.pack(padx=15, pady=5)
ent0 = tkinter.Entry(fr1, width=30, textvariable=customer)
ent0.bind("<FocusOut>", checkMeasurementEvent)
ent0.pack(fill="x", expand=1, padx=5, pady=5)

separator2 = Frame(fr1, height=2, bd=1, relief=SUNKEN)
separator2.pack(fill=X, padx=1, pady=5)

frJahr = tkinter.Frame(fr0)
frJahr.pack(expand=1, fill="x")
lbJahr = tkinter.Label(frJahr, text="Jahr:", anchor="w")
lbJahr.pack(padx=10)

frEntJahr = tkinter.Frame(fr0)
frEntJahr.pack(expand=1, fill="x")
jahrVar = StringVar()
entJahr = tkinter.Entry(frEntJahr, width=15, textvariable=jahrVar)
entJahr.pack(expand=1, padx=5)

separator = Frame(fr0, height=2, bd=1, relief=SUNKEN)
separator.pack(fill=X, padx=1, pady=10)

fr2 = tkinter.Frame(fr0)
fr2.pack(expand=1, fill="x")
lb3 = tkinter.Label(fr2, text="Darstellung auswaehlen:", anchor="w")
lb3.pack(padx=15, pady=5)

omVar23 = tkinter.StringVar()
intervallList = ["Monate", "Wochen", "Tage"]
omVar23.set(intervallList[0])
fr23 = tkinter.Frame(fr0)
fr23.pack(expand=1, fill="x")
om3 = tkinter.OptionMenu(fr23, omVar23, *intervallList)
om3.pack()

separator4 = Frame(fr23, height=2, bd=1, relief=SUNKEN)
separator4.pack(fill=X, padx=1, pady=10)

lbYAchse = tkinter.Label(fr23, text="Obere Grenze der Y-Achse:")
lbYAchse.pack(padx=15, pady=5)
yAchseVar = tkinter.StringVar()
entYAchse = tkinter.Entry(fr23, width=15, textvariable=yAchseVar)
entYAchse.pack(expand=1, pady=5)

lbYAchse = tkinter.Label(fr23, text="Kanal:")
lbYAchse.pack(padx=15)
dropdowndata = ["asdf"]
omKanalVar = tkinter.StringVar()
omKanalVar.set("Kanal auswaehlen")
omKanal = tkinter.OptionMenu(fr23, omKanalVar, *dropdowndata)
omKanal.pack(padx=10, pady=5)
omKanal.configure(state="disabled")

frName = tkinter.Frame(fr0)
frName.pack(padx=5, pady=5)
entNameVar = StringVar()
lbName = tkinter.Label(frName, text="Dateiname:")
lbName.pack(padx=5)
entName = tkinter.Entry(frName, width=15, textvariable=entNameVar)
entName.pack(padx=5, pady=5)

separator5 = Frame(fr0, height=2, bd=1, relief=SUNKEN)
separator5.pack(fill=X, padx=1, pady=10)

fr4 = tkinter.Frame(fr0)
fr4.pack(expand=1, fill="x")
bt2 = tkinter.Button(fr4, text="Visualisieren", width=15, command=visualise)
bt2.pack(padx=10, pady=5)
bt2.configure(state="disabled")

mainFrame.mainloop()